Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <libavcodec/avcodec.h>
- #include <libavformat/avformat.h>
- #include <libswscale/swscale.h>
- #define CONTAINER_FORMAT "matroska"
- #define VIDEO_FILENAME "test.mkv"
- #define WIDTH 640
- #define HEIGHT 480
- #define PIX_FMT_IN PIX_FMT_YUV420P
- #define PIX_FMT_OUT PIX_FMT_RGB24
- int
- main(void)
- {
- AVInputFormat *format;
- AVFormatContext *format_ctx;
- AVCodec *codec, *image_codec;
- AVCodecContext *codec_ctx, *image_codec_ctx;
- avcodec_register_all();
- av_register_all();
- format = av_find_input_format(CONTAINER_FORMAT);
- if (format == NULL) return 1;
- format_ctx = avformat_alloc_context();
- if (avformat_open_input(&format_ctx, VIDEO_FILENAME, format, NULL) != 0) return 1;
- codec_ctx = format_ctx->streams[0]->codec;
- codec = avcodec_find_decoder(codec_ctx->codec_id);
- if (codec == NULL) return 1;
- if (codec->capabilities & CODEC_CAP_TRUNCATED) {
- codec_ctx->flags |= CODEC_FLAG_TRUNCATED;
- }
- if (avcodec_open2(codec_ctx, codec, NULL) != 0) return 1;
- image_codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
- if (image_codec == NULL) return 1;
- image_codec_ctx = avcodec_alloc_context3(image_codec);
- if (image_codec_ctx == NULL) return 1;
- image_codec_ctx->pix_fmt = AV_PIX_FMT_RGB24;
- image_codec_ctx->width = WIDTH;
- image_codec_ctx->height = HEIGHT;
- if (avcodec_open2(image_codec_ctx, image_codec, NULL) != 0) return 1;
- struct SwsContext *img_convert_ctx = sws_getContext(
- WIDTH, HEIGHT, PIX_FMT_IN,
- WIDTH, HEIGHT, PIX_FMT_OUT,
- SWS_FAST_BILINEAR, NULL, NULL, NULL
- );
- AVFrame *frame = avcodec_alloc_frame();
- int got_frame, got_packet;
- AVPacket packet;
- av_init_packet(&packet);
- packet.data = NULL;
- packet.size = 0;
- AVFrame *frame2 = avcodec_alloc_frame();
- int buf_size = avpicture_get_size(PIX_FMT_OUT, WIDTH, HEIGHT);
- uint8_t *buf = malloc(buf_size);
- avpicture_fill(
- (AVPicture *)frame2,
- buf,
- PIX_FMT_OUT,
- WIDTH, HEIGHT
- );
- while (av_read_frame(format_ctx, &packet) >= 0) {
- if (avcodec_decode_video2(codec_ctx, frame, &got_frame, &packet) < 0) return 1;
- if (got_frame) {
- sws_scale(
- img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,
- 0, HEIGHT,
- frame2->data, frame2->linesize
- );
- av_init_packet(&packet);
- packet.data = NULL;
- packet.size = 0;
- /* If this next block is commented out, valgrind shows no invalid reads
- * or use of uninitialized values.
- */
- if (avcodec_encode_video2(image_codec_ctx, &packet, frame2, &got_packet) < 0) return 1;
- printf("### packet size: %d\n", packet.size);
- if (got_packet) {
- int fd = open("frame.png", O_CREAT|O_WRONLY|O_TRUNC, 0600);
- write(fd, packet.data, packet.size);
- close(fd);
- }
- break; /* just process one frame */
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement