]> git.sesse.net Git - nageru/blob - nageru/ffmpeg_capture.h
6084b68f398dd6a15727fc380c3ef1207a818db6
[nageru] / 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 // You can get out the audio either as decoded or in raw form (Kaeru uses this).
20 //
21 // If there's a subtitle track, you can also get out the last subtitle at the
22 // point of the frame. Note that once we get a video frame, we don't look for
23 // subtitle, so if subtitles and a frame comes at the same time, you might not
24 // see the subtitle until the next frame.
25
26 #include <assert.h>
27 #include <stdint.h>
28 #include <functional>
29 #include <map>
30 #include <memory>
31 #include <mutex>
32 #include <set>
33 #include <string>
34 #include <thread>
35
36 #include <movit/effect.h>
37 #include <movit/ycbcr.h>
38
39 extern "C" {
40 #include <libswresample/swresample.h>
41 #include <libavutil/pixfmt.h>
42 #include <libavutil/rational.h>
43 #include <libavutil/samplefmt.h>
44 }
45
46 #include "bmusb/bmusb.h"
47 #include "shared/ffmpeg_raii.h"
48 #include "ref_counted_frame.h"
49 #include "quittable_sleeper.h"
50
51 struct AVFormatContext;
52 struct AVFrame;
53 struct AVRational;
54 struct AVPacket;
55
56 class FFmpegCapture : public bmusb::CaptureInterface
57 {
58 public:
59         FFmpegCapture(const std::string &filename, unsigned width, unsigned height);
60         ~FFmpegCapture();
61
62         void set_card_index(int card_index)
63         {
64                 this->card_index = card_index;
65         }
66
67         int get_card_index() const
68         {
69                 return card_index;
70         }
71
72         void rewind()
73         {
74                 std::lock_guard<std::mutex> lock(queue_mu);
75                 command_queue.push_back(QueuedCommand { QueuedCommand::REWIND });
76                 producer_thread_should_quit.wakeup();
77         }
78
79         void change_rate(double new_rate)
80         {
81                 std::lock_guard<std::mutex> lock(queue_mu);
82                 command_queue.push_back(QueuedCommand { QueuedCommand::CHANGE_RATE, new_rate });
83                 producer_thread_should_quit.wakeup();
84         }
85
86         std::string get_filename() const
87         {
88                 std::lock_guard<std::mutex> lock(filename_mu);
89                 return filename;
90         }
91
92         void change_filename(const std::string &new_filename)
93         {
94                 std::lock_guard<std::mutex> lock(filename_mu);
95                 filename = new_filename;
96                 should_interrupt = true;
97         }
98
99         // Will stop the stream even if it's hung on blocking I/O.
100         void disconnect()
101         {
102                 should_interrupt = true;
103         }
104
105         // CaptureInterface.
106         void set_video_frame_allocator(bmusb::FrameAllocator *allocator) override
107         {
108                 video_frame_allocator = allocator;
109                 if (owned_video_frame_allocator.get() != allocator) {
110                         owned_video_frame_allocator.reset();
111                 }
112         }
113
114         bmusb::FrameAllocator *get_video_frame_allocator() override
115         {
116                 return video_frame_allocator;
117         }
118
119         // Does not take ownership.
120         void set_audio_frame_allocator(bmusb::FrameAllocator *allocator) override
121         {
122                 audio_frame_allocator = allocator;
123                 if (owned_audio_frame_allocator.get() != allocator) {
124                         owned_audio_frame_allocator.reset();
125                 }
126         }
127
128         bmusb::FrameAllocator *get_audio_frame_allocator() override
129         {
130                 return audio_frame_allocator;
131         }
132
133         // FFmpegCapture-specific overload of set_frame_callback that also gives
134         // the raw original pts from the video. Negative pts means a dummy frame.
135         typedef std::function<void(int64_t video_pts, AVRational video_timebase, int64_t audio_pts, AVRational audio_timebase,
136                                    uint16_t timecode,
137                                    bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
138                                    bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format)>
139                 frame_callback_t;
140         void set_frame_callback(frame_callback_t callback)
141         {
142                 frame_callback = callback;
143         }
144
145         void set_frame_callback(bmusb::frame_callback_t callback) override
146         {
147                 frame_callback = std::bind(
148                         callback,
149                         std::placeholders::_5,
150                         std::placeholders::_6,
151                         std::placeholders::_7,
152                         std::placeholders::_8,
153                         std::placeholders::_9,
154                         std::placeholders::_10,
155                         std::placeholders::_11);
156         }
157
158         // FFmpegCapture-specific callback that gives the raw audio.
159         typedef std::function<void(const AVPacket *pkt, const AVRational timebase)> audio_callback_t;
160         void set_audio_callback(audio_callback_t callback)
161         {
162                 audio_callback = callback;
163         }
164
165         // Used to get precise information about the Y'CbCr format used
166         // for a given frame. Only valid to call during the frame callback,
167         // and only when receiving a frame with pixel format PixelFormat_8BitYCbCrPlanar.
168         movit::YCbCrFormat get_current_frame_ycbcr_format() const
169         {
170                 return current_frame_ycbcr_format;
171         }
172
173         // Only valid to call during the frame callback.
174         std::string get_last_subtitle() const
175         {
176                 return last_subtitle;
177         }
178
179         // Same.
180         bool get_has_last_subtitle() const
181         {
182                 return has_last_subtitle;
183         }
184
185         // Same.
186         movit::RGBTriplet get_last_neutral_color() const
187         {
188                 return last_neutral_color;
189         }
190
191         void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
192         {
193                 dequeue_init_callback = init;
194                 dequeue_cleanup_callback = cleanup;
195                 has_dequeue_callbacks = true;
196         }
197
198         std::string get_description() const override
199         {
200                 return description;
201         }
202
203         void configure_card() override;
204         void start_bm_capture() override;
205         void stop_dequeue_thread() override;
206         bool get_disconnected() const override { return false; }  // We never unplug.
207
208         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const override;
209         void set_video_mode(uint32_t video_mode_id) override {}  // Ignore.
210         uint32_t get_current_video_mode() const override { return 0; }
211
212         static constexpr bmusb::PixelFormat PixelFormat_NV12 = static_cast<bmusb::PixelFormat>(100);  // In the private range.
213         std::set<bmusb::PixelFormat> get_available_pixel_formats() const override {
214                 return std::set<bmusb::PixelFormat>{ bmusb::PixelFormat_8BitBGRA, bmusb::PixelFormat_8BitYCbCrPlanar, PixelFormat_NV12 };
215         }
216         void set_pixel_format(bmusb::PixelFormat pixel_format) override {
217                 this->pixel_format = pixel_format;
218         }       
219         bmusb::PixelFormat get_current_pixel_format() const override {
220                 return pixel_format;
221         }
222
223         std::map<uint32_t, std::string> get_available_video_inputs() const override {
224                 return { { 0, "Auto" } }; }
225         void set_video_input(uint32_t video_input_id) override {}  // Ignore.
226         uint32_t get_current_video_input() const override { return 0; }
227
228         std::map<uint32_t, std::string> get_available_audio_inputs() const override {
229                 return { { 0, "Embedded" } };
230         }
231         void set_audio_input(uint32_t audio_input_id) override {}  // Ignore.
232         uint32_t get_current_audio_input() const override { return 0; }
233
234 private:
235         void producer_thread_func();
236         void send_disconnected_frame();
237         bool play_video(const std::string &pathname);
238         void internal_rewind();
239
240         // Returns true if there was an error.
241         bool process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound);
242
243         // Returns nullptr if no frame was decoded (e.g. EOF).
244         AVFrameWithDeleter decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
245                                         const std::string &pathname, int video_stream_index, int audio_stream_index, int subtitle_stream_index,
246                                         bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format, int64_t *audio_pts, bool *error);
247         void convert_audio(const AVFrame *audio_avframe, bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format);
248
249         bmusb::VideoFormat construct_video_format(const AVFrame *frame, AVRational video_timebase);
250         UniqueFrame make_video_frame(const AVFrame *frame, const std::string &pathname, bool *error);
251
252         static int interrupt_cb_thunk(void *unique);
253         int interrupt_cb();
254
255         mutable std::mutex filename_mu;
256         std::string description, filename;
257         uint16_t timecode = 0;
258         unsigned width, height;
259         bmusb::PixelFormat pixel_format = bmusb::PixelFormat_8BitBGRA;
260         movit::YCbCrFormat current_frame_ycbcr_format;
261         bool running = false;
262         int card_index = -1;
263         double rate = 1.0;
264         bool play_as_fast_as_possible = false;  // Activated iff rate >= 10.0.
265         std::atomic<bool> should_interrupt{false};
266         bool last_frame_was_connected = true;
267
268         bool has_dequeue_callbacks = false;
269         std::function<void()> dequeue_init_callback = nullptr;
270         std::function<void()> dequeue_cleanup_callback = nullptr;
271
272         bmusb::FrameAllocator *video_frame_allocator = nullptr;
273         bmusb::FrameAllocator *audio_frame_allocator = nullptr;
274         std::unique_ptr<bmusb::FrameAllocator> owned_video_frame_allocator;
275         std::unique_ptr<bmusb::FrameAllocator> owned_audio_frame_allocator;
276         frame_callback_t frame_callback = nullptr;
277         audio_callback_t audio_callback = nullptr;
278
279         SwsContextWithDeleter sws_ctx;
280         int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
281         AVPixelFormat sws_dst_format = AVPixelFormat(-1);  // In practice, always initialized.
282         AVRational video_timebase, audio_timebase;
283         bool is_mjpeg = false;
284
285         QuittableSleeper producer_thread_should_quit;
286         std::thread producer_thread;
287
288         int64_t pts_origin, last_pts;
289         std::chrono::steady_clock::time_point start, next_frame_start, last_frame;
290
291         std::mutex queue_mu;
292         struct QueuedCommand {
293                 enum Command { REWIND, CHANGE_RATE } command;
294                 double new_rate;  // For CHANGE_RATE.
295         };
296         std::vector<QueuedCommand> command_queue;  // Protected by <queue_mu>.
297
298         // Audio resampler.
299         SwrContext *resampler = nullptr;
300         AVSampleFormat last_src_format, last_dst_format;
301         int64_t last_channel_layout;
302         int last_sample_rate;
303
304         // Subtitles (no decoding done, really).
305         bool has_last_subtitle = false;
306         std::string last_subtitle;
307
308         movit::RGBTriplet last_neutral_color;
309 };
310
311 #endif  // !defined(_FFMPEG_CAPTURE_H)