]> git.sesse.net Git - nageru/blob - ffmpeg_capture.h
Fix an issue where the mixer lagging too much behind CEF would cause us to display...
[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 // However, the rest of Nageru can't really use the audio for anything yet.
21
22 #include <assert.h>
23 #include <stdint.h>
24 #include <functional>
25 #include <map>
26 #include <memory>
27 #include <mutex>
28 #include <set>
29 #include <string>
30 #include <thread>
31
32 #include <movit/ycbcr.h>
33
34 extern "C" {
35 #include <libavresample/avresample.h>
36 #include <libavutil/pixfmt.h>
37 #include <libavutil/rational.h>
38 #include <libavutil/samplefmt.h>
39 }
40
41 #include "bmusb/bmusb.h"
42 #include "ffmpeg_raii.h"
43 #include "ref_counted_frame.h"
44 #include "quittable_sleeper.h"
45
46 struct AVFormatContext;
47 struct AVFrame;
48 struct AVRational;
49 struct AVPacket;
50
51 class FFmpegCapture : public bmusb::CaptureInterface
52 {
53 public:
54         FFmpegCapture(const std::string &filename, unsigned width, unsigned height);
55         ~FFmpegCapture();
56
57         void set_card_index(int card_index)
58         {
59                 this->card_index = card_index;
60         }
61
62         int get_card_index() const
63         {
64                 return card_index;
65         }
66
67         void rewind()
68         {
69                 std::lock_guard<std::mutex> lock(queue_mu);
70                 command_queue.push_back(QueuedCommand { QueuedCommand::REWIND });
71                 producer_thread_should_quit.wakeup();
72         }
73
74         void change_rate(double new_rate)
75         {
76                 std::lock_guard<std::mutex> lock(queue_mu);
77                 command_queue.push_back(QueuedCommand { QueuedCommand::CHANGE_RATE, new_rate });
78                 producer_thread_should_quit.wakeup();
79         }
80
81         // CaptureInterface.
82         void set_video_frame_allocator(bmusb::FrameAllocator *allocator) override
83         {
84                 video_frame_allocator = allocator;
85                 if (owned_video_frame_allocator.get() != allocator) {
86                         owned_video_frame_allocator.reset();
87                 }
88         }
89
90         bmusb::FrameAllocator *get_video_frame_allocator() override
91         {
92                 return video_frame_allocator;
93         }
94
95         // Does not take ownership.
96         void set_audio_frame_allocator(bmusb::FrameAllocator *allocator) override
97         {
98                 audio_frame_allocator = allocator;
99                 if (owned_audio_frame_allocator.get() != allocator) {
100                         owned_audio_frame_allocator.reset();
101                 }
102         }
103
104         bmusb::FrameAllocator *get_audio_frame_allocator() override
105         {
106                 return audio_frame_allocator;
107         }
108
109         // FFmpegCapture-specific overload of set_frame_callback that also gives
110         // the raw original pts from the video. Negative pts means a dummy frame.
111         typedef std::function<void(int64_t video_pts, AVRational video_timebase, int64_t audio_pts, AVRational audio_timebase,
112                                    uint16_t timecode,
113                                    bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
114                                    bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format)>
115                 frame_callback_t;
116         void set_frame_callback(frame_callback_t callback)
117         {
118                 frame_callback = callback;
119         }
120
121         void set_frame_callback(bmusb::frame_callback_t callback) override
122         {
123                 frame_callback = std::bind(
124                         callback,
125                         std::placeholders::_5,
126                         std::placeholders::_6,
127                         std::placeholders::_7,
128                         std::placeholders::_8,
129                         std::placeholders::_9,
130                         std::placeholders::_10,
131                         std::placeholders::_11);
132         }
133
134         // FFmpegCapture-specific callback that gives the raw audio.
135         typedef std::function<void(const AVPacket *pkt, const AVRational timebase)> audio_callback_t;
136         void set_audio_callback(audio_callback_t callback)
137         {
138                 audio_callback = callback;
139         }
140
141         // Used to get precise information about the Y'CbCr format used
142         // for a given frame. Only valid to call during the frame callback,
143         // and only when receiving a frame with pixel format PixelFormat_8BitYCbCrPlanar.
144         movit::YCbCrFormat get_current_frame_ycbcr_format() const
145         {
146                 return current_frame_ycbcr_format;
147         }
148
149         void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
150         {
151                 dequeue_init_callback = init;
152                 dequeue_cleanup_callback = cleanup;
153                 has_dequeue_callbacks = true;
154         }
155
156         std::string get_description() const override
157         {
158                 return description;
159         }
160
161         void configure_card() override;
162         void start_bm_capture() override;
163         void stop_dequeue_thread() override;
164         bool get_disconnected() const override { return false; }  // We never unplug.
165
166         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const override;
167         void set_video_mode(uint32_t video_mode_id) override {}  // Ignore.
168         uint32_t get_current_video_mode() const override { return 0; }
169
170         static constexpr bmusb::PixelFormat PixelFormat_NV12 = static_cast<bmusb::PixelFormat>(100);  // In the private range.
171         std::set<bmusb::PixelFormat> get_available_pixel_formats() const override {
172                 return std::set<bmusb::PixelFormat>{ bmusb::PixelFormat_8BitBGRA, bmusb::PixelFormat_8BitYCbCrPlanar, PixelFormat_NV12 };
173         }
174         void set_pixel_format(bmusb::PixelFormat pixel_format) override {
175                 this->pixel_format = pixel_format;
176         }       
177         bmusb::PixelFormat get_current_pixel_format() const override {
178                 return pixel_format;
179         }
180
181         std::map<uint32_t, std::string> get_available_video_inputs() const override {
182                 return { { 0, "Auto" } }; }
183         void set_video_input(uint32_t video_input_id) override {}  // Ignore.
184         uint32_t get_current_video_input() const override { return 0; }
185
186         std::map<uint32_t, std::string> get_available_audio_inputs() const override {
187                 return { { 0, "Embedded" } };
188         }
189         void set_audio_input(uint32_t audio_input_id) override {}  // Ignore.
190         uint32_t get_current_audio_input() const override { return 0; }
191
192 private:
193         void producer_thread_func();
194         void send_disconnected_frame();
195         bool play_video(const std::string &pathname);
196         void internal_rewind();
197
198         // Returns true if there was an error.
199         bool process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound);
200
201         // Returns nullptr if no frame was decoded (e.g. EOF).
202         AVFrameWithDeleter decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
203                                         const std::string &pathname, int video_stream_index, int audio_stream_index,
204                                         bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format, int64_t *audio_pts, bool *error);
205         void convert_audio(const AVFrame *audio_avframe, bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format);
206
207         bmusb::VideoFormat construct_video_format(const AVFrame *frame, AVRational video_timebase);
208         UniqueFrame make_video_frame(const AVFrame *frame, const std::string &pathname, bool *error);
209
210         std::string description, filename;
211         uint16_t timecode = 0;
212         unsigned width, height;
213         bmusb::PixelFormat pixel_format = bmusb::PixelFormat_8BitBGRA;
214         movit::YCbCrFormat current_frame_ycbcr_format;
215         bool running = false;
216         int card_index = -1;
217         double rate = 1.0;
218
219         bool has_dequeue_callbacks = false;
220         std::function<void()> dequeue_init_callback = nullptr;
221         std::function<void()> dequeue_cleanup_callback = nullptr;
222
223         bmusb::FrameAllocator *video_frame_allocator = nullptr;
224         bmusb::FrameAllocator *audio_frame_allocator = nullptr;
225         std::unique_ptr<bmusb::FrameAllocator> owned_video_frame_allocator;
226         std::unique_ptr<bmusb::FrameAllocator> owned_audio_frame_allocator;
227         frame_callback_t frame_callback = nullptr;
228         audio_callback_t audio_callback = nullptr;
229
230         SwsContextWithDeleter sws_ctx;
231         int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
232         AVPixelFormat sws_dst_format = AVPixelFormat(-1);  // In practice, always initialized.
233         AVRational video_timebase, audio_timebase;
234
235         QuittableSleeper producer_thread_should_quit;
236         std::thread producer_thread;
237
238         int64_t pts_origin, last_pts;
239         std::chrono::steady_clock::time_point start, next_frame_start;
240
241         std::mutex queue_mu;
242         struct QueuedCommand {
243                 enum Command { REWIND, CHANGE_RATE } command;
244                 double new_rate;  // For CHANGE_RATE.
245         };
246         std::vector<QueuedCommand> command_queue;  // Protected by <queue_mu>.
247
248         // Audio resampler.
249         AVAudioResampleContext *resampler = nullptr;
250         AVSampleFormat last_src_format, last_dst_format;
251         int64_t last_channel_layout;
252         int last_sample_rate;
253
254 };
255
256 #endif  // !defined(_FFMPEG_CAPTURE_H)