]> git.sesse.net Git - nageru/blob - ffmpeg_capture.h
Update the queue length metric after trimming, not before.
[nageru] / ffmpeg_capture.h
1 #ifndef _FFMPEG_CAPTURE_H
2 #define _FFMPEG_CAPTURE_H 1
3
4 // FFmpegCapture looks much like a capture card, but the frames it spits out
5 // come from a video in real time, looping. Because it decodes the video using
6 // FFmpeg (thus the name), this means it can handle a very wide array of video
7 // formats, and also things like network streaming and V4L capture, but it is
8 // also significantly less integrated and optimized than the regular capture
9 // cards. In particular, the frames are always scaled and converted to 8-bit
10 // RGBA on the CPU before being sent on to the GPU.
11 //
12 // Since we don't really know much about the video when building the chains,
13 // there are some limitations. In particular, frames are always assumed to be
14 // sRGB even if the video container says something else. We could probably
15 // try to load the video on startup and pick out the parameters at that point,
16 // but it would require some more plumbing, and it would also fail if the file
17 // changes parameters midway, which is allowed in some formats.
18 //
19 // There is currently no audio support.
20
21 #include <assert.h>
22 #include <stdint.h>
23 #include <functional>
24 #include <map>
25 #include <memory>
26 #include <mutex>
27 #include <set>
28 #include <string>
29 #include <thread>
30
31 #include <movit/ycbcr.h>
32
33 extern "C" {
34 #include <libavutil/pixfmt.h>
35 #include <libavutil/rational.h>
36 }
37
38 #include "bmusb/bmusb.h"
39 #include "ffmpeg_raii.h"
40 #include "quittable_sleeper.h"
41
42 struct AVFormatContext;
43 struct AVFrame;
44 struct AVRational;
45
46 class FFmpegCapture : public bmusb::CaptureInterface
47 {
48 public:
49         FFmpegCapture(const std::string &filename, unsigned width, unsigned height);
50         ~FFmpegCapture();
51
52         void set_card_index(int card_index)
53         {
54                 this->card_index = card_index;
55         }
56
57         int get_card_index() const
58         {
59                 return card_index;
60         }
61
62         void rewind()
63         {
64                 std::lock_guard<std::mutex> lock(queue_mu);
65                 command_queue.push_back(QueuedCommand { QueuedCommand::REWIND });
66                 producer_thread_should_quit.wakeup();
67         }
68
69         void change_rate(double new_rate)
70         {
71                 std::lock_guard<std::mutex> lock(queue_mu);
72                 command_queue.push_back(QueuedCommand { QueuedCommand::CHANGE_RATE, new_rate });
73                 producer_thread_should_quit.wakeup();
74         }
75
76         // CaptureInterface.
77         void set_video_frame_allocator(bmusb::FrameAllocator *allocator) override
78         {
79                 video_frame_allocator = allocator;
80                 if (owned_video_frame_allocator.get() != allocator) {
81                         owned_video_frame_allocator.reset();
82                 }
83         }
84
85         bmusb::FrameAllocator *get_video_frame_allocator() override
86         {
87                 return video_frame_allocator;
88         }
89
90         // Does not take ownership.
91         void set_audio_frame_allocator(bmusb::FrameAllocator *allocator) override
92         {
93                 audio_frame_allocator = allocator;
94                 if (owned_audio_frame_allocator.get() != allocator) {
95                         owned_audio_frame_allocator.reset();
96                 }
97         }
98
99         bmusb::FrameAllocator *get_audio_frame_allocator() override
100         {
101                 return audio_frame_allocator;
102         }
103
104         void set_frame_callback(bmusb::frame_callback_t callback) override
105         {
106                 frame_callback = callback;
107         }
108
109         // Used to get precise information about the Y'CbCr format used
110         // for a given frame. Only valid to call during the frame callback,
111         // and only when receiving a frame with pixel format PixelFormat_8BitYCbCrPlanar.
112         movit::YCbCrFormat get_current_frame_ycbcr_format() const
113         {
114                 return current_frame_ycbcr_format;
115         }
116
117         void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
118         {
119                 dequeue_init_callback = init;
120                 dequeue_cleanup_callback = cleanup;
121                 has_dequeue_callbacks = true;
122         }
123
124         std::string get_description() const override
125         {
126                 return description;
127         }
128
129         void configure_card() override;
130         void start_bm_capture() override;
131         void stop_dequeue_thread() override;
132         bool get_disconnected() const override { return false; }  // We never unplug.
133
134         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const;
135         void set_video_mode(uint32_t video_mode_id) override {}  // Ignore.
136         uint32_t get_current_video_mode() const override { return 0; }
137
138         std::set<bmusb::PixelFormat> get_available_pixel_formats() const override {
139                 return std::set<bmusb::PixelFormat>{ bmusb::PixelFormat_8BitBGRA, bmusb::PixelFormat_8BitYCbCrPlanar };
140         }
141         void set_pixel_format(bmusb::PixelFormat pixel_format) override {
142                 this->pixel_format = pixel_format;
143         }       
144         bmusb::PixelFormat get_current_pixel_format() const override {
145                 return pixel_format;
146         }
147
148         std::map<uint32_t, std::string> get_available_video_inputs() const override {
149                 return { { 0, "Auto" } }; }
150         void set_video_input(uint32_t video_input_id) override {}  // Ignore.
151         uint32_t get_current_video_input() const override { return 0; }
152
153         std::map<uint32_t, std::string> get_available_audio_inputs() const override {
154                 return { { 0, "Embedded" } };
155         }
156         void set_audio_input(uint32_t audio_input_id) override {}  // Ignore.
157         uint32_t get_current_audio_input() const override { return 0; }
158
159 private:
160         void producer_thread_func();
161         void send_disconnected_frame();
162         bool play_video(const std::string &pathname);
163         void internal_rewind();
164
165         // Returns true if there was an error.
166         bool process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound);
167
168         // Returns nullptr if no frame was decoded (e.g. EOF).
169         AVFrameWithDeleter decode_frame(AVFormatContext *format_ctx, AVCodecContext *codec_ctx, const std::string &pathname, int video_stream_index, bool *error);
170
171         bmusb::VideoFormat construct_video_format(const AVFrame *frame, AVRational video_timebase);
172         bmusb::FrameAllocator::Frame make_video_frame(const AVFrame *frame, const std::string &pathname, bool *error);
173
174         std::string description, filename;
175         uint16_t timecode = 0;
176         unsigned width, height;
177         bmusb::PixelFormat pixel_format = bmusb::PixelFormat_8BitBGRA;
178         movit::YCbCrFormat current_frame_ycbcr_format;
179         bool running = false;
180         int card_index = -1;
181         double rate = 1.0;
182
183         bool has_dequeue_callbacks = false;
184         std::function<void()> dequeue_init_callback = nullptr;
185         std::function<void()> dequeue_cleanup_callback = nullptr;
186
187         bmusb::FrameAllocator *video_frame_allocator = nullptr;
188         bmusb::FrameAllocator *audio_frame_allocator = nullptr;
189         std::unique_ptr<bmusb::FrameAllocator> owned_video_frame_allocator;
190         std::unique_ptr<bmusb::FrameAllocator> owned_audio_frame_allocator;
191         bmusb::frame_callback_t frame_callback = nullptr;
192
193         SwsContextWithDeleter sws_ctx;
194         int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
195         AVPixelFormat sws_dst_format = AVPixelFormat(-1);  // In practice, always initialized.
196         AVRational video_timebase;
197
198         QuittableSleeper producer_thread_should_quit;
199         std::thread producer_thread;
200
201         int64_t pts_origin, last_pts;
202         std::chrono::steady_clock::time_point start, next_frame_start;
203
204         std::mutex queue_mu;
205         struct QueuedCommand {
206                 enum Command { REWIND, CHANGE_RATE } command;
207                 double new_rate;  // For CHANGE_RATE.
208         };
209         std::vector<QueuedCommand> command_queue;  // Protected by <queue_mu>.
210 };
211
212 #endif  // !defined(_FFMPEG_CAPTURE_H)