Wrap h264 stream to mp4 container

Examples and samples for those who develop software with FFmpeg.
Post Reply
plobovikov
Posts: 2
Joined: Thu Dec 13, 2018 2:26 pm

Wrap h264 stream to mp4 container

Post by plobovikov » Thu Dec 13, 2018 2:33 pm

Hi all!

I have a collection of h264 video frames + collection of amr_nb audio frames in my program.

I need to wrap this collections in video file with .mp4 extension.

can anyone provide an example of how to do this?

My sample code following:

Code: Select all

static AVStream *add_audio_stream(AVFormatContext *oc, AVCodecID codec_id)
{
    AVCodecParameters *c;
    AVStream *st;

    st = avformat_new_stream(oc, NULL);
    st->id = 1;
    if (!st) {
        fprintf(stderr, "Could not alloc stream\n");
        exit(1);
    }

    c = st->codecpar;
    c->codec_id = codec_id;
    c->codec_type = AVMEDIA_TYPE_AUDIO;

    /* put sample parameters */
    c->bit_rate = 64000;
    c->sample_rate = 44100;
    c->channels = 2;

    return st;
}
static AVStream *add_video_stream(AVFormatContext *oc, AVCodecID codec_id)
{
    AVCodecParameters *c;
    AVStream *st;

    st = avformat_new_stream(oc, NULL);
    if (!st) {
        fprintf(stderr, "Could not alloc stream\n");
        exit(1);
    }
    st->id = 0;
    c = st->codecpar;
    c->codec_id = codec_id;
    c->codec_type = AVMEDIA_TYPE_VIDEO;

    /* put sample parameters */
    c->bit_rate = 400000;
    /* resolution must be a multiple of two */
    c->width = 1366;
    c->height = 780;
   
    return st;
}

    av_register_all();
    AVOutputFormat *format = av_guess_format(NULL, filename, NULL);
    AVFormatContext *formatContext = avformat_alloc_context();
    formatContext->oformat = format;
    AVStream *audio_st, *video_st;

    audio_st = add_audio_stream(formatContext,  format->audio_codec);
    video_st = add_video_stream(formatContext, format->video_codec);
    avio_open(&formatContext->pb, filename, AVIO_FLAG_WRITE);
    avformat_write_header(formatContext , NULL);
    
    //read frames from stream cycle
    		AVPacket pkt = { 0 };
		av_init_packet(&pkt);

   		pkt.data = frame->data;  //frame data
		pkt.size = frame->dataLength;
		
		pkt.stream_index = (frame->type == e_Audio ? audio_st->index : video_st->index);
		av_interleaved_write_frame(formatContext, &pkt);
		
	//clear resources

Actually, my output video is not good and doesn't have sound.

Plese, help me

Post Reply