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).
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.
36 #include <movit/effect.h>
37 #include <movit/ycbcr.h>
40 #include <libswresample/swresample.h>
41 #include <libavutil/pixfmt.h>
42 #include <libavutil/rational.h>
43 #include <libavutil/samplefmt.h>
46 #include "bmusb/bmusb.h"
47 #include "shared/ffmpeg_raii.h"
48 #include "ref_counted_frame.h"
49 #include "quittable_sleeper.h"
51 struct AVFormatContext;
56 class FFmpegCapture : public bmusb::CaptureInterface
59 FFmpegCapture(const std::string &filename, unsigned width, unsigned height);
61 // Takes ownership of the SRT client socket.
62 FFmpegCapture(int srt_sock, const std::string &stream_id);
66 void set_card_index(int card_index)
68 this->card_index = card_index;
71 int get_card_index() const
78 std::lock_guard<std::mutex> lock(queue_mu);
79 command_queue.push_back(QueuedCommand { QueuedCommand::REWIND });
80 producer_thread_should_quit.wakeup();
83 void change_rate(double new_rate)
85 std::lock_guard<std::mutex> lock(queue_mu);
86 command_queue.push_back(QueuedCommand { QueuedCommand::CHANGE_RATE, new_rate });
87 producer_thread_should_quit.wakeup();
90 std::string get_filename() const
92 std::lock_guard<std::mutex> lock(filename_mu);
96 void change_filename(const std::string &new_filename)
98 std::lock_guard<std::mutex> lock(filename_mu);
99 filename = new_filename;
100 should_interrupt = true;
103 // Will stop the stream even if it's hung on blocking I/O.
106 should_interrupt = true;
110 void set_video_frame_allocator(bmusb::FrameAllocator *allocator) override
112 video_frame_allocator = allocator;
113 if (owned_video_frame_allocator.get() != allocator) {
114 owned_video_frame_allocator.reset();
118 bmusb::FrameAllocator *get_video_frame_allocator() override
120 return video_frame_allocator;
123 // Does not take ownership.
124 void set_audio_frame_allocator(bmusb::FrameAllocator *allocator) override
126 audio_frame_allocator = allocator;
127 if (owned_audio_frame_allocator.get() != allocator) {
128 owned_audio_frame_allocator.reset();
132 bmusb::FrameAllocator *get_audio_frame_allocator() override
134 return audio_frame_allocator;
137 // FFmpegCapture-specific overload of set_frame_callback that also gives
138 // the raw original pts from the video. Negative pts means a dummy frame.
139 typedef std::function<void(int64_t video_pts, AVRational video_timebase, int64_t audio_pts, AVRational audio_timebase,
141 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
142 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format)>
144 void set_frame_callback(frame_callback_t callback)
146 frame_callback = callback;
149 void set_frame_callback(bmusb::frame_callback_t callback) override
151 frame_callback = std::bind(
153 std::placeholders::_5,
154 std::placeholders::_6,
155 std::placeholders::_7,
156 std::placeholders::_8,
157 std::placeholders::_9,
158 std::placeholders::_10,
159 std::placeholders::_11);
162 // FFmpegCapture-specific callback that gives the raw audio.
163 typedef std::function<void(const AVPacket *pkt, const AVRational timebase)> audio_callback_t;
164 void set_audio_callback(audio_callback_t callback)
166 audio_callback = callback;
169 // Used to get precise information about the Y'CbCr format used
170 // for a given frame. Only valid to call during the frame callback,
171 // and only when receiving a frame with pixel format PixelFormat_8BitYCbCrPlanar.
172 movit::YCbCrFormat get_current_frame_ycbcr_format() const
174 return current_frame_ycbcr_format;
177 // Only valid to call during the frame callback.
178 std::string get_last_subtitle() const
180 return last_subtitle;
184 bool get_has_last_subtitle() const
186 return has_last_subtitle;
190 movit::RGBTriplet get_last_neutral_color() const
192 return last_neutral_color;
195 void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
197 dequeue_init_callback = init;
198 dequeue_cleanup_callback = cleanup;
199 has_dequeue_callbacks = true;
202 void set_card_disconnected_callback(bmusb::card_disconnected_callback_t callback)
204 card_disconnected_callback = callback;
207 std::string get_description() const override
212 void configure_card() override;
213 void start_bm_capture() override;
214 void stop_dequeue_thread() override;
215 bool get_disconnected() const override { return disconnected; } // Only if play_once == true.
217 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const override;
218 void set_video_mode(uint32_t video_mode_id) override {} // Ignore.
219 uint32_t get_current_video_mode() const override { return 0; }
221 static constexpr bmusb::PixelFormat PixelFormat_NV12 = static_cast<bmusb::PixelFormat>(100); // In the private range.
222 std::set<bmusb::PixelFormat> get_available_pixel_formats() const override {
223 return std::set<bmusb::PixelFormat>{ bmusb::PixelFormat_8BitBGRA, bmusb::PixelFormat_8BitYCbCrPlanar, PixelFormat_NV12 };
225 void set_pixel_format(bmusb::PixelFormat pixel_format) override {
226 this->pixel_format = pixel_format;
228 bmusb::PixelFormat get_current_pixel_format() const override {
232 std::map<uint32_t, std::string> get_available_video_inputs() const override {
233 return { { 0, "Auto" } }; }
234 void set_video_input(uint32_t video_input_id) override {} // Ignore.
235 uint32_t get_current_video_input() const override { return 0; }
237 std::map<uint32_t, std::string> get_available_audio_inputs() const override {
238 return { { 0, "Embedded" } };
240 void set_audio_input(uint32_t audio_input_id) override {} // Ignore.
241 uint32_t get_current_audio_input() const override { return 0; }
244 void producer_thread_func();
245 void send_disconnected_frame();
246 bool play_video(const std::string &pathname);
247 void internal_rewind();
249 // Returns true if there was an error.
250 bool process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound);
252 // Returns nullptr if no frame was decoded (e.g. EOF).
253 AVFrameWithDeleter decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
254 const std::string &pathname, int video_stream_index, int audio_stream_index, int subtitle_stream_index,
255 bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format, int64_t *audio_pts, bool *error);
256 void convert_audio(const AVFrame *audio_avframe, bmusb::FrameAllocator::Frame *audio_frame, bmusb::AudioFormat *audio_format);
258 bmusb::VideoFormat construct_video_format(const AVFrame *frame, AVRational video_timebase);
259 UniqueFrame make_video_frame(const AVFrame *frame, const std::string &pathname, bool *error);
261 static int interrupt_cb_thunk(void *opaque);
265 static int read_srt_thunk(void *opaque, uint8_t *buf, int buf_size);
266 int read_srt(uint8_t *buf, int buf_size);
269 inline unsigned frame_width(const AVFrame *frame) const;
270 inline unsigned frame_height(const AVFrame *frame) const;
272 mutable std::mutex filename_mu;
273 std::string description, filename;
275 uint16_t timecode = 0;
276 unsigned width, height; // 0 means keep input size.
277 bmusb::PixelFormat pixel_format = bmusb::PixelFormat_8BitBGRA;
278 movit::YCbCrFormat current_frame_ycbcr_format;
279 bool running = false;
282 bool play_as_fast_as_possible = false; // Activated iff rate >= 10.0.
283 std::atomic<bool> should_interrupt{false};
284 bool last_frame_was_connected = true;
286 bool has_dequeue_callbacks = false;
287 std::function<void()> dequeue_init_callback = nullptr;
288 std::function<void()> dequeue_cleanup_callback = nullptr;
290 bmusb::card_disconnected_callback_t card_disconnected_callback = nullptr;
291 bool play_once = false; // End thread after playing. Only for SRT, since the socket is ephemeral.
292 std::atomic<bool> disconnected{false};
294 bmusb::FrameAllocator *video_frame_allocator = nullptr;
295 bmusb::FrameAllocator *audio_frame_allocator = nullptr;
296 std::unique_ptr<bmusb::FrameAllocator> owned_video_frame_allocator;
297 std::unique_ptr<bmusb::FrameAllocator> owned_audio_frame_allocator;
298 frame_callback_t frame_callback = nullptr;
299 audio_callback_t audio_callback = nullptr;
301 SwsContextWithDeleter sws_ctx;
302 int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
303 AVPixelFormat sws_dst_format = AVPixelFormat(-1); // In practice, always initialized.
304 AVRational video_timebase, audio_timebase;
305 bool is_mjpeg = false;
307 QuittableSleeper producer_thread_should_quit;
308 std::thread producer_thread;
310 int64_t pts_origin, last_pts;
311 std::chrono::steady_clock::time_point start, next_frame_start, last_frame;
314 struct QueuedCommand {
315 enum Command { REWIND, CHANGE_RATE } command;
316 double new_rate; // For CHANGE_RATE.
318 std::vector<QueuedCommand> command_queue; // Protected by <queue_mu>.
321 SwrContext *resampler = nullptr;
322 AVSampleFormat last_src_format, last_dst_format;
323 int64_t last_channel_layout;
324 int last_sample_rate;
326 // Subtitles (no decoding done, really).
327 bool has_last_subtitle = false;
328 std::string last_subtitle;
330 movit::RGBTriplet last_neutral_color{1.0f, 1.0f, 1.0f};
333 #endif // !defined(_FFMPEG_CAPTURE_H)