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