]> git.sesse.net Git - nageru/blob - image_input.cpp
Update the queue length metric after trimming, not before.
[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 <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 extern "C" {
12 #include <libavcodec/avcodec.h>
13 #include <libavformat/avformat.h>
14 #include <libavutil/avutil.h>
15 #include <libavutil/error.h>
16 #include <libavutil/frame.h>
17 #include <libavutil/imgutils.h>
18 #include <libavutil/mem.h>
19 #include <libavutil/pixfmt.h>
20 #include <libswscale/swscale.h>
21 }
22
23 #include <fcntl.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <cstddef>
27 #include <functional>
28 #include <mutex>
29 #include <thread>
30 #include <utility>
31 #include <vector>
32
33 #include "ffmpeg_raii.h"
34 #include "ffmpeg_util.h"
35 #include "flags.h"
36
37 struct SwsContext;
38
39 using namespace std;
40
41 ImageInput::ImageInput(const string &filename)
42         : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
43                            GL_UNSIGNED_BYTE, 1280, 720),  // Resolution will be overwritten.
44           filename(filename),
45           pathname(search_for_file_or_die(filename)),
46           current_image(load_image(filename, pathname))
47 {
48         if (current_image == nullptr) {  // Could happen even though search_for_file() returned.
49                 fprintf(stderr, "Couldn't load image, exiting.\n");
50                 exit(1);
51         }
52         set_width(current_image->width);
53         set_height(current_image->height);
54         set_pixel_data(current_image->pixels.get());
55 }
56
57 void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num)
58 {
59         // See if the background thread has given us a new version of our image.
60         // Note: The old version might still be lying around in other ImageInputs
61         // (in fact, it's likely), but at least the total amount of memory used
62         // is bounded. Currently we don't even share textures between them,
63         // so there's a fair amount of OpenGL memory waste anyway (the cache
64         // is mostly there to save startup time, not RAM).
65         {
66                 unique_lock<mutex> lock(all_images_lock);
67                 if (all_images[pathname] != current_image) {
68                         current_image = all_images[pathname];
69                         set_pixel_data(current_image->pixels.get());
70                 }
71         }
72         movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
73 }
74
75 shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
76 {
77         unique_lock<mutex> lock(all_images_lock);  // Held also during loading.
78         if (all_images.count(pathname)) {
79                 return all_images[pathname];
80         }
81
82         all_images[pathname] = load_image_raw(pathname);
83         timespec first_modified = all_images[pathname]->last_modified;
84         update_threads[pathname] =
85                 thread(bind(update_thread_func, filename, pathname, first_modified));
86
87         return all_images[pathname];
88 }
89
90 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
91 {
92         // Note: Call before open, not after; otherwise, there's a race.
93         // (There is now, too, but it tips the correct way. We could use fstat()
94         // if we had the file descriptor.)
95         struct stat buf;
96         if (stat(pathname.c_str(), &buf) != 0) {
97                 fprintf(stderr, "%s: Error stat-ing file\n", pathname.c_str());
98                 return nullptr;
99         }
100         timespec last_modified = buf.st_mtim;
101
102         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
103         if (format_ctx == nullptr) {
104                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
105                 return nullptr;
106         }
107
108         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
109                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
110                 return nullptr;
111         }
112
113         int stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
114         if (stream_index == -1) {
115                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
116                 return nullptr;
117         }
118
119         const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
120         AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
121         if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
122                 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
123                 return nullptr;
124         }
125         AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
126         if (codec == nullptr) {
127                 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
128                 return nullptr;
129         }
130         if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
131                 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
132                 return nullptr;
133         }
134         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
135                 codec_ctx.get(), avcodec_close);
136
137         // Read packets until we have a frame or there are none left.
138         int frame_finished = 0;
139         AVFrameWithDeleter frame = av_frame_alloc_unique();
140         bool eof = false;
141         do {
142                 AVPacket pkt;
143                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
144                         &pkt, av_packet_unref);
145                 av_init_packet(&pkt);
146                 pkt.data = nullptr;
147                 pkt.size = 0;
148                 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
149                         if (pkt.stream_index != stream_index) {
150                                 continue;
151                         }
152                         if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
153                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
154                                 return nullptr;
155                         }
156                 } else {
157                         eof = true;  // Or error, but ignore that for the time being.
158                 }
159
160                 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
161                 if (err == 0) {
162                         frame_finished = true;
163                         break;
164                 } else if (err != AVERROR(EAGAIN)) {
165                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
166                         return nullptr;
167                 }
168         } while (!eof);
169
170         if (!frame_finished) {
171                 fprintf(stderr, "%s: Decoder did not output frame.\n", pathname.c_str());
172                 return nullptr;
173         }
174
175         uint8_t *pic_data[4] = {nullptr};
176         unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
177                 &pic_data[0], av_freep);
178         int linesizes[4];
179         if (av_image_alloc(pic_data, linesizes, frame->width, frame->height, AV_PIX_FMT_RGBA, 1) < 0) {
180                 fprintf(stderr, "%s: Could not allocate picture data\n", pathname.c_str());
181                 return nullptr;
182         }
183         unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(
184                 sws_getContext(frame->width, frame->height,
185                         (AVPixelFormat)frame->format, frame->width, frame->height,
186                         AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr, nullptr, nullptr),
187                 sws_freeContext);
188         if (sws_ctx == nullptr) {
189                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
190                 return nullptr;
191         }
192         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
193
194         size_t len = frame->width * frame->height * 4;
195         unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
196         av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
197
198         shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), move(image_data), last_modified});
199         return image;
200 }
201
202 // Fire up a thread to update the image every second.
203 // We could do inotify, but this is good enough for now.
204 void ImageInput::update_thread_func(const std::string &filename, const std::string &pathname, const timespec &first_modified)
205 {
206         char thread_name[16];
207         snprintf(thread_name, sizeof(thread_name), "Update_%s", filename.c_str());
208         pthread_setname_np(pthread_self(), thread_name);
209
210         timespec last_modified = first_modified;
211         struct stat buf;
212         for ( ;; ) {
213                 {
214                         unique_lock<mutex> lock(threads_should_quit_mu);
215                         threads_should_quit_modified.wait_for(lock, chrono::seconds(1), []() { return threads_should_quit; });
216                 }
217
218                 if (threads_should_quit) {
219                         return;
220                 }
221
222                 if (stat(pathname.c_str(), &buf) != 0) {
223                         fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
224                         continue;
225                 }
226                 if (buf.st_mtim.tv_sec == last_modified.tv_sec &&
227                     buf.st_mtim.tv_nsec == last_modified.tv_nsec) {
228                         // Not changed.
229                         continue;
230                 }
231                 shared_ptr<const Image> image = load_image_raw(pathname);
232                 if (image == nullptr) {
233                         fprintf(stderr, "Couldn't load image, leaving the old in place.\n");
234                         continue;
235                 }
236                 fprintf(stderr, "Loaded new version of %s from disk.\n", pathname.c_str());
237                 unique_lock<mutex> lock(all_images_lock);
238                 all_images[pathname] = image;
239                 last_modified = image->last_modified;
240         }
241 }
242
243 void ImageInput::shutdown_updaters()
244 {
245         {
246                 unique_lock<mutex> lock(threads_should_quit_mu);
247                 threads_should_quit = true;
248                 threads_should_quit_modified.notify_all();
249         }
250         for (auto &it : update_threads) {
251                 it.second.join();
252         }
253 }
254
255 mutex ImageInput::all_images_lock;
256 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
257 map<string, thread> ImageInput::update_threads;
258 mutex ImageInput::threads_should_quit_mu;
259 bool ImageInput::threads_should_quit = false;
260 condition_variable ImageInput::threads_should_quit_modified;