]> git.sesse.net Git - nageru/blob - nageru/decklink_output.h
Fix DeckLink capture using the 11.7 or newer drivers.
[nageru] / nageru / decklink_output.h
1 #ifndef _DECKLINK_OUTPUT_H
2 #define _DECKLINK_OUTPUT_H 1
3
4 #include <epoxy/gl.h>
5 #include <movit/image_format.h>
6 #include <stdint.h>
7 #include <atomic>
8 #include <chrono>
9 #include <condition_variable>
10 #include <deque>
11 #include <memory>
12 #include <mutex>
13 #include <queue>
14 #include <thread>
15 #include <vector>
16
17 #include "DeckLinkAPI.h"
18 #include "DeckLinkAPITypes.h"
19 #include "LinuxCOM.h"
20
21 #include "shared/context.h"
22 #include "print_latency.h"
23 #include "quittable_sleeper.h"
24 #include "ref_counted_frame.h"
25 #include "shared/ref_counted_gl_sync.h"
26
27 namespace movit {
28
29 class ResourcePool;
30
31 }  // namespace movit
32
33 class ChromaSubsampler;
34 class IDeckLink;
35 class IDeckLinkOutput;
36 class QSurface;
37
38 class DeckLinkOutput : public IDeckLinkVideoOutputCallback {
39 public:
40         DeckLinkOutput(movit::ResourcePool *resource_pool, QSurface *surface, unsigned width, unsigned height, unsigned card_index);
41
42         // The IDecklinkInput argument is to work around a bug
43         // in the 11.7 and newer drivers against older SDKs,
44         // where you get a freeze if querying an IDeckLinkInput interface
45         // on an already-started card.
46         bool set_device(IDeckLink *decklink, IDeckLinkInput *input_arg);
47         void start_output(uint32_t mode, int64_t base_pts);  // Mode comes from get_available_video_modes().
48         void end_output();
49
50         void send_frame(GLuint y_tex, GLuint cbcr_tex, movit::YCbCrLumaCoefficients ycbcr_coefficients, const std::vector<RefCountedFrame> &input_frames, int64_t pts, int64_t duration);
51         void send_audio(int64_t pts, const std::vector<float> &samples);
52
53         // NOTE: The returned timestamp is undefined for preroll.
54         // Otherwise, it is the timestamp of the output frame as it should have been,
55         // even if we're overshooting. E.g. at 50 fps (0.02 spf), assuming the
56         // last frame was at t=0.980:
57         //
58         //   If we're at t=0.999, we wait until t=1.000 and return that.
59         //   If we're at t=1.001, we return t=1.000 immediately (small overshoot).
60         //   If we're at t=1.055, we drop two frames and return t=1.040 immediately.
61         void wait_for_frame(int64_t pts, int *dropped_frames, int64_t *frame_duration, bool *is_preroll, std::chrono::steady_clock::time_point *frame_timestamp);
62
63         // Analogous to CaptureInterface. Will only return modes that have the right width/height.
64         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes() const { return video_modes; }
65
66         // If the given mode is supported, return it. If not, pick some “best” valid mode.
67         uint32_t pick_video_mode(uint32_t mode) const;
68
69         // Desired Y'CbCr coefficients for the current mode. Undefined before start_output().
70         movit::YCbCrLumaCoefficients preferred_ycbcr_coefficients() const;
71
72         // IUnknown.
73         HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) override;
74         ULONG STDMETHODCALLTYPE AddRef() override;
75         ULONG STDMETHODCALLTYPE Release() override;
76
77         // IDeckLinkVideoOutputCallback.
78         HRESULT ScheduledFrameCompleted(/* in */ IDeckLinkVideoFrame *completedFrame, /* in */ BMDOutputFrameCompletionResult result) override;
79         HRESULT ScheduledPlaybackHasStopped() override;
80
81 private:
82         struct Frame : public IDeckLinkVideoFrame {
83         public:
84                 ~Frame();
85
86                 // IUnknown.
87                 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) override;
88                 ULONG STDMETHODCALLTYPE AddRef() override;
89                 ULONG STDMETHODCALLTYPE Release() override;
90
91                 // IDeckLinkVideoFrame.
92                 long GetWidth() override;
93                 long GetHeight() override;
94                 long GetRowBytes() override;
95                 BMDPixelFormat GetPixelFormat() override;
96                 BMDFrameFlags GetFlags() override;
97                 HRESULT GetBytes(/* out */ void **buffer) override;
98
99                 HRESULT GetTimecode(/* in */ BMDTimecodeFormat format, /* out */ IDeckLinkTimecode **timecode) override;
100                 HRESULT GetAncillaryData(/* out */ IDeckLinkVideoFrameAncillary **ancillary) override;
101
102         private:
103                 std::atomic<int> refcount{1};
104                 RefCountedGLsync fence;  // Needs to be waited on before uyvy_ptr can be read from.
105                 std::vector<RefCountedFrame> input_frames;  // Cannot be released before we are done rendering (ie., <fence> is asserted).
106                 ReceivedTimestamps received_ts;
107                 int64_t pts, duration;
108                 movit::ResourcePool *resource_pool;
109
110                 // These members are persistently allocated, and reused when the frame object is.
111                 GLuint uyvy_tex;  // Owned by <resource_pool>. Can also hold v210 data.
112                 GLuint pbo;
113                 uint8_t *uyvy_ptr;  // Persistent mapping into the PBO.
114
115                 // Current Blackmagic drivers (January 2017) have a bug where sending a PBO
116                 // pointer to the driver causes a kernel oops. Thus, we do an extra copy into
117                 // this pointer before giving the data to the driver. (We don't do a get
118                 // directly into this pointer, because e.g. Intel/Mesa hits a slow path when
119                 // you do readback into something that's not a PBO.) When Blackmagic fixes
120                 // the bug, we should drop this.
121                 std::unique_ptr<uint8_t[]> uyvy_ptr_local;
122
123                 friend class DeckLinkOutput;
124         };
125         std::unique_ptr<Frame> get_frame();
126         void create_uyvy(GLuint y_tex, GLuint cbcr_tex, GLuint dst_tex);
127
128         void present_thread_func();
129
130         std::atomic<int> refcount{1};
131
132         std::unique_ptr<ChromaSubsampler> chroma_subsampler;
133         std::map<uint32_t, bmusb::VideoMode> video_modes;
134
135         std::thread present_thread;
136         QuittableSleeper should_quit;
137
138         std::mutex frame_queue_mutex;
139         std::queue<std::unique_ptr<Frame>> pending_video_frames;  // Under <frame_queue_mutex>.
140         std::queue<std::unique_ptr<Frame>> frame_freelist;  // Under <frame_queue_mutex>.
141         std::deque<Frame *> scheduled_frames;  // Owned by the driver, so no unique_ptr. Under <frame_queue_mutex>.
142
143         std::condition_variable frame_queues_changed;
144         bool playback_initiated = false, playback_started = false;
145         int64_t base_pts, frame_duration;
146         BMDDisplayModeFlags current_mode_flags = 0;
147         bool last_frame_had_mode_mismatch = false;
148
149         movit::ResourcePool *resource_pool;
150         IDeckLinkInput *input = nullptr;
151         IDeckLinkOutput *output = nullptr;
152         BMDVideoConnection video_connection;
153         QSurface *surface;
154         unsigned width, height;
155         unsigned card_index;
156
157         GLuint uyvy_vbo;  // Holds position and texcoord data.
158         GLuint uyvy_program_num;  // Owned by <resource_pool>.
159         GLuint uyvy_position_attribute_index, uyvy_texcoord_attribute_index;
160 };
161
162 #endif  // !defined(_DECKLINK_OUTPUT_H)