1 #ifndef _FFMPEG_CAPTURE_H
2 #define _FFMPEG_CAPTURE_H 1
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.
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.
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.
32 #include <movit/ycbcr.h>
35 #include <libavresample/avresample.h>
36 #include <libavutil/pixfmt.h>
37 #include <libavutil/rational.h>
38 #include <libavutil/samplefmt.h>
41 #include "bmusb/bmusb.h"
42 #include "ffmpeg_raii.h"
43 #include "ref_counted_frame.h"
44 #include "quittable_sleeper.h"
46 struct AVFormatContext;
51 class FFmpegCapture : public bmusb::CaptureInterface
54 FFmpegCapture(const std::string &filename, unsigned width, unsigned height);
57 void set_card_index(int card_index)
59 this->card_index = card_index;
62 int get_card_index() const
69 std::lock_guard<std::mutex> lock(queue_mu);
70 command_queue.push_back(QueuedCommand { QueuedCommand::REWIND });
71 producer_thread_should_quit.wakeup();
74 void change_rate(double new_rate)
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();
81 // Will stop the stream even if it's hung on blocking I/O.
84 should_interrupt = true;
88 void set_video_frame_allocator(bmusb::FrameAllocator *allocator) override
90 video_frame_allocator = allocator;
91 if (owned_video_frame_allocator.get() != allocator) {
92 owned_video_frame_allocator.reset();
96 bmusb::FrameAllocator *get_video_frame_allocator() override
98 return video_frame_allocator;
101 // Does not take ownership.
102 void set_audio_frame_allocator(bmusb::FrameAllocator *allocator) override
104 audio_frame_allocator = allocator;
105 if (owned_audio_frame_allocator.get() != allocator) {
106 owned_audio_frame_allocator.reset();
110 bmusb::FrameAllocator *get_audio_frame_allocator() override
112 return audio_frame_allocator;
115 // FFmpegCapture-specific overload of set_frame_callback that also gives
116 // the raw original pts from the video. Negative pts means a dummy frame.
117 typedef std::function<void(int64_t video_pts, AVRational video_timebase, int64_t audio_pts, AVRational audio_timebase,
119 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
120 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format)>
122 void set_frame_callback(frame_callback_t callback)
124 frame_callback = callback;
127 void set_frame_callback(bmusb::frame_callback_t callback) override
129 frame_callback = std::bind(
131 std::placeholders::_5,
132 std::placeholders::_6,
133 std::placeholders::_7,
134 std::placeholders::_8,
135 std::placeholders::_9,
136 std::placeholders::_10,
137 std::placeholders::_11);
140 // FFmpegCapture-specific callback that gives the raw audio.
141 typedef std::function<void(const AVPacket *pkt, const AVRational timebase)> audio_callback_t;
142 void set_audio_callback(audio_callback_t callback)
144 audio_callback = callback;
147 // Used to get precise information about the Y'CbCr format used
148 // for a given frame. Only valid to call during the frame callback,
149 // and only when receiving a frame with pixel format PixelFormat_8BitYCbCrPlanar.
150 movit::YCbCrFormat get_current_frame_ycbcr_format() const
152 return current_frame_ycbcr_format;
155 void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
157 dequeue_init_callback = init;
158 dequeue_cleanup_callback = cleanup;
159 has_dequeue_callbacks = true;
162 std::string get_description() const override
167 void configure_card() override;
168 void start_bm_capture() override;
169 void stop_dequeue_thread() override;
170 bool get_disconnected() const override { return false; } // We never unplug.
172 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const override;
173 void set_video_mode(uint32_t video_mode_id) override {} // Ignore.
174 uint32_t get_current_video_mode() const override { return 0; }
176 static constexpr bmusb::PixelFormat PixelFormat_NV12 = static_cast<bmusb::PixelFormat>(100); // In the private range.
177 std::set<bmusb::PixelFormat> get_available_pixel_formats() const override {
178 return std::set<bmusb::PixelFormat>{ bmusb::PixelFormat_8BitBGRA, bmusb::PixelFormat_8BitYCbCrPlanar, PixelFormat_NV12 };
180 void set_pixel_format(bmusb::PixelFormat pixel_format) override {
181 this->pixel_format = pixel_format;
183 bmusb::PixelFormat get_current_pixel_format() const override {
187 std::map<uint32_t, std::string> get_available_video_inputs() const override {
188 return { { 0, "Auto" } }; }
189 void set_video_input(uint32_t video_input_id) override {} // Ignore.
190 uint32_t get_current_video_input() const override { return 0; }
192 std::map<uint32_t, std::string> get_available_audio_inputs() const override {
193 return { { 0, "Embedded" } };
195 void set_audio_input(uint32_t audio_input_id) override {} // Ignore.
196 uint32_t get_current_audio_input() const override { return 0; }
199 void producer_thread_func();
200 void send_disconnected_frame();
201 bool play_video(const std::string &pathname);
202 void internal_rewind();
204 // Returns true if there was an error.
205 bool process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound);
207 // Returns nullptr if no frame was decoded (e.g. EOF).
208 AVFrameWithDeleter decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
209 const std::string &pathname, int video_stream_index, int audio_stream_index,
210 bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format, int64_t *audio_pts, bool *error);
211 void convert_audio(const AVFrame *audio_avframe, bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format);
213 bmusb::VideoFormat construct_video_format(const AVFrame *frame, AVRational video_timebase);
214 UniqueFrame make_video_frame(const AVFrame *frame, const std::string &pathname, bool *error);
216 static int interrupt_cb_thunk(void *unique);
219 std::string description, filename;
220 uint16_t timecode = 0;
221 unsigned width, height;
222 bmusb::PixelFormat pixel_format = bmusb::PixelFormat_8BitBGRA;
223 movit::YCbCrFormat current_frame_ycbcr_format;
224 bool running = false;
227 std::atomic<bool> should_interrupt{false};
228 bool last_frame_was_connected = true;
230 bool has_dequeue_callbacks = false;
231 std::function<void()> dequeue_init_callback = nullptr;
232 std::function<void()> dequeue_cleanup_callback = nullptr;
234 bmusb::FrameAllocator *video_frame_allocator = nullptr;
235 bmusb::FrameAllocator *audio_frame_allocator = nullptr;
236 std::unique_ptr<bmusb::FrameAllocator> owned_video_frame_allocator;
237 std::unique_ptr<bmusb::FrameAllocator> owned_audio_frame_allocator;
238 frame_callback_t frame_callback = nullptr;
239 audio_callback_t audio_callback = nullptr;
241 SwsContextWithDeleter sws_ctx;
242 int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
243 AVPixelFormat sws_dst_format = AVPixelFormat(-1); // In practice, always initialized.
244 AVRational video_timebase, audio_timebase;
246 QuittableSleeper producer_thread_should_quit;
247 std::thread producer_thread;
249 int64_t pts_origin, last_pts;
250 std::chrono::steady_clock::time_point start, next_frame_start, last_frame;
253 struct QueuedCommand {
254 enum Command { REWIND, CHANGE_RATE } command;
255 double new_rate; // For CHANGE_RATE.
257 std::vector<QueuedCommand> command_queue; // Protected by <queue_mu>.
260 AVAudioResampleContext *resampler = nullptr;
261 AVSampleFormat last_src_format, last_dst_format;
262 int64_t last_channel_layout;
263 int last_sample_rate;
267 #endif // !defined(_FFMPEG_CAPTURE_H)