1 #include "image_input.h"
4 #include <movit/flat_input.h>
5 #include <movit/image_format.h>
6 #include <movit/util.h>
13 #include <libavcodec/avcodec.h>
14 #include <libavformat/avformat.h>
15 #include <libavutil/avutil.h>
16 #include <libavutil/error.h>
17 #include <libavutil/frame.h>
18 #include <libavutil/imgutils.h>
19 #include <libavutil/mem.h>
20 #include <libavutil/pixfmt.h>
21 #include <libswscale/swscale.h>
24 #include <epoxy/egl.h>
35 #include "shared/context.h"
36 #include "shared/ffmpeg_raii.h"
37 #include "ffmpeg_util.h"
44 ImageInput::ImageInput()
45 : sRGBSwitchingFlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
46 GL_UNSIGNED_BYTE, 1280, 720) // Resolution will be overwritten.
49 ImageInput::ImageInput(const string &filename)
50 : sRGBSwitchingFlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
51 GL_UNSIGNED_BYTE, 1280, 720), // Resolution will be overwritten.
52 pathname(search_for_file_or_die(filename)),
53 current_image(load_image(filename, pathname))
55 if (current_image == nullptr) { // Could happen even though search_for_file() returned.
56 fprintf(stderr, "Couldn't load image, exiting.\n");
59 set_width(current_image->width);
60 set_height(current_image->height);
61 set_texture_num(*current_image->tex);
64 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
66 // See if the background thread has given us a new version of our image.
67 // Note: The old version might still be lying around in other ImageInputs
68 // (in fact, it's likely), but at least the total amount of memory used
69 // is bounded. Currently we don't even share textures between them,
70 // so there's a fair amount of OpenGL memory waste anyway (the cache
71 // is mostly there to save startup time, not RAM).
73 lock_guard<mutex> lock(all_images_lock);
74 assert(all_images.count(pathname));
75 if (all_images[pathname] != current_image) {
76 current_image = all_images[pathname];
77 set_texture_num(*current_image->tex);
80 sRGBSwitchingFlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
83 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
85 lock_guard<mutex> lock(all_images_lock); // Held also during loading.
86 if (all_images.count(pathname)) {
87 return all_images[pathname];
90 all_images[pathname] = load_image_raw(pathname);
91 return all_images[pathname];
94 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
96 // Note: Call before open, not after; otherwise, there's a race.
97 // (There is now, too, but it tips the correct way. We could use fstat()
98 // if we had the file descriptor.)
100 if (stat(pathname.c_str(), &buf) != 0) {
101 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
104 timespec last_modified = buf.st_mtim;
106 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
107 if (format_ctx == nullptr) {
108 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
112 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
113 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
117 int stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
118 if (stream_index == -1) {
119 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
123 const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
124 AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
125 if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
126 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
129 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
130 if (codec == nullptr) {
131 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
134 if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
135 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
138 unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
139 codec_ctx.get(), avcodec_close);
141 // Read packets until we have a frame or there are none left.
142 int frame_finished = 0;
143 AVFrameWithDeleter frame = av_frame_alloc_unique();
147 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
148 &pkt, av_packet_unref);
149 av_init_packet(&pkt);
152 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
153 if (pkt.stream_index != stream_index) {
156 if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
157 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
161 eof = true; // Or error, but ignore that for the time being.
164 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
166 frame_finished = true;
168 } else if (err != AVERROR(EAGAIN)) {
169 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
174 if (!frame_finished) {
175 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
179 uint8_t *pic_data[4] = {nullptr};
180 unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
181 &pic_data[0], av_freep);
183 if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
184 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
187 unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
188 sws_getContext(frame->width, frame->height,
189 (AVPixelFormat)frame->format, frame->width, frame->height,
190 AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
192 if (sws_ctx == nullptr) {
193 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
196 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
198 size_t len = frame->width * frame->height * 4;
199 unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
200 av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
202 // Create and upload the texture. We always make mipmaps, since we have
203 // generally no idea of all the different chains that might crop up.
205 glGenTextures(1, &tex);
207 glBindTexture(GL_TEXTURE_2D, tex);
209 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
211 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
213 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
217 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
219 glPixelStorei(GL_UNPACK_ROW_LENGTH, linesizes[0] / 4);
221 glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, frame->width, frame->height, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image_data.get());
223 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
226 glGenerateMipmap(GL_TEXTURE_2D);
228 glBindTexture(GL_TEXTURE_2D, 0);
231 shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), UniqueTexture(new GLuint(tex)), last_modified});
235 // Fire up a thread to update all images every second.
236 // We could do inotify, but this is good enough for now.
237 void ImageInput::update_thread_func(QSurface *surface)
239 pthread_setname_np(pthread_self(), "Update_Images");
241 eglBindAPI(EGL_OPENGL_API);
242 QOpenGLContext *context = create_context(surface);
243 if (!make_current(context, surface)) {
244 printf("Couldn't initialize OpenGL context!\n");
251 unique_lock<mutex> lock(update_thread_should_quit_mu);
252 update_thread_should_quit_modified.wait_for(lock, chrono::seconds(1), [] { return update_thread_should_quit; });
254 if (update_thread_should_quit) {
258 // Go through all loaded images and see if they need to be updated.
259 // We do one pass first through the array with no I/O, to avoid
260 // blocking the renderer.
261 vector<pair<string, timespec>> images_to_check;
263 unique_lock<mutex> lock(all_images_lock);
264 for (const auto &pathname_and_image : all_images) {
265 const string pathname = pathname_and_image.first;
266 const timespec last_modified = pathname_and_image.second->last_modified;
267 images_to_check.emplace_back(pathname, last_modified);
271 for (const auto &pathname_and_timespec : images_to_check) {
272 const string pathname = pathname_and_timespec.first;
273 const timespec last_modified = pathname_and_timespec.second;
275 if (stat(pathname.c_str(), &buf) != 0) {
276 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
279 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
280 buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
285 shared_ptr<const Image> image = load_image_raw(pathname);
286 if (image == nullptr) {
287 fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
291 unique_lock<mutex> lock(all_images_lock);
292 all_images[pathname] = image;
297 void ImageInput::switch_image(const string &pathname)
300 lock_guard<mutex> lock(all_images_lock);
301 assert(all_images.count(pathname));
303 this->pathname = pathname;
306 void ImageInput::start_update_thread(QSurface *surface)
308 update_thread = thread(update_thread_func, surface);
311 void ImageInput::end_update_thread()
315 lock_guard<mutex> lock(update_thread_should_quit_mu);
316 update_thread_should_quit = true;
317 update_thread_should_quit_modified.notify_all();
319 update_thread.join();
322 mutex ImageInput::all_images_lock;
323 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
324 thread ImageInput::update_thread;
325 mutex ImageInput::update_thread_should_quit_mu;
326 bool ImageInput::update_thread_should_quit = false;
327 condition_variable ImageInput::update_thread_should_quit_modified;