I started using ffmpeg and I want to convert avi file to mp4/h264 file. I've read many posts including this, but I couldn't find any good example how to save frames to mp4 file. The code below is simplified one that decodes frames from avi file and encode it to H264/mp4 file, but when I save the frames the mp4 file cannot be played. I think I do somethinkg wrong in encoding
I will appreciate if you could tell me what is wrong and how to fix it.
const char* aviFileName = "aviFrom.avi";
const char* mp4FileName = "mp4To.mp4";
// Filling pFormatCtx by open video file and Retrieve stream information
// ...
// Retrieving codecCtxDecode and opening codecDecode
//...
// Get encoder
codecCtxEncode = avcodec_alloc_context();
codecCtxEncode->qmax = 69;
codecCtxEncode->max_qdiff = 4;
codecCtxEncode->bit_rate = 400000;
codecCtxEncode->width = codecCtxDecode->width;
codecCtxEncode->height = codecCtxDecode->height;
codecCtxEncode->pix_fmt = AV_PIX_FMT_YUV420P;
codecEncode = avcodec_find_encoder(CODEC_ID_H264);
if(codecEncode == NULL)
return -1;
if(avcodec_open2(codecCtxEncode, codecEncode, NULL))
return -1;
SwsContext *sws_ctx = sws_getContext(codecCtxDecode->width, codecCtxDecode->height, codecCtxDecode->pix_fmt,
codecCtxDecode->width, codecCtxDecode->height, AV_PIX_FMT_YUV420P,
SWS_BILINEAR, NULL, NULL, NULL);
// Allocate an AVFrame structure
frameDecoded = avcodec_alloc_frame();
frameEncoded = avcodec_alloc_frame();
avpicture_alloc((AVPicture *)frameEncoded, AV_PIX_FMT_YUV420P, codecCtxDecode->width, codecCtxDecode->height);
while(av_read_frame(pFormatCtx, &packet)>=0)
{
// Is this a packet from the video stream?
if(packet.stream_index==videoStreamIndex) {
avcodec_decode_video2(codecCtxDecode, frameDecoded, &frameFinished, &packet);
// Did we get a video frame?
if(frameFinished)
{
fwrite(packet.data, packet.size,
sws_scale(sws_ctx, frameDecoded->data, frameDecoded->linesize, 0, codecCtxDecode->height,
frameEncoded->data, frameEncoded->linesize);
int64_t pts = packet.pts;
av_free_packet(&packet);
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
frameEncoded->pts = pts;
int failed = avcodec_encode_video2(codecCtxEncode, &packet, frameEncoded, &got_output);
if(failed)
{
exit(1);
}
fwrite(packet.data,1,packet.size, mp4File);
}
}
av_free_packet(&packet);
}
You have to use ffmpeg output context, instead of writing raw packets directly.
The basic steps you need to perform:
UPD: The full code that copies the video without re-encoding: