OpenShot Library | libopenshot 0.2.7
DecklinkReader.cpp
Go to the documentation of this file.
1/**
2 * @file
3 * @brief Source file for DecklinkReader class
4 * @author Jonathan Thomas <jonathan@openshot.org>
5 *
6 * @ref License
7 */
8
9/* LICENSE
10 *
11 * Copyright (c) 2008-2019 OpenShot Studios, LLC
12 * <http://www.openshotstudios.com/>. This file is part of
13 * OpenShot Library (libopenshot), an open-source project dedicated to
14 * delivering high quality video editing and animation solutions to the
15 * world. For more information visit <http://www.openshot.org/>.
16 *
17 * OpenShot Library (libopenshot) is free software: you can redistribute it
18 * and/or modify it under the terms of the GNU Lesser General Public License
19 * as published by the Free Software Foundation, either version 3 of the
20 * License, or (at your option) any later version.
21 *
22 * OpenShot Library (libopenshot) is distributed in the hope that it will be
23 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU Lesser General Public License for more details.
26 *
27 * You should have received a copy of the GNU Lesser General Public License
28 * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
29 */
30
31#include "DecklinkReader.h"
32#include "Exceptions.h"
33
34using namespace openshot;
35
36DecklinkReader::DecklinkReader(int device, int video_mode, int pixel_format, int channels, int sample_depth)
37 : device(device), is_open(false), g_videoModeIndex(video_mode), g_audioChannels(channels), g_audioSampleDepth(sample_depth)
38{
39 // Init decklink variables
40 inputFlags = 0;
41 selectedDisplayMode = bmdModeNTSC;
42 pixelFormat = bmdFormat8BitYUV;
43 displayModeCount = 0;
44 exitStatus = 1;
45 foundDisplayMode = false;
46 pthread_mutex_init(&sleepMutex, NULL);
47 pthread_cond_init(&sleepCond, NULL);
48
49 switch(pixel_format)
50 {
51 case 0: pixelFormat = bmdFormat8BitYUV; break;
52 case 1: pixelFormat = bmdFormat10BitYUV; break;
53 case 2: pixelFormat = bmdFormat10BitRGB; break;
54 default:
55 throw DecklinkError("Pixel format is not valid (must be 0,1,2).");
56 }
57
58
59 // Attempt to open blackmagic card
60 deckLinkIterator = CreateDeckLinkIteratorInstance();
61
62 if (!deckLinkIterator)
63 throw DecklinkError("This application requires the DeckLink drivers installed.");
64
65 /* Connect to a DeckLink instance */
66 for (int device_count = 0; device_count <= device; device_count++)
67 {
68 // Check for requested device
69 result = deckLinkIterator->Next(&deckLink);
70 if (result != S_OK)
71 throw DecklinkError("No DeckLink PCI cards found.");
72
73 if (device_count == device)
74 break;
75 }
76
77 if (deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&deckLinkInput) != S_OK)
78 throw DecklinkError("DeckLink QueryInterface Failed.");
79
80 // Obtain an IDeckLinkDisplayModeIterator to enumerate the display modes supported on output
81 result = deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
82 if (result != S_OK)
83 throw DecklinkError("Could not obtain the video output display mode iterator.");
84
85 // Init deckLinkOutput (needed for color conversion)
86 if (deckLink->QueryInterface(IID_IDeckLinkOutput, (void**)&m_deckLinkOutput) != S_OK)
87 throw DecklinkError("Failed to create a deckLinkOutput(), used to convert YUV to RGB.");
88
89 // Init the YUV to RGB conversion
90 if(!(m_deckLinkConverter = CreateVideoConversionInstance()))
91 throw DecklinkError("Failed to create a VideoConversionInstance(), used to convert YUV to RGB.");
92
93 // Create Delegate & Pass in pointers to the output and converters
94 delegate = new DeckLinkInputDelegate(&sleepCond, m_deckLinkOutput, m_deckLinkConverter);
95 deckLinkInput->SetCallback(delegate);
96
97
98
99 if (g_videoModeIndex < 0)
100 throw DecklinkError("No video mode specified.");
101
102 // Loop through all available display modes, until a match is found (if any)
103 while (displayModeIterator->Next(&displayMode) == S_OK)
104 {
105 if (g_videoModeIndex == displayModeCount)
106 {
107 BMDDisplayModeSupport result;
108
109 foundDisplayMode = true;
110 displayMode->GetName(&displayModeName);
111 selectedDisplayMode = displayMode->GetDisplayMode();
112 deckLinkInput->DoesSupportVideoMode(selectedDisplayMode, pixelFormat, bmdVideoInputFlagDefault, &result, NULL);
113
114 // Get framerate
115 displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
116
117 if (result == bmdDisplayModeNotSupported)
118 throw DecklinkError("The display mode does not support the selected pixel format.");
119
120 if (inputFlags & bmdVideoInputDualStream3D)
121 {
122 if (!(displayMode->GetFlags() & bmdDisplayModeSupports3D))
123 throw DecklinkError("The display mode does not support 3D.");
124 }
125
126 break;
127 }
128 displayModeCount++;
129 displayMode->Release();
130 }
131
132 if (!foundDisplayMode)
133 throw DecklinkError("Invalid video mode. No matching ones found.");
134
135 // Check for video input
136 result = deckLinkInput->EnableVideoInput(selectedDisplayMode, pixelFormat, inputFlags);
137 if(result != S_OK)
138 throw DecklinkError("Failed to enable video input. Is another application using the card?");
139
140 // Check for audio input
141 result = deckLinkInput->EnableAudioInput(bmdAudioSampleRate48kHz, g_audioSampleDepth, g_audioChannels);
142 if(result != S_OK)
143 throw DecklinkError("Failed to enable audio input. Is another application using the card?");
144
145}
146
147// destructor
149{
150 if (displayModeIterator != NULL)
151 {
152 displayModeIterator->Release();
153 displayModeIterator = NULL;
154 }
155
156 if (deckLinkInput != NULL)
157 {
158 deckLinkInput->Release();
159 deckLinkInput = NULL;
160 }
161
162 if (deckLink != NULL)
163 {
164 deckLink->Release();
165 deckLink = NULL;
166 }
167
168 if (deckLinkIterator != NULL)
169 deckLinkIterator->Release();
170}
171
172// Open image file
174{
175 // Open reader if not already open
176 if (!is_open)
177 {
178 // Start the streams
179 result = deckLinkInput->StartStreams();
180 if(result != S_OK)
181 throw DecklinkError("Failed to start the video and audio streams.");
182
183
184 // Update image properties
185 info.has_audio = false;
186 info.has_video = true;
187 info.vcodec = displayModeName;
188 info.width = displayMode->GetWidth();
189 info.height = displayMode->GetHeight();
190 info.file_size = info.width * info.height * sizeof(char) * 4;
191 info.pixel_ratio.num = 1;
192 info.pixel_ratio.den = 1;
193 info.duration = 60 * 60 * 24; // 24 hour duration... since we're capturing a live stream
194 info.fps.num = frameRateScale;
195 info.fps.den = frameRateDuration;
196 info.video_timebase.num = frameRateDuration;
197 info.video_timebase.den = frameRateScale;
199
200 // Calculate the DAR (display aspect ratio)
202
203 // Reduce size fraction
204 size.Reduce();
205
206 // Set the ratio based on the reduced fraction
207 info.display_ratio.num = size.num;
208 info.display_ratio.den = size.den;
209
210 // Mark as "open"
211 is_open = true;
212 }
213}
214
215// Close device and video stream
217{
218 // Close all objects, if reader is 'open'
219 if (is_open)
220 {
221 // Stop streams
222 result = deckLinkInput->StopStreams();
223
224 if(result != S_OK)
225 throw DecklinkError("Failed to stop the video and audio streams.");
226
227 // Mark as "closed"
228 is_open = false;
229 }
230}
231
233{
234 return delegate->GetCurrentFrameNumber();
235}
236
237// Get an openshot::Frame object for the next available LIVE frame
238std::shared_ptr<Frame> DecklinkReader::GetFrame(int64_t requested_frame)
239{
240 // Get a frame from the delegate decklink class (which is collecting them on another thread)
241 std::shared_ptr<Frame> f = delegate->GetFrame(requested_frame);
242
243// cout << "Change the frame number to " << requested_frame << endl;
244// f->SetFrameNumber(requested_frame);
245 return f; // frame # does not matter, since it always gets the oldest frame
246}
247
248
249// Generate JSON string of this object
250std::string DecklinkReader::Json() const {
251
252 // Return formatted string
253 return JsonValue().toStyledString();
254}
255
256// Generate Json::Value for this object
257Json::Value DecklinkReader::JsonValue() const {
258
259 // Create root json object
260 Json::Value root = ReaderBase::JsonValue(); // get parent properties
261 root["type"] = "DecklinkReader";
262
263 // return JsonValue
264 return root;
265}
266
267// Load JSON string into this object
268void DecklinkReader::SetJson(const std::string value) {
269
270 // Parse JSON string into JSON objects
271 try
272 {
273 const Json::Value root = openshot::stringToJson(value);
274 // Set all values that match
275 SetJsonValue(root);
276 }
277 catch (const std::exception& e)
278 {
279 // Error parsing JSON (or missing keys)
280 throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
281 }
282}
283
284// Load Json::Value into this object
285void DecklinkReader::SetJsonValue(const Json::Value root) {
286
287 // Set parent data
289
290 // Re-Open path, and re-init everything (if needed)
291 if (is_open)
292 {
293 Close();
294 Open();
295 }
296}
Header file for DecklinkReader class.
Header file for all Exception classes.
Implementation of the Blackmagic Decklink API (used by the DecklinkReader)
Definition: DecklinkInput.h:74
unsigned long GetCurrentFrameNumber()
std::shared_ptr< openshot::Frame > GetFrame(int64_t requested_frame)
Exception when accessing a blackmagic decklink card.
Definition: Exceptions.h:80
std::shared_ptr< Frame > GetFrame(int64_t requested_frame)
Json::Value JsonValue() const
Generate Json::Value for this object.
void SetJson(const std::string value)
Load JSON string into this object.
unsigned long GetCurrentFrameNumber()
void Open()
Open device and video stream - which is called by the constructor automatically.
std::string Json() const override
Generate JSON string of this object.
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
This class represents a fraction.
Definition: Fraction.h:48
int num
Numerator for the fraction.
Definition: Fraction.h:50
double ToDouble() const
Return this fraction as a double (i.e. 1/2 = 0.5)
Definition: Fraction.cpp:59
void Reduce()
Reduce this fraction (i.e. 640/480 = 4/3)
Definition: Fraction.cpp:84
int den
Denominator for the fraction.
Definition: Fraction.h:51
Exception for invalid JSON.
Definition: Exceptions.h:206
openshot::ReaderInfo info
Information about the current media file.
Definition: ReaderBase.h:111
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: ReaderBase.cpp:171
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
Definition: ReaderBase.cpp:116
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:47
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:34
float duration
Length of time (in seconds)
Definition: ReaderBase.h:65
int width
The width of the video (in pixesl)
Definition: ReaderBase.h:68
openshot::Fraction fps
Frames per second, as a fraction (i.e. 24/1 = 24 fps)
Definition: ReaderBase.h:70
openshot::Fraction display_ratio
The ratio of width to height of the video stream (i.e. 640x480 has a ratio of 4/3)
Definition: ReaderBase.h:73
int height
The height of the video (in pixels)
Definition: ReaderBase.h:67
int64_t video_length
The number of frames in the video stream.
Definition: ReaderBase.h:75
std::string vcodec
The name of the video codec used to encode / decode the video stream.
Definition: ReaderBase.h:74
openshot::Fraction pixel_ratio
The pixel ratio of the video stream as a fraction (i.e. some pixels are not square)
Definition: ReaderBase.h:72
bool has_video
Determines if this file has a video stream.
Definition: ReaderBase.h:62
bool has_audio
Determines if this file has an audio stream.
Definition: ReaderBase.h:63
openshot::Fraction video_timebase
The video timebase determines how long each frame stays on the screen.
Definition: ReaderBase.h:77
int64_t file_size
Size of file (in bytes)
Definition: ReaderBase.h:66