1 #include "image_input.h"
4 #include <movit/image_format.h>
11 #include <libavcodec/avcodec.h>
12 #include <libavformat/avformat.h>
13 #include <libavutil/avutil.h>
14 #include <libavutil/error.h>
15 #include <libavutil/frame.h>
16 #include <libavutil/imgutils.h>
17 #include <libavutil/mem.h>
18 #include <libavutil/pixfmt.h>
19 #include <libswscale/swscale.h>
32 #include "ffmpeg_raii.h"
34 #include "flat_input.h"
42 string search_for_file(const string &filename)
44 // Look for the file in all theme_dirs until we find one;
45 // that will be the permanent resolution of this file, whether
46 // it is actually valid or not.
47 // We store errors from all the attempts, and show them
48 // once we know we can't find any of them.
49 vector<string> errors;
50 for (const string &dir : global_flags.theme_dirs) {
51 string pathname = dir + "/" + filename;
52 if (access(pathname.c_str(), O_RDONLY) == 0) {
56 snprintf(buf, sizeof(buf), "%s: %s", pathname.c_str(), strerror(errno));
57 errors.push_back(buf);
61 for (const string &error : errors) {
62 fprintf(stderr, "%s\n", error.c_str());
64 fprintf(stderr, "Couldn't find %s in any directory in --theme-dirs, exiting.\n",
71 ImageInput::ImageInput(const string &filename)
72 : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
73 GL_UNSIGNED_BYTE, 1280, 720), // Resolution will be overwritten.
75 pathname(search_for_file(filename)),
76 current_image(load_image(filename, pathname))
78 if (current_image == nullptr) { // Could happen even though search_for_file() returned.
79 fprintf(stderr, "Couldn't load image, exiting.\n");
82 set_width(current_image->width);
83 set_height(current_image->height);
84 set_pixel_data(current_image->pixels.get());
87 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
89 // See if the background thread has given us a new version of our image.
90 // Note: The old version might still be lying around in other ImageInputs
91 // (in fact, it's likely), but at least the total amount of memory used
92 // is bounded. Currently we don't even share textures between them,
93 // so there's a fair amount of OpenGL memory waste anyway (the cache
94 // is mostly there to save startup time, not RAM).
96 unique_lock<mutex> lock(all_images_lock);
97 if (all_images[pathname] != current_image) {
98 current_image = all_images[pathname];
99 set_pixel_data(current_image->pixels.get());
102 movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
105 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
107 unique_lock<mutex> lock(all_images_lock); // Held also during loading.
108 if (all_images.count(pathname)) {
109 return all_images[pathname];
112 all_images[pathname] = load_image_raw(pathname);
113 timespec first_modified = all_images[pathname]->last_modified;
114 update_threads[pathname] =
115 thread(bind(update_thread_func, filename, pathname, first_modified));
117 return all_images[pathname];
120 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
122 // Note: Call before open, not after; otherwise, there's a race.
123 // (There is now, too, but it tips the correct way. We could use fstat()
124 // if we had the file descriptor.)
126 if (stat(pathname.c_str(), &buf) != 0) {
127 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
130 timespec last_modified = buf.st_mtim;
132 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
133 if (format_ctx == nullptr) {
134 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
138 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
139 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
143 int stream_index = -1;
144 for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
145 if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
150 if (stream_index == -1) {
151 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
155 const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
156 AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
157 if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
158 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
161 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
162 if (codec == nullptr) {
163 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
166 if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
167 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
170 unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
171 codec_ctx.get(), avcodec_close);
173 // Read packets until we have a frame or there are none left.
174 int frame_finished = 0;
175 AVFrameWithDeleter frame = av_frame_alloc_unique();
179 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
180 &pkt, av_packet_unref);
181 av_init_packet(&pkt);
184 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
185 if (pkt.stream_index != stream_index) {
188 if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
189 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
193 eof = true; // Or error, but ignore that for the time being.
196 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
198 frame_finished = true;
200 } else if (err != AVERROR(EAGAIN)) {
201 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
206 if (!frame_finished) {
207 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
211 uint8_t *pic_data[4] = {nullptr};
212 unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
213 &pic_data[0], av_freep);
215 if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
216 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
219 unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
220 sws_getContext(frame->width, frame->height,
221 (AVPixelFormat)frame->format, frame->width, frame->height,
222 AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
224 if (sws_ctx == nullptr) {
225 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
228 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
230 size_t len = frame->width * frame->height * 4;
231 unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
232 av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
234 shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), move(image_data), last_modified});
238 // Fire up a thread to update the image every second.
239 // We could do inotify, but this is good enough for now.
240 void ImageInput::update_thread_func(const std::string &filename, const std::string &pathname, const timespec &first_modified)
242 char thread_name[16];
243 snprintf(thread_name, sizeof(thread_name), "Update_%s", filename.c_str());
244 pthread_setname_np(pthread_self(), thread_name);
246 timespec last_modified = first_modified;
250 unique_lock<mutex> lock(threads_should_quit_mu);
251 threads_should_quit_modified.wait_for(lock, chrono::seconds(1), []() { return threads_should_quit; });
254 if (threads_should_quit) {
258 if (stat(pathname.c_str(), &buf) != 0) {
259 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
262 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
263 buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
267 shared_ptr<const Image> image = load_image_raw(pathname);
268 if (image == nullptr) {
269 fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
272 fprintf(stderr, "Loaded new version of %s from disk.\n", pathname.c_str());
273 unique_lock<mutex> lock(all_images_lock);
274 all_images[pathname] = image;
275 last_modified = image->last_modified;
279 void ImageInput::shutdown_updaters()
282 unique_lock<mutex> lock(threads_should_quit_mu);
283 threads_should_quit = true;
284 threads_should_quit_modified.notify_all();
286 for (auto &it : update_threads) {
291 mutex ImageInput::all_images_lock;
292 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
293 map<string, thread> ImageInput::update_threads;
294 mutex ImageInput::threads_should_quit_mu;
295 bool ImageInput::threads_should_quit = false;
296 condition_variable ImageInput::threads_should_quit_modified;