]> git.sesse.net Git - nageru/blob - nageru/image_input.cpp
Make the ImageInput cache store textures, not images.
[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 // FIXME gl context
45 ImageInput::ImageInput(const string &filename)
46         : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
47                            GL_UNSIGNED_BYTE, 1280, 720),  // Resolution will be overwritten.
48           pathname(search_for_file_or_die(filename)),
49           current_image(load_image(filename, pathname))
50 {
51         if (current_image == nullptr) {  // Could happen even though search_for_file() returned.
52                 fprintf(stderr, "Couldn't load image, exiting.\n");
53                 abort();
54         }
55         set_width(current_image->width);
56         set_height(current_image->height);
57         set_texture_num(*current_image->tex);
58 }
59
60 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
61 {
62         // See if the background thread has given us a new version of our image.
63         // Note: The old version might still be lying around in other ImageInputs
64         // (in fact, it's likely), but at least the total amount of memory used
65         // is bounded. Currently we don't even share textures between them,
66         // so there's a fair amount of OpenGL memory waste anyway (the cache
67         // is mostly there to save startup time, not RAM).
68         {
69                 lock_guard<mutex> lock(all_images_lock);
70                 if (all_images[pathname] != current_image) {
71                         current_image = all_images[pathname];
72                         set_texture_num(*current_image->tex);
73                 }
74         }
75         movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
76 }
77
78 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
79 {
80         lock_guard<mutex> lock(all_images_lock);  // Held also during loading.
81         if (all_images.count(pathname)) {
82                 return all_images[pathname];
83         }
84
85         all_images[pathname] = load_image_raw(pathname);
86         return all_images[pathname];
87 }
88
89 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
90 {
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.)
94         struct stat buf;
95         if (stat(pathname.c_str(), &buf) != 0) {
96                 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
97                 return nullptr;
98         }
99         timespec last_modified = buf.st_mtim;
100
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());
104                 return nullptr;
105         }
106
107         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
108                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
109                 return nullptr;
110         }
111
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());
115                 return nullptr;
116         }
117
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());
122                 return nullptr;
123         }
124         AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
125         if (codec == nullptr) {
126                 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
127                 return nullptr;
128         }
129         if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
130                 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
131                 return nullptr;
132         }
133         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
134                 codec_ctx.get(), avcodec_close);
135
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();
139         bool eof = false;
140         do {
141                 AVPacket pkt;
142                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
143                         &pkt, av_packet_unref);
144                 av_init_packet(&pkt);
145                 pkt.data = nullptr;
146                 pkt.size = 0;
147                 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
148                         if (pkt.stream_index != stream_index) {
149                                 continue;
150                         }
151                         if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
152                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
153                                 return nullptr;
154                         }
155                 } else {
156                         eof = true;  // Or error, but ignore that for the time being.
157                 }
158
159                 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
160                 if (err == 0) {
161                         frame_finished = true;
162                         break;
163                 } else if (err != AVERROR(EAGAIN)) {
164                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
165                         return nullptr;
166                 }
167         } while (!eof);
168
169         if (!frame_finished) {
170                 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
171                 return nullptr;
172         }
173
174         uint8_t *pic_data[4] = {nullptr};
175         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
176                 &pic_data[0], av_freep);
177         int linesizes[4];
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());
180                 return nullptr;
181         }
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),
186                 sws_freeContext);
187         if (sws_ctx == nullptr) {
188                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
189                 return nullptr;
190         }
191         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
192
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);
196
197         // Create and upload the texture. We always make mipmaps, since we have
198         // generally no idea of all the different chains that might crop up.
199         GLuint tex;
200         glGenTextures(1, &tex);
201         check_error();
202         glBindTexture(GL_TEXTURE_2D, tex);
203         check_error();
204         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
205         check_error();
206         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
207         check_error();
208         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
209         check_error();
210
211         // Actual upload.
212         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
213         check_error();
214         glPixelStorei(GL_UNPACK_ROW_LENGTH, linesizes[0] / 4);
215         check_error();
216         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, frame->width, frame->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data.get());
217         check_error();
218         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
219         check_error();
220
221         glGenerateMipmap(GL_TEXTURE_2D);
222         check_error();
223         glBindTexture(GL_TEXTURE_2D, 0);
224         check_error();
225
226         shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), RefCountedTexture(new GLuint(tex)), last_modified});
227         return image;
228 }
229
230 // Fire up a thread to update all images every second.
231 // We could do inotify, but this is good enough for now.
232 void ImageInput::update_thread_func(QSurface *surface)
233 {
234         pthread_setname_np(pthread_self(), "Update_Images");
235
236         eglBindAPI(EGL_OPENGL_API);
237         QOpenGLContext *context = create_context(surface);
238         if (!make_current(context, surface)) {
239                 printf("Couldn't initialize OpenGL context!\n");
240                 abort();
241         }
242
243         struct stat buf;
244         for ( ;; ) {
245                 {
246                         unique_lock<mutex> lock(update_thread_should_quit_mu);
247                         update_thread_should_quit_modified.wait_for(lock, chrono::seconds(1), [] { return update_thread_should_quit; });
248                 }
249                 if (update_thread_should_quit) {
250                         return;
251                 }
252
253                 // Go through all loaded images and see if they need to be updated.
254                 // We do one pass first through the array with no I/O, to avoid
255                 // blocking the renderer.
256                 vector<pair<string, timespec>> images_to_check;
257                 {
258                         unique_lock<mutex> lock(all_images_lock);
259                         for (const auto &pathname_and_image : all_images) {
260                                 const string pathname = pathname_and_image.first;
261                                 const timespec last_modified = pathname_and_image.second->last_modified;
262                                 images_to_check.emplace_back(pathname, last_modified);
263                         }
264                 }
265
266                 for (const auto &pathname_and_timespec : images_to_check) {
267                         const string pathname = pathname_and_timespec.first;
268                         const timespec last_modified = pathname_and_timespec.second;
269
270                         if (stat(pathname.c_str(), &buf) != 0) {
271                                 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
272                                 continue;
273                         }
274                         if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
275                             buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
276                                 // Not changed.
277                                 continue;
278                         }
279
280                         shared_ptr<const Image> image = load_image_raw(pathname);
281                         if (image == nullptr) {
282                                 fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
283                                 continue;
284                         }
285
286                         unique_lock<mutex> lock(all_images_lock);
287                         all_images[pathname] = image;
288                 }
289         }
290 }
291
292 void ImageInput::start_update_thread(QSurface *surface)
293 {
294         update_thread = thread(update_thread_func, surface);
295 }
296
297 void ImageInput::end_update_thread()
298
299 {
300         {
301                 lock_guard<mutex> lock(update_thread_should_quit_mu);
302                 update_thread_should_quit = true;
303                 update_thread_should_quit_modified.notify_all();
304         }
305         update_thread.join();
306 }
307
308 mutex ImageInput::all_images_lock;
309 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
310 thread ImageInput::update_thread;
311 mutex ImageInput::update_thread_should_quit_mu;
312 bool ImageInput::update_thread_should_quit = false;
313 condition_variable ImageInput::update_thread_should_quit_modified;