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