1 #include "image_input.h"
4 #include <movit/flat_input.h>
5 #include <movit/image_format.h>
12 #include <libavcodec/avcodec.h>
13 #include <libavformat/avformat.h>
14 #include <libavutil/avutil.h>
15 #include <libavutil/error.h>
16 #include <libavutil/frame.h>
17 #include <libavutil/imgutils.h>
18 #include <libavutil/mem.h>
19 #include <libavutil/pixfmt.h>
20 #include <libswscale/swscale.h>
33 #include "shared/ffmpeg_raii.h"
34 #include "ffmpeg_util.h"
41 ImageInput::ImageInput(const string &filename)
42 : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
43 GL_UNSIGNED_BYTE, 1280, 720), // Resolution will be overwritten.
44 pathname(search_for_file_or_die(filename)),
45 current_image(load_image(filename, pathname))
47 if (current_image == nullptr) { // Could happen even though search_for_file() returned.
48 fprintf(stderr, "Couldn't load image, exiting.\n");
51 set_width(current_image->width);
52 set_height(current_image->height);
53 set_pixel_data(current_image->pixels.get());
56 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
58 // See if the background thread has given us a new version of our image.
59 // Note: The old version might still be lying around in other ImageInputs
60 // (in fact, it's likely), but at least the total amount of memory used
61 // is bounded. Currently we don't even share textures between them,
62 // so there's a fair amount of OpenGL memory waste anyway (the cache
63 // is mostly there to save startup time, not RAM).
65 lock_guard<mutex> lock(all_images_lock);
66 if (all_images[pathname] != current_image) {
67 current_image = all_images[pathname];
68 set_pixel_data(current_image->pixels.get());
71 movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
74 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
76 lock_guard<mutex> lock(all_images_lock); // Held also during loading.
77 if (all_images.count(pathname)) {
78 return all_images[pathname];
81 all_images[pathname] = load_image_raw(pathname);
82 timespec first_modified = all_images[pathname]->last_modified;
83 update_threads[pathname] =
84 thread(bind(update_thread_func, filename, pathname, first_modified));
86 return all_images[pathname];
89 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
91 // Note: Call before open, not after; otherwise, there's a race.
92 // (There is now, too, but it tips the correct way. We could use fstat()
93 // if we had the file descriptor.)
95 if (stat(pathname.c_str(), &buf) != 0) {
96 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
99 timespec last_modified = buf.st_mtim;
101 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
102 if (format_ctx == nullptr) {
103 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
107 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
108 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
112 int stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
113 if (stream_index == -1) {
114 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
118 const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
119 AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
120 if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
121 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
124 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
125 if (codec == nullptr) {
126 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
129 if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
130 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
133 unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
134 codec_ctx.get(), avcodec_close);
136 // Read packets until we have a frame or there are none left.
137 int frame_finished = 0;
138 AVFrameWithDeleter frame = av_frame_alloc_unique();
142 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
143 &pkt, av_packet_unref);
144 av_init_packet(&pkt);
147 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
148 if (pkt.stream_index != stream_index) {
151 if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
152 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
156 eof = true; // Or error, but ignore that for the time being.
159 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
161 frame_finished = true;
163 } else if (err != AVERROR(EAGAIN)) {
164 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
169 if (!frame_finished) {
170 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
174 uint8_t *pic_data[4] = {nullptr};
175 unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
176 &pic_data[0], av_freep);
178 if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
179 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
182 unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
183 sws_getContext(frame->width, frame->height,
184 (AVPixelFormat)frame->format, frame->width, frame->height,
185 AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
187 if (sws_ctx == nullptr) {
188 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
191 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
193 size_t len = frame->width * frame->height * 4;
194 unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
195 av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
197 shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), move(image_data), last_modified});
201 // Fire up a thread to update the image every second.
202 // We could do inotify, but this is good enough for now.
203 void ImageInput::update_thread_func(const std::string &filename, const std::string &pathname, const timespec &first_modified)
205 char thread_name[16];
206 snprintf(thread_name, sizeof(thread_name), "Update_%s", filename.c_str());
207 pthread_setname_np(pthread_self(), thread_name);
209 timespec last_modified = first_modified;
213 unique_lock<mutex> lock(threads_should_quit_mu);
214 threads_should_quit_modified.wait_for(lock, chrono::seconds(1), []() { return threads_should_quit; });
217 if (threads_should_quit) {
221 if (stat(pathname.c_str(), &buf) != 0) {
222 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
225 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
226 buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
230 shared_ptr<const Image> image = load_image_raw(pathname);
231 if (image == nullptr) {
232 fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
235 fprintf(stderr, "Loaded new version of %s from disk.\n", pathname.c_str());
236 lock_guard<mutex> lock(all_images_lock);
237 all_images[pathname] = image;
238 last_modified = image->last_modified;
242 void ImageInput::shutdown_updaters()
245 lock_guard<mutex> lock(threads_should_quit_mu);
246 threads_should_quit = true;
247 threads_should_quit_modified.notify_all();
249 for (auto &it : update_threads) {
254 mutex ImageInput::all_images_lock;
255 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
256 map<string, thread> ImageInput::update_threads;
257 mutex ImageInput::threads_should_quit_mu;
258 bool ImageInput::threads_should_quit = false;
259 condition_variable ImageInput::threads_should_quit_modified;