]> git.sesse.net Git - nageru/blob - image_input.cpp
Refresh ImageInputs from disk every second. Not the most efficient or elegant way...
[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
17 #include <mutex>
18 #include <thread>
19
20 using namespace std;
21
22 ImageInput::ImageInput(const string &filename)
23         : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
24                            GL_UNSIGNED_BYTE, 1280, 720),  // FIXME
25           filename(filename),
26           current_image(load_image(filename))
27 {
28         if (current_image == nullptr) {
29                 fprintf(stderr, "Couldn't load image, exiting.\n");
30                 exit(1);
31         }
32         set_pixel_data(current_image->pixels.get());
33 }
34
35 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
36 {
37         // See if the background thread has given us a new version of our image.
38         // Note: The old version might still be lying around in other ImageInputs
39         // (in fact, it's likely), but at least the total amount of memory used
40         // is bounded. Currently we don't even share textures between them,
41         // so there's a fair amount of OpenGL memory waste anyway (the cache
42         // is mostly there to save startup time, not RAM).
43         {
44                 unique_lock<mutex> lock(all_images_lock);
45                 if (all_images[filename] != current_image) {
46                         current_image = all_images[filename];
47                         set_pixel_data(current_image->pixels.get());
48                 }
49         }
50         movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
51 }
52
53 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename)
54 {
55         unique_lock<mutex> lock(all_images_lock);  // Held also during loading.
56         if (all_images.count(filename)) {
57                 return all_images[filename];
58         }
59
60         all_images[filename] = load_image_raw(filename);
61         timespec first_modified = all_images[filename]->last_modified;
62         update_threads[filename] =
63                 thread(bind(update_thread_func, filename, first_modified));
64
65         return all_images[filename];
66 }
67
68 // Some helpers to make RAII versions of FFmpeg objects.
69 // The cleanup functions don't interact all that well with unique_ptr,
70 // so things get a bit messy and verbose, but overall it's worth it to ensure
71 // we never leak things by accident in error paths.
72
73 namespace {
74
75 void avformat_close_input_unique(AVFormatContext *format_ctx)
76 {
77         avformat_close_input(&format_ctx);
78 }
79
80 unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>
81 avformat_open_input_unique(const char *filename,
82                            AVInputFormat *fmt, AVDictionary **options)
83 {
84         AVFormatContext *format_ctx = nullptr;
85         if (avformat_open_input(&format_ctx, filename, fmt, options) != 0) {
86                 format_ctx = nullptr;
87         }
88         return unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>(
89                 format_ctx, avformat_close_input_unique);
90 }
91
92 void av_frame_free_unique(AVFrame *frame)
93 {
94         av_frame_free(&frame);
95 }
96
97 unique_ptr<AVFrame, decltype(av_frame_free_unique)*>
98 av_frame_alloc_unique()
99 {
100         AVFrame *frame = av_frame_alloc();
101         return unique_ptr<AVFrame, decltype(av_frame_free_unique)*>(
102                 frame, av_frame_free_unique);
103 }
104
105 }  // namespace
106
107 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &filename)
108 {
109         // Note: Call before open, not after; otherwise, there's a race.
110         // (There is now, too, but it tips the correct way. We could use fstat()
111         // if we had the file descriptor.)
112         struct stat buf;
113         if (stat(filename.c_str(), &buf) != 0) {
114                 fprintf(stderr, "%s: Error stat-ing file\n", filename.c_str());
115                 return nullptr;
116         }
117         timespec last_modified = buf.st_mtim;
118
119         auto format_ctx = avformat_open_input_unique(filename.c_str(), nullptr, nullptr);
120         if (format_ctx == nullptr) {
121                 fprintf(stderr, "%s: Error opening file\n", filename.c_str());
122                 return nullptr;
123         }
124
125         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
126                 fprintf(stderr, "%s: Error finding stream info\n", filename.c_str());
127                 return nullptr;
128         }
129
130         int stream_index = -1;
131         for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
132                 if (format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
133                         stream_index = i;
134                         break;
135                 }
136         }
137         if (stream_index == -1) {
138                 fprintf(stderr, "%s: No video stream found\n", filename.c_str());
139                 return nullptr;
140         }
141
142         AVCodecContext *codec_ctx = format_ctx->streams[stream_index]->codec;
143         AVCodec *codec = avcodec_find_decoder(codec_ctx->codec_id);
144         if (codec == nullptr) {
145                 fprintf(stderr, "%s: Cannot find decoder\n", filename.c_str());
146                 return nullptr;
147         }
148         if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
149                 fprintf(stderr, "%s: Cannot open decoder\n", filename.c_str());
150                 return nullptr;
151         }
152         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
153                 codec_ctx, avcodec_close);
154
155         // Read packets until we have a frame.
156         int frame_finished = 0;
157         auto frame = av_frame_alloc_unique();
158         do {
159                 AVPacket pkt;
160                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
161                         &pkt, av_packet_unref);
162                 av_init_packet(&pkt);
163                 pkt.data = nullptr;
164                 pkt.size = 0;
165                 if (av_read_frame(format_ctx.get(), &pkt) < 0) {
166                         fprintf(stderr, "%s: Cannot read frame\n", filename.c_str());
167                         return nullptr;
168                 }
169                 if (pkt.stream_index != stream_index) {
170                         continue;
171                 }
172
173                 if (avcodec_decode_video2(codec_ctx, frame.get(), &frame_finished, &pkt) < 0) {
174                         fprintf(stderr, "%s: Cannot decode frame\n", filename.c_str());
175                         return nullptr;
176                 }
177         } while (!frame_finished);
178
179         // TODO: Scale down if needed!
180         uint8_t *pic_data[4] = {nullptr};
181         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
182                 &pic_data[0], av_freep);
183         int linesizes[4];
184         if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
185                 fprintf(stderr, "%s: Could not allocate picture data\n", filename.c_str());
186                 return nullptr;
187         }
188         unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
189                 sws_getContext(frame->width, frame->height,
190                         (AVPixelFormat)frame->format, frame->width, frame->height,
191                         AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
192                 sws_freeContext);
193         if (sws_ctx == nullptr) {
194                 fprintf(stderr, "%s: Could not create scaler context\n", filename.c_str());
195                 return nullptr;
196         }
197         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
198
199         size_t len = frame->width * frame->height * 4;
200         unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
201         av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
202
203         shared_ptr<Image> image(new Image{move(image_data), last_modified});
204         return image;
205 }
206
207 // Fire up a thread to update the image every second.
208 // We could do inotify, but this is good enough for now.
209 // TODO: These don't really quit, ever. Should they?
210 void ImageInput::update_thread_func(const std::string &filename, const timespec &first_modified)
211 {
212         timespec last_modified = first_modified;
213         struct stat buf;
214         for ( ;; ) {
215                 sleep(1);
216
217                 if (stat(filename.c_str(), &buf) != 0) {
218                         fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", filename.c_str());
219                         continue;
220                 }
221                 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
222                     buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
223                         // Not changed.
224                         continue;
225                 }
226                 shared_ptr<const Image> image = load_image_raw(filename);
227                 if (image == nullptr) {
228                         fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
229                         continue;
230                 }
231                 fprintf(stderr, "Loaded new version of %s from disk.\n", filename.c_str());
232                 unique_lock<mutex> lock(all_images_lock);
233                 all_images[filename] = image;
234                 last_modified = image->last_modified;
235         }
236 }
237
238 mutex ImageInput::all_images_lock;
239 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
240 map<string, thread> ImageInput::update_threads;