]> git.sesse.net Git - nageru/blob - image_input.cpp
c9f74f8847c4b5f297c512de57c6d9eed1f7201f
[nageru] / image_input.cpp
1 #include "image_input.h"
2
3 #include <movit/image_format.h>
4
5 extern "C" {
6 #include <libavcodec/avcodec.h>
7 #include <libavformat/avformat.h>
8 #include <libavutil/imgutils.h>
9 #include <libavutil/pixfmt.h>
10 #include <libswscale/swscale.h>
11 }
12
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17
18 #include <mutex>
19 #include <thread>
20
21 #include "flags.h"
22
23 using namespace std;
24
25 namespace {
26
27 string search_for_file(const string &filename)
28 {
29         // Look for the file in all theme_dirs until we find one;
30         // that will be the permanent resolution of this file, whether
31         // it is actually valid or not.
32         // We store errors from all the attempts, and show them
33         // once we know we can't find any of them.
34         vector<string> errors;
35         for (const string &dir : global_flags.theme_dirs) {
36                 string pathname = dir + "/" + filename;
37                 if (access(pathname.c_str(), O_RDONLY) == 0) {
38                         return pathname;
39                 } else {
40                         char buf[512];
41                         snprintf(buf, sizeof(buf), "%s: %s", pathname.c_str(), strerror(errno));
42                         errors.push_back(buf);
43                 }
44         }
45
46         for (const string &error : errors) {
47                 fprintf(stderr, "%s\n", error.c_str());
48         }
49         fprintf(stderr, "Couldn't find %s in any directory in --theme-dirs, exiting.\n",
50                 filename.c_str());
51         exit(1);
52 }
53
54 }  // namespace
55
56 ImageInput::ImageInput(const string &filename)
57         : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
58                            GL_UNSIGNED_BYTE, 1280, 720),  // FIXME
59           pathname(search_for_file(filename)),
60           current_image(load_image(pathname))
61 {
62         if (current_image == nullptr) {  // Could happen even though search_for_file() returned.
63                 fprintf(stderr, "Couldn't load image, exiting.\n");
64                 exit(1);
65         }
66         set_pixel_data(current_image->pixels.get());
67 }
68
69 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
70 {
71         // See if the background thread has given us a new version of our image.
72         // Note: The old version might still be lying around in other ImageInputs
73         // (in fact, it's likely), but at least the total amount of memory used
74         // is bounded. Currently we don't even share textures between them,
75         // so there's a fair amount of OpenGL memory waste anyway (the cache
76         // is mostly there to save startup time, not RAM).
77         {
78                 unique_lock<mutex> lock(all_images_lock);
79                 if (all_images[pathname] != current_image) {
80                         current_image = all_images[pathname];
81                         set_pixel_data(current_image->pixels.get());
82                 }
83         }
84         movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
85 }
86
87 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &pathname)
88 {
89         unique_lock<mutex> lock(all_images_lock);  // Held also during loading.
90         if (all_images.count(pathname)) {
91                 return all_images[pathname];
92         }
93
94         all_images[pathname] = load_image_raw(pathname);
95         timespec first_modified = all_images[pathname]->last_modified;
96         update_threads[pathname] =
97                 thread(bind(update_thread_func, pathname, first_modified));
98
99         return all_images[pathname];
100 }
101
102 // Some helpers to make RAII versions of FFmpeg objects.
103 // The cleanup functions don't interact all that well with unique_ptr,
104 // so things get a bit messy and verbose, but overall it's worth it to ensure
105 // we never leak things by accident in error paths.
106
107 namespace {
108
109 void avformat_close_input_unique(AVFormatContext *format_ctx)
110 {
111         avformat_close_input(&format_ctx);
112 }
113
114 unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>
115 avformat_open_input_unique(const char *pathname,
116                            AVInputFormat *fmt, AVDictionary **options)
117 {
118         AVFormatContext *format_ctx = nullptr;
119         if (avformat_open_input(&format_ctx, pathname, fmt, options) != 0) {
120                 format_ctx = nullptr;
121         }
122         return unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>(
123                 format_ctx, avformat_close_input_unique);
124 }
125
126 void av_frame_free_unique(AVFrame *frame)
127 {
128         av_frame_free(&frame);
129 }
130
131 unique_ptr<AVFrame, decltype(av_frame_free_unique)*>
132 av_frame_alloc_unique()
133 {
134         AVFrame *frame = av_frame_alloc();
135         return unique_ptr<AVFrame, decltype(av_frame_free_unique)*>(
136                 frame, av_frame_free_unique);
137 }
138
139 void avcodec_free_context_unique(AVCodecContext *codec_ctx)
140 {
141         avcodec_free_context(&codec_ctx);
142 }
143
144 }  // namespace
145
146 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
147 {
148         // Note: Call before open, not after; otherwise, there's a race.
149         // (There is now, too, but it tips the correct way. We could use fstat()
150         // if we had the file descriptor.)
151         struct stat buf;
152         if (stat(pathname.c_str(), &buf) != 0) {
153                 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
154                 return nullptr;
155         }
156         timespec last_modified = buf.st_mtim;
157
158         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
159         if (format_ctx == nullptr) {
160                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
161                 return nullptr;
162         }
163
164         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
165                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
166                 return nullptr;
167         }
168
169         int stream_index = -1;
170         for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
171                 if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
172                         stream_index = i;
173                         break;
174                 }
175         }
176         if (stream_index == -1) {
177                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
178                 return nullptr;
179         }
180
181         const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
182         AVCodecContext *codec_ctx = avcodec_alloc_context3(nullptr);
183         unique_ptr<AVCodecContext, decltype(avcodec_free_context_unique)*> codec_ctx_free(
184                 codec_ctx, avcodec_free_context_unique);
185         if (avcodec_parameters_to_context(codec_ctx, codecpar) < 0) {
186                 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
187                 return nullptr;
188         }
189         AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
190         if (codec == nullptr) {
191                 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
192                 return nullptr;
193         }
194         if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
195                 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
196                 return nullptr;
197         }
198         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
199                 codec_ctx, avcodec_close);
200
201         // Read packets until we have a frame or there are none left.
202         int frame_finished = 0;
203         auto frame = av_frame_alloc_unique();
204         bool eof = false;
205         do {
206                 AVPacket pkt;
207                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
208                         &pkt, av_packet_unref);
209                 av_init_packet(&pkt);
210                 pkt.data = nullptr;
211                 pkt.size = 0;
212                 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
213                         if (pkt.stream_index != stream_index) {
214                                 continue;
215                         }
216                         if (avcodec_send_packet(codec_ctx, &pkt) < 0) {
217                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
218                                 return nullptr;
219                         }
220                 } else {
221                         eof = true;  // Or error, but ignore that for the time being.
222                 }
223
224                 int err = avcodec_receive_frame(codec_ctx, frame.get());
225                 if (err == 0) {
226                         frame_finished = true;
227                         break;
228                 } else if (err != AVERROR(EAGAIN)) {
229                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
230                         return nullptr;
231                 }
232         } while (!eof);
233
234         if (!frame_finished) {
235                 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
236                 return nullptr;
237         }
238
239         // TODO: Scale down if needed!
240         uint8_t *pic_data[4] = {nullptr};
241         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
242                 &pic_data[0], av_freep);
243         int linesizes[4];
244         if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
245                 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
246                 return nullptr;
247         }
248         unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
249                 sws_getContext(frame->width, frame->height,
250                         (AVPixelFormat)frame->format, frame->width, frame->height,
251                         AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
252                 sws_freeContext);
253         if (sws_ctx == nullptr) {
254                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
255                 return nullptr;
256         }
257         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
258
259         size_t len = frame->width * frame->height * 4;
260         unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
261         av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
262
263         shared_ptr<Image> image(new Image{move(image_data), last_modified});
264         return image;
265 }
266
267 // Fire up a thread to update the image every second.
268 // We could do inotify, but this is good enough for now.
269 void ImageInput::update_thread_func(const std::string &pathname, const timespec &first_modified)
270 {
271         timespec last_modified = first_modified;
272         struct stat buf;
273         for ( ;; ) {
274                 sleep(1);
275
276                 if (threads_should_quit) {
277                         return;
278                 }
279
280                 if (stat(pathname.c_str(), &buf) != 0) {
281                         fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
282                         continue;
283                 }
284                 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
285                     buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
286                         // Not changed.
287                         continue;
288                 }
289                 shared_ptr<const Image> image = load_image_raw(pathname);
290                 if (image == nullptr) {
291                         fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
292                         continue;
293                 }
294                 fprintf(stderr, "Loaded new version of %s from disk.\n", pathname.c_str());
295                 unique_lock<mutex> lock(all_images_lock);
296                 all_images[pathname] = image;
297                 last_modified = image->last_modified;
298         }
299 }
300
301 void ImageInput::shutdown_updaters()
302 {
303         // TODO: Kick these out of the sleep before one second?
304         threads_should_quit = true;
305
306         for (auto &it : update_threads) {
307                 it.second.join();
308         }
309 }
310
311 mutex ImageInput::all_images_lock;
312 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
313 map<string, thread> ImageInput::update_threads;
314 volatile bool ImageInput::threads_should_quit = false;