]> git.sesse.net Git - nageru/blob - nageru/image_input.cpp
Fix a comment typo.
[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         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                 AVPacket pkt;
147                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
148                         &pkt, av_packet_unref);
149                 av_init_packet(&pkt);
150                 pkt.data = nullptr;
151                 pkt.size = 0;
152                 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
153                         if (pkt.stream_index != stream_index) {
154                                 continue;
155                         }
156                         if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
157                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
158                                 return nullptr;
159                         }
160                 } else {
161                         eof = true;  // Or error, but ignore that for the time being.
162                 }
163
164                 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
165                 if (err == 0) {
166                         frame_finished = true;
167                         break;
168                 } else if (err != AVERROR(EAGAIN)) {
169                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
170                         return nullptr;
171                 }
172         } while (!eof);
173
174         if (!frame_finished) {
175                 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
176                 return nullptr;
177         }
178
179         uint8_t *pic_data[4] = {nullptr};
180         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
181                 &pic_data[0], av_freep);
182         int linesizes[4];
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());
185                 return nullptr;
186         }
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),
191                 sws_freeContext);
192         if (sws_ctx == nullptr) {
193                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
194                 return nullptr;
195         }
196         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
197
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);
201
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.
204         GLuint tex;
205         glGenTextures(1, &tex);
206         check_error();
207         glBindTexture(GL_TEXTURE_2D, tex);
208         check_error();
209         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
210         check_error();
211         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
212         check_error();
213         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
214         check_error();
215
216         // Actual upload.
217         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
218         check_error();
219         glPixelStorei(GL_UNPACK_ROW_LENGTH, linesizes[0] / 4);
220         check_error();
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());
222         check_error();
223         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
224         check_error();
225
226         glGenerateMipmap(GL_TEXTURE_2D);
227         check_error();
228         glBindTexture(GL_TEXTURE_2D, 0);
229         check_error();
230
231         shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), RefCountedTexture(new GLuint(tex)), last_modified});
232         return image;
233 }
234
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)
238 {
239         pthread_setname_np(pthread_self(), "Update_Images");
240
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");
245                 abort();
246         }
247
248         struct stat buf;
249         for ( ;; ) {
250                 {
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; });
253                 }
254                 if (update_thread_should_quit) {
255                         return;
256                 }
257
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;
262                 {
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);
268                         }
269                 }
270
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;
274
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());
277                                 continue;
278                         }
279                         if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
280                             buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
281                                 // Not changed.
282                                 continue;
283                         }
284
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");
288                                 continue;
289                         }
290
291                         unique_lock<mutex> lock(all_images_lock);
292                         all_images[pathname] = image;
293                 }
294         }
295 }
296
297 void ImageInput::switch_image(const string &pathname)
298 {
299 #ifndef NDEBUG
300         lock_guard<mutex> lock(all_images_lock);
301         assert(all_images.count(pathname));
302 #endif
303         this->pathname = pathname;
304 }
305
306 void ImageInput::start_update_thread(QSurface *surface)
307 {
308         update_thread = thread(update_thread_func, surface);
309 }
310
311 void ImageInput::end_update_thread()
312
313 {
314         {
315                 lock_guard<mutex> lock(update_thread_should_quit_mu);
316                 update_thread_should_quit = true;
317                 update_thread_should_quit_modified.notify_all();
318         }
319         update_thread.join();
320 }
321
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;