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