Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int VideoTest::convert_first_frame_to_png(const char* inputVideoFileName, const char*
- outputPngName)
- {
- av_register_all();
- avcodec_register_all();
- avformat_network_init();
- av_log_set_level(AV_LOG_DEBUG); // debugging info
- ::AVFormatContext * ctx = NULL;
- int err = avformat_open_input(&ctx, inputVideoFileName, NULL, NULL);
- CHECK_ERR(err);
- err = av_find_stream_info(ctx);
- CHECK_ERR(err);
- AVCodec * codec = NULL;
- int strm = av_find_best_stream(ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
- AVCodecContext * codecCtx = ctx->streams[strm]->codec;
- err = avcodec_open2(codecCtx, codec, NULL);
- CHECK_ERR(err);
- SwsContext * swCtx = sws_getContext(
- codecCtx->width,
- codecCtx->height,
- codecCtx->pix_fmt,
- 640,
- 480,
- PIX_OUT_FORMAT,
- SWS_FAST_BILINEAR, 0, 0, 0);
- for (;;)
- {
- AVPacket pkt;
- err = av_read_frame(ctx, &pkt);
- CHECK_ERR(err);
- if (pkt.stream_index == strm)
- {
- int got = 0;
- AVFrame * frame = avcodec_alloc_frame();
- err = avcodec_decode_video2(codecCtx, frame, &got, &pkt);
- CHECK_ERR(err);
- if (got)
- {
- AVFrame * rgbFrame = avcodec_alloc_frame();
- avpicture_alloc((AVPicture *)rgbFrame, PIX_OUT_FORMAT, 640, 480);
- sws_scale(swCtx, frame->data, frame->linesize, 0, frame->height, rgbFrame->data, rgbFrame->linesize);
- AVCodec *outCodec = avcodec_find_encoder(AV_CODEC_ID_PNG);
- AVCodecContext *outCodecCtx = avcodec_alloc_context3(outCodec);
- outCodecCtx->width = 640;
- outCodecCtx->height = 480;
- outCodecCtx->pix_fmt = PIX_OUT_FORMAT;
- outCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
- outCodecCtx->time_base.num = codecCtx->time_base.num;
- outCodecCtx->time_base.den = codecCtx->time_base.den;
- CheckResult("Open PNG codec", avcodec_open2(outCodecCtx, outCodec, NULL));
- if (!outCodec) return -1;
- int res = avcodec_open2(outCodecCtx, outCodec, NULL);
- if (res < 0) return -1;
- AVPacket outPacket;
- av_init_packet(&outPacket);
- outPacket.size = 0;
- outPacket.data = NULL;
- int gotFrame = 0;
- int ret = avcodec_encode_video2(outCodecCtx, &outPacket, rgbFrame, &gotFrame);
- if (ret >= 0 && gotFrame)
- {
- FILE * outPng = fopen(outputPngName, "wb");
- fwrite(outPacket.data, outPacket.size, 1, outPng);
- fclose(outPng);
- }
- avcodec_close(outCodecCtx);
- av_free(outCodecCtx);
- break;
- }
- avcodec_free_frame(&frame);
- }
- }
- avformat_network_deinit();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement