1 #include "image_input.h"
3 #include <movit/image_format.h>
6 #include <libavcodec/avcodec.h>
7 #include <libavformat/avformat.h>
8 #include <libavutil/imgutils.h>
9 #include <libavutil/pixfmt.h>
10 #include <libswscale/swscale.h>
15 ImageInput::ImageInput(const std::string &filename)
16 : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
17 GL_UNSIGNED_BYTE, 1280, 720) // FIXME
19 AVFormatContext *format_ctx = nullptr;
20 if (avformat_open_input(&format_ctx, filename.c_str(), nullptr, nullptr) != 0) {
21 fprintf(stderr, "%s: Error opening file\n", filename.c_str());
25 if (avformat_find_stream_info(format_ctx, nullptr) < 0) {
26 fprintf(stderr, "%s: Error finding stream info\n", filename.c_str());
30 int stream_index = -1;
31 for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
32 if (format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
37 if (stream_index == -1) {
38 fprintf(stderr, "%s: No video stream found\n", filename.c_str());
42 AVCodecContext *codec_ctx = format_ctx->streams[stream_index]->codec;
43 AVCodec *codec = avcodec_find_decoder(codec_ctx->codec_id);
44 if (codec == nullptr) {
45 fprintf(stderr, "%s: Cannot find decoder\n", filename.c_str());
48 if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
49 fprintf(stderr, "%s: Cannot open decoder\n", filename.c_str());
53 // Read packets until we have a frame.
54 int frame_finished = 0;
55 AVFrame *frame = av_frame_alloc();
61 if (av_read_frame(format_ctx, &pkt) < 0) {
62 fprintf(stderr, "%s: Cannot read frame\n", filename.c_str());
65 if (pkt.stream_index != stream_index) {
69 if (avcodec_decode_video2(codec_ctx, frame, &frame_finished, &pkt) < 0) {
70 fprintf(stderr, "%s: Cannot decode frame\n", filename.c_str());
73 } while (!frame_finished);
75 // TODO: Scale down if needed!
77 avpicture_alloc(&pic, PIX_FMT_RGBA, frame->width, frame->height);
78 SwsContext *sws_ctx = sws_getContext(frame->width, frame->height,
79 (PixelFormat)frame->format, frame->width, frame->height,
80 PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr);
81 if (sws_ctx == nullptr) {
82 fprintf(stderr, "%s: Could not create scaler context\n", filename.c_str());
85 sws_scale(sws_ctx, frame->data, frame->linesize, 0, frame->height, pic.data, pic.linesize);
86 sws_freeContext(sws_ctx);
88 size_t len = frame->width * frame->height * 4;
89 image_data.reset(new uint8_t[len]);
90 av_image_copy_to_buffer(image_data.get(), len, pic.data, pic.linesize, PIX_FMT_RGBA, frame->width, frame->height, 1);
91 set_pixel_data(image_data.get());