]> git.sesse.net Git - nageru/blob - nageru/image_input.cpp
7b11679e03b22089e1f0508e658e049d4be89662
[nageru] / nageru / image_input.cpp
1 #include "image_input.h"
2
3 #include <errno.h>
4 #include <movit/flat_input.h>
5 #include <movit/image_format.h>
6 #include <movit/util.h>
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 extern "C" {
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>
22 }
23
24 #include <epoxy/egl.h>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <cstddef>
29 #include <functional>
30 #include <mutex>
31 #include <thread>
32 #include <utility>
33 #include <vector>
34
35 #include "shared/context.h"
36 #include "shared/ffmpeg_raii.h"
37 #include "ffmpeg_util.h"
38 #include "flags.h"
39
40 struct SwsContext;
41
42 using namespace std;
43
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.
47 {}
48
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))
54 {
55         if (current_image == nullptr) {  // Could happen even though search_for_file() returned.
56                 fprintf(stderr, "Couldn't load image, exiting.\n");
57                 abort();
58         }
59         set_width(current_image->width);
60         set_height(current_image->height);
61         set_texture_num(*current_image->tex);
62 }
63
64 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
65 {
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).
72         {
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);
78                 }
79         }
80         sRGBSwitchingFlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
81 }
82
83 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
84 {
85         lock_guard<mutex> lock(all_images_lock);  // Held also during loading.
86         if (all_images.count(pathname)) {
87                 return all_images[pathname];
88         }
89
90         all_images[pathname] = load_image_raw(pathname);
91         return all_images[pathname];
92 }
93
94 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
95 {
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.)
99         struct stat buf;
100         if (stat(pathname.c_str(), &buf) != 0) {
101                 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
102                 return nullptr;
103         }
104         timespec last_modified = buf.st_mtim;
105
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());
109                 return nullptr;
110         }
111
112         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
113                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
114                 return nullptr;
115         }
116
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());
120                 return nullptr;
121         }
122
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());
127                 return nullptr;
128         }
129         const AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
130         if (codec == nullptr) {
131                 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
132                 return nullptr;
133         }
134         if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
135                 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
136                 return nullptr;
137         }
138         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
139                 codec_ctx.get(), avcodec_close);
140
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();
144         bool eof = false;
145         do {
146                 AVPacketWithDeleter pkt = av_packet_alloc_unique();
147                 pkt->data = nullptr;
148                 pkt->size = 0;
149                 if (av_read_frame(format_ctx.get(), pkt.get()) == 0) {
150                         if (pkt->stream_index != stream_index) {
151                                 continue;
152                         }
153                         if (avcodec_send_packet(codec_ctx.get(), pkt.get()) < 0) {
154                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
155                                 return nullptr;
156                         }
157                 } else {
158                         eof = true;  // Or error, but ignore that for the time being.
159                 }
160
161                 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
162                 if (err == 0) {
163                         frame_finished = true;
164                         break;
165                 } else if (err != AVERROR(EAGAIN)) {
166                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
167                         return nullptr;
168                 }
169         } while (!eof);
170
171         if (!frame_finished) {
172                 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
173                 return nullptr;
174         }
175
176         uint8_t *pic_data[4] = {nullptr};
177         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
178                 &pic_data[0], av_freep);
179         int linesizes[4];
180         if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
181                 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
182                 return nullptr;
183         }
184         unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
185                 sws_getContext(frame->width, frame->height,
186                         (AVPixelFormat)frame->format, frame->width, frame->height,
187                         AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
188                 sws_freeContext);
189         if (sws_ctx == nullptr) {
190                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
191                 return nullptr;
192         }
193         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
194
195         size_t len = frame->width * frame->height * 4;
196         unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
197         av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
198
199         // Create and upload the texture. We always make mipmaps, since we have
200         // generally no idea of all the different chains that might crop up.
201         GLuint tex;
202         glGenTextures(1, &tex);
203         check_error();
204         glBindTexture(GL_TEXTURE_2D, tex);
205         check_error();
206         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
207         check_error();
208         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
209         check_error();
210         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
211         check_error();
212
213         // Actual upload.
214         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
215         check_error();
216         glPixelStorei(GL_UNPACK_ROW_LENGTH, linesizes[0] / 4);
217         check_error();
218         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());
219         check_error();
220         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
221         check_error();
222
223         glGenerateMipmap(GL_TEXTURE_2D);
224         check_error();
225         glBindTexture(GL_TEXTURE_2D, 0);
226         check_error();
227
228         shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), UniqueTexture(new GLuint(tex)), last_modified});
229         return image;
230 }
231
232 // Fire up a thread to update all images every second.
233 // We could do inotify, but this is good enough for now.
234 void ImageInput::update_thread_func(QSurface *surface)
235 {
236         pthread_setname_np(pthread_self(), "Update_Images");
237
238         eglBindAPI(EGL_OPENGL_API);
239         QOpenGLContext *context = create_context(surface);
240         if (!make_current(context, surface)) {
241                 printf("Couldn't initialize OpenGL context!\n");
242                 abort();
243         }
244
245         struct stat buf;
246         for ( ;; ) {
247                 {
248                         unique_lock<mutex> lock(update_thread_should_quit_mu);
249                         update_thread_should_quit_modified.wait_for(lock, chrono::seconds(1), [] { return update_thread_should_quit; });
250                 }
251                 if (update_thread_should_quit) {
252                         return;
253                 }
254
255                 // Go through all loaded images and see if they need to be updated.
256                 // We do one pass first through the array with no I/O, to avoid
257                 // blocking the renderer.
258                 vector<pair<string, timespec>> images_to_check;
259                 {
260                         unique_lock<mutex> lock(all_images_lock);
261                         for (const auto &pathname_and_image : all_images) {
262                                 const string pathname = pathname_and_image.first;
263                                 const timespec last_modified = pathname_and_image.second->last_modified;
264                                 images_to_check.emplace_back(pathname, last_modified);
265                         }
266                 }
267
268                 for (const auto &pathname_and_timespec : images_to_check) {
269                         const string pathname = pathname_and_timespec.first;
270                         const timespec last_modified = pathname_and_timespec.second;
271
272                         if (stat(pathname.c_str(), &buf) != 0) {
273                                 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
274                                 continue;
275                         }
276                         if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
277                             buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
278                                 // Not changed.
279                                 continue;
280                         }
281
282                         shared_ptr<const Image> image = load_image_raw(pathname);
283                         if (image == nullptr) {
284                                 fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
285                                 continue;
286                         }
287
288                         unique_lock<mutex> lock(all_images_lock);
289                         all_images[pathname] = image;
290                 }
291         }
292 }
293
294 void ImageInput::switch_image(const string &pathname)
295 {
296 #ifndef NDEBUG
297         lock_guard<mutex> lock(all_images_lock);
298         assert(all_images.count(pathname));
299 #endif
300         this->pathname = pathname;
301 }
302
303 void ImageInput::start_update_thread(QSurface *surface)
304 {
305         update_thread = thread(update_thread_func, surface);
306 }
307
308 void ImageInput::end_update_thread()
309
310 {
311         {
312                 lock_guard<mutex> lock(update_thread_should_quit_mu);
313                 update_thread_should_quit = true;
314                 update_thread_should_quit_modified.notify_all();
315         }
316         update_thread.join();
317 }
318
319 mutex ImageInput::all_images_lock;
320 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
321 thread ImageInput::update_thread;
322 mutex ImageInput::update_thread_should_quit_mu;
323 bool ImageInput::update_thread_should_quit = false;
324 condition_variable ImageInput::update_thread_should_quit_modified;