0

I'm trying to use libavcodec to encode a flv video. Following code is a sample code to generate a mpeg video, it works well. But after replacing the codec ID with AV_CODEC_ID_FLV1, the generated video file cannot be played.

void simpleEncode(){
    AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_MPEG1VIDEO);
    AVCodecContext *ctx = avcodec_alloc_context3(codec);
    ctx->bit_rate = 400000;
    ctx->width = 352;
    ctx->height = 288;
    AVRational time_base = {1,25};
    ctx->time_base = time_base;
    ctx->gop_size = 10;
    ctx->pix_fmt = AV_PIX_FMT_YUV420P;

    avcodec_open2(ctx, codec, NULL);

    AVFrame *frame = av_frame_alloc();
    av_image_alloc(frame->data, frame->linesize, ctx->width, ctx->height, ctx->pix_fmt, 32);
    frame->format = ctx->pix_fmt;
    frame->height = ctx->height;
    frame->width = ctx->width;

    AVPacket pkt;
    int got_output;
    FILE *f = fopen("test.mpg", "wb");
    for(int i=0; i<25; i++){
        av_init_packet(&pkt);
        pkt.data = NULL;
        pkt.size = 0;

        for(int w=0; w<ctx->width; w++){
            for(int h=0; h<ctx->height; h++){
                frame->data[0][h*frame->linesize[0]+w]=i*10;
            }
        }
        for(int w=0; w<ctx->width/2; w++){
            for(int h=0; h<ctx->height/2; h++){
                frame->data[1][h*frame->linesize[1]+w]=i*10;
                frame->data[2][h*frame->linesize[2]+w]=i*10;
            }
        }

        frame->pts=i;
        avcodec_encode_video2(ctx, &pkt, frame, &got_output);

        fwrite(pkt.data, 1, pkt.size, f);
    }
}
Mark Ma
  • 1,342
  • 3
  • 19
  • 35

1 Answers1

0

AV_CODEC_ID_FLV1 is a poorly named macro. It refers to the Sorenson H.263 codec. It at one time was the default codec for the FLV container format, but no longer is. It was replaced with VP6 and now h.264. Except for this history it has no relation to the flv container format.

An mpeg1 stream is an odd thing in that its elementary stream format is also a valid container. This is not the case for h.263. You can not simply write the packets to disk and play them back. You must encapsulate the ES into a container. The easiest way to do that is use libavformat.

szatmary
  • 29,969
  • 8
  • 44
  • 57