]> git.sesse.net Git - nageru/blobdiff - image_input.cpp
Release Nageru 1.7.2.
[nageru] / image_input.cpp
index 8cd395ac7aca7d55c4947cb4509047cd7f909e04..2bf4a237bb86758f92cbdcfba808c514c7c19b82 100644 (file)
@@ -1,68 +1,56 @@
 #include "image_input.h"
 
+#include <errno.h>
+#include <movit/flat_input.h>
 #include <movit/image_format.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 extern "C" {
 #include <libavcodec/avcodec.h>
 #include <libavformat/avformat.h>
+#include <libavutil/avutil.h>
+#include <libavutil/error.h>
+#include <libavutil/frame.h>
 #include <libavutil/imgutils.h>
+#include <libavutil/mem.h>
 #include <libavutil/pixfmt.h>
 #include <libswscale/swscale.h>
 }
 
-#include <sys/types.h>
+#include <fcntl.h>
 #include <sys/stat.h>
 #include <unistd.h>
-#include <fcntl.h>
-
+#include <cstddef>
+#include <functional>
 #include <mutex>
 #include <thread>
+#include <utility>
+#include <vector>
 
+#include "ffmpeg_raii.h"
+#include "ffmpeg_util.h"
 #include "flags.h"
 
-using namespace std;
-
-namespace {
-
-string search_for_file(const string &filename)
-{
-       // Look for the file in all theme_dirs until we find one;
-       // that will be the permanent resolution of this file, whether
-       // it is actually valid or not.
-       // We store errors from all the attempts, and show them
-       // once we know we can't find any of them.
-       vector<string> errors;
-       for (const string &dir : global_flags.theme_dirs) {
-               string pathname = dir + "/" + filename;
-               if (access(pathname.c_str(), O_RDONLY) == 0) {
-                       return pathname;
-               } else {
-                       char buf[512];
-                       snprintf(buf, sizeof(buf), "%s: %s", pathname.c_str(), strerror(errno));
-                       errors.push_back(buf);
-               }
-       }
-
-       for (const string &error : errors) {
-               fprintf(stderr, "%s\n", error.c_str());
-       }
-       fprintf(stderr, "Couldn't find %s in any directory in --theme-dirs, exiting.\n",
-               filename.c_str());
-       exit(1);
-}
+struct SwsContext;
 
-}  // namespace
+using namespace std;
 
 ImageInput::ImageInput(const string &filename)
        : movit::FlatInput({movit::COLORSPACE_sRGB, movit::GAMMA_sRGB}, movit::FORMAT_RGBA_POSTMULTIPLIED_ALPHA,
-                          GL_UNSIGNED_BYTE, 1280, 720),  // FIXME
-         pathname(search_for_file(filename)),
-         current_image(load_image(pathname))
+                          GL_UNSIGNED_BYTE, 1280, 720),  // Resolution will be overwritten.
+         filename(filename),
+         pathname(search_for_file_or_die(filename)),
+         current_image(load_image(filename, pathname))
 {
        if (current_image == nullptr) {  // Could happen even though search_for_file() returned.
                fprintf(stderr, "Couldn't load image, exiting.\n");
                exit(1);
        }
+       set_width(current_image->width);
+       set_height(current_image->height);
        set_pixel_data(current_image->pixels.get());
 }
 
@@ -84,7 +72,7 @@ void ImageInput::set_gl_state(GLuint glsl_program_num, const string& prefix, uns
        movit::FlatInput::set_gl_state(glsl_program_num, prefix, sampler_num);
 }
 
-shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &pathname)
+shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &filename, const string &pathname)
 {
        unique_lock<mutex> lock(all_images_lock);  // Held also during loading.
        if (all_images.count(pathname)) {
@@ -94,50 +82,11 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image(const string &pathnam
        all_images[pathname] = load_image_raw(pathname);
        timespec first_modified = all_images[pathname]->last_modified;
        update_threads[pathname] =
-               thread(bind(update_thread_func, pathname, first_modified));
+               thread(bind(update_thread_func, filename, pathname, first_modified));
 
        return all_images[pathname];
 }
 
-// Some helpers to make RAII versions of FFmpeg objects.
-// The cleanup functions don't interact all that well with unique_ptr,
-// so things get a bit messy and verbose, but overall it's worth it to ensure
-// we never leak things by accident in error paths.
-
-namespace {
-
-void avformat_close_input_unique(AVFormatContext *format_ctx)
-{
-       avformat_close_input(&format_ctx);
-}
-
-unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>
-avformat_open_input_unique(const char *pathname,
-                           AVInputFormat *fmt, AVDictionary **options)
-{
-       AVFormatContext *format_ctx = nullptr;
-       if (avformat_open_input(&format_ctx, pathname, fmt, options) != 0) {
-               format_ctx = nullptr;
-       }
-       return unique_ptr<AVFormatContext, decltype(avformat_close_input_unique)*>(
-               format_ctx, avformat_close_input_unique);
-}
-
-void av_frame_free_unique(AVFrame *frame)
-{
-       av_frame_free(&frame);
-}
-
-unique_ptr<AVFrame, decltype(av_frame_free_unique)*>
-av_frame_alloc_unique()
-{
-       AVFrame *frame = av_frame_alloc();
-       return unique_ptr<AVFrame, decltype(av_frame_free_unique)*>(
-               frame, av_frame_free_unique);
-}
-
-}  // namespace
-
 shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pathname)
 {
        // Note: Call before open, not after; otherwise, there's a race.
@@ -161,34 +110,33 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pat
                return nullptr;
        }
 
-       int stream_index = -1;
-       for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
-               if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
-                       stream_index = i;
-                       break;
-               }
-       }
+       int stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
        if (stream_index == -1) {
                fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
                return nullptr;
        }
 
-       AVCodecContext *codec_ctx = format_ctx->streams[stream_index]->codec;
-       AVCodec *codec = avcodec_find_decoder(codec_ctx->codec_id);
+       const AVCodecParameters *codecpar = format_ctx->streams[stream_index]->codecpar;
+       AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
+       if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
+               fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
+               return nullptr;
+       }
+       AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
        if (codec == nullptr) {
                fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
                return nullptr;
        }
-       if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
+       if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
                fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
                return nullptr;
        }
        unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
-               codec_ctx, avcodec_close);
+               codec_ctx.get(), avcodec_close);
 
        // Read packets until we have a frame or there are none left.
        int frame_finished = 0;
-       auto frame = av_frame_alloc_unique();
+       AVFrameWithDeleter frame = av_frame_alloc_unique();
        bool eof = false;
        do {
                AVPacket pkt;
@@ -201,7 +149,7 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pat
                        if (pkt.stream_index != stream_index) {
                                continue;
                        }
-                       if (avcodec_send_packet(codec_ctx, &pkt) < 0) {
+                       if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
                                fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
                                return nullptr;
                        }
@@ -209,7 +157,7 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pat
                        eof = true;  // Or error, but ignore that for the time being.
                }
 
-               int err = avcodec_receive_frame(codec_ctx, frame.get());
+               int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
                if (err == 0) {
                        frame_finished = true;
                        break;
@@ -224,7 +172,6 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pat
                return nullptr;
        }
 
-       // TODO: Scale down if needed!
        uint8_t *pic_data[4] = {nullptr};
        unique_ptr<uint8_t *, decltype(av_freep)*> pic_data_cleanup(
                &pic_data[0], av_freep);
@@ -248,18 +195,25 @@ shared_ptr<const ImageInput::Image> ImageInput::load_image_raw(const string &pat
        unique_ptr<uint8_t[]> image_data(new uint8_t[len]);
        av_image_copy_to_buffer(image_data.get(), len, pic_data, linesizes, AV_PIX_FMT_RGBA, frame->width, frame->height, 1);
 
-       shared_ptr<Image> image(new Image{move(image_data), last_modified});
+       shared_ptr<Image> image(new Image{unsigned(frame->width), unsigned(frame->height), move(image_data), last_modified});
        return image;
 }
 
 // Fire up a thread to update the image every second.
 // We could do inotify, but this is good enough for now.
-void ImageInput::update_thread_func(const std::string &pathname, const timespec &first_modified)
+void ImageInput::update_thread_func(const std::string &filename, const std::string &pathname, const timespec &first_modified)
 {
+       char thread_name[16];
+       snprintf(thread_name, sizeof(thread_name), "Update_%s", filename.c_str());
+       pthread_setname_np(pthread_self(), thread_name);
+
        timespec last_modified = first_modified;
        struct stat buf;
        for ( ;; ) {
-               sleep(1);
+               {
+                       unique_lock<mutex> lock(threads_should_quit_mu);
+                       threads_should_quit_modified.wait_for(lock, chrono::seconds(1), []() { return threads_should_quit; });
+               }
 
                if (threads_should_quit) {
                        return;
@@ -288,9 +242,11 @@ void ImageInput::update_thread_func(const std::string &pathname, const timespec
 
 void ImageInput::shutdown_updaters()
 {
-       // TODO: Kick these out of the sleep before one second?
-       threads_should_quit = true;
-
+       {
+               unique_lock<mutex> lock(threads_should_quit_mu);
+               threads_should_quit = true;
+               threads_should_quit_modified.notify_all();
+       }
        for (auto &it : update_threads) {
                it.second.join();
        }
@@ -299,4 +255,6 @@ void ImageInput::shutdown_updaters()
 mutex ImageInput::all_images_lock;
 map<string, shared_ptr<const ImageInput::Image>> ImageInput::all_images;
 map<string, thread> ImageInput::update_threads;
-volatile bool ImageInput::threads_should_quit = false;
+mutex ImageInput::threads_should_quit_mu;
+bool ImageInput::threads_should_quit = false;
+condition_variable ImageInput::threads_should_quit_modified;