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