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