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