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