-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathblackmagic_common.cpp
More file actions
1926 lines (1754 loc) · 74.7 KB
/
Copy pathblackmagic_common.cpp
File metadata and controls
1926 lines (1754 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file blackmagic_common.cpp
* @author Martin Pulec <pulec@cesnet.cz>
*/
/*
* Copyright (c) 2014-2026 CESNET, zájmové sdružení právnických osob
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of CESNET nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "blackmagic_common.hpp"
#include <algorithm>
#include <atomic> // for atomic
#include <cassert>
#include <chrono> // for seconds
#include <climits> // for UINT_MAX
#include <cinttypes> // for PRId64
#include <condition_variable>
#include <cstdio> // for printf, snprintf
#include <cstdint> // for int64_t, uint32_t
#include <cstdlib> // for free
#include <cstring> // for strlen, NULL, strdup, memcpy, size_t
#include <iomanip>
#include <iterator> // for pair, size
#include <map>
#include <mutex> // for mutex, lock_guard, unique_lock
#include <sstream>
#include <stdexcept>
#include <utility>
#include "DeckLinkAPIVersion.h"
#include "compat/endian.h" // for be32toh, htobe32
#include "debug.h"
#include "host.h"
#include "tv.h"
#include "utils/color_out.h"
#include "utils/debug.h" // for DEBUG_TIMER_*
#include "utils/macros.h" // for STR_LEN, snprintf_ch, IS_FCC
#include "utils/string.h" // for DELDEL
#include "utils/unicode.h" // for wcs_to_mbs_fallb
#include "utils/windows.h"
#include "utils/worker.h"
// BMD sometimes do a ABI bump that entirely breaks compatibility (eg. changing
// GUIDs), this can be inspected by checking the "versioned" DeckLinkAPI here:
// <https://github.com/MartinPulec/desktopvideo_sdk-api/tree/main/Linux/include>
#define BMD_LAST_INCOMPATIBLE_ABI 0x0b050100 // 11.5.1
#if BLACKMAGIC_DECKLINK_API_VERSION > 0x0c080000
#warning \
"Increased BMD API - enum diffs recheck recommends (or just increase the compared API version)"
#endif
#define MOD_NAME "[DeckLink] "
using std::clamp;
using std::fixed;
using std::hex;
using std::invalid_argument;
using std::map;
using std::min;
using std::pair;
using std::ostringstream;
using std::setfill;
using std::setw;
using std::stod;
using std::stoi;
using std::string;
using std::uppercase;
using std::vector;
string bmd_hresult_to_string(HRESULT res)
{
const char *errptr = nullptr;
#ifdef _WIN32
errptr = hresult_to_str(res);
#else
HRESULT_GET_ERROR_COMMON(res, errptr)
#endif
ostringstream oss;
if (errptr) {
oss << errptr;
}
oss << " " << "(0x" << hex << setfill('0') << setw(8) << res << ")";
return oss.str();
}
/**
* returned c-sring needs to be freed when not used
*/
char *get_cstr_from_bmd_api_str(BMD_STR bmd_string)
{
if (!bmd_string) {
return strdup("(NULL!)");
}
char *cstr;
#ifdef __APPLE__
size_t len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(bmd_string), kCFStringEncodingUTF8) + 1;
cstr = (char *) malloc(len);
CFStringGetCString(bmd_string, (char *) cstr, len, kCFStringEncodingUTF8);
#elif defined _WIN32
size_t len = SysStringLen(bmd_string) * 4 + 1;
cstr = (char *) malloc(len);
wcstombs((char *) cstr, bmd_string, len);
#else // Linux
cstr = strdup(bmd_string);
#endif
return cstr;
}
BMD_STR get_bmd_api_str_from_cstr(const char *cstr)
{
#ifdef __APPLE__
return CFStringCreateWithCString(kCFAllocatorMalloc, cstr, kCFStringEncodingUTF8);
#elif defined _WIN32
mbstate_t mbstate{};
const char *tmp = cstr;
size_t required_size = mbsrtowcs(NULL, &tmp, 0, &mbstate) + 1;
BMD_STR out = (wchar_t *) malloc(required_size * sizeof(wchar_t));
mbsrtowcs(out, &tmp, required_size, &mbstate);
return out;
#else
return strdup(cstr);
#endif
}
void release_bmd_api_str(BMD_STR string)
{
if (!string) {
return;
}
#ifdef __APPLE__
CFRelease(string);
#elif defined _WIN32
SysFreeString(string);
#else
free(const_cast<char *>(string));
#endif
}
std::string get_str_from_bmd_api_str(BMD_STR string)
{
char *displayModeCString = get_cstr_from_bmd_api_str(string);
std::string out = displayModeCString;
free(displayModeCString);
return out;
}
/**
* @param[out] com_initialized pointer to be passed to decklnk_uninitialize
(keeps information if COM needs to be uninitialized)
* @note
* Each successful call (returning non-null pointer) of this function
* should be followed by com_uninitialize() when done with DeckLink (not when releasing
* IDeckLinkIterator!), typically on application shutdown.
*/
IDeckLinkIterator *create_decklink_iterator(bool *com_initialized, bool verbose)
{
IDeckLinkIterator *deckLinkIterator = nullptr;
#ifdef _WIN32
com_initialize(com_initialized, "[BMD] ");
HRESULT result = CoCreateInstance(CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL,
IID_IDeckLinkIterator, (void **) &deckLinkIterator);
if (FAILED(result)) {
decklink_uninitialize(com_initialized);
deckLinkIterator = nullptr;
}
#else
*com_initialized = false;
deckLinkIterator = CreateDeckLinkIteratorInstance();
#endif
if (!deckLinkIterator && verbose) {
log_msg(LOG_LEVEL_ERROR, "A DeckLink iterator could not be created. The DeckLink drivers may not be installed or are outdated.\n");
log_msg(LOG_LEVEL_INFO, "This UltraGrid version was compiled with DeckLink drivers %s. You should have at least this version.\n\n",
BLACKMAGIC_DECKLINK_API_VERSION_STRING);
}
return deckLinkIterator;
}
void decklink_uninitialize(bool *com_initialized)
{
com_uninitialize(com_initialized);
}
bool blackmagic_api_version_check()
{
bool ret = false;
IDeckLinkAPIInformation *APIInformation = NULL;
HRESULT result;
bool com_initialized = false;
if (!com_initialize(&com_initialized, "[BMD] ")) {
goto cleanup;
}
#ifdef _WIN32
result = CoCreateInstance(CLSID_CDeckLinkAPIInformation, NULL, CLSCTX_ALL,
IID_IDeckLinkAPIInformation, (void **) &APIInformation);
if(FAILED(result)) {
#else
APIInformation = CreateDeckLinkAPIInformationInstance();
if(APIInformation == NULL) {
#endif
log_msg(LOG_LEVEL_ERROR, "Cannot get API information! Perhaps drivers not installed.\n");
goto cleanup;
}
int64_t value;
result = APIInformation->GetInt(BMDDeckLinkAPIVersion, &value);
if(result != S_OK) {
log_msg(LOG_LEVEL_ERROR, "Cannot get API version!\n");
goto cleanup;
}
// this is safe comparison, for internal structure please see SDK
// documentation
if (value <= BMD_LAST_INCOMPATIBLE_ABI) {
MSG(ERROR, "The DeckLink drivers are be outdated.\n");
MSG(ERROR, "You must have drivers newer than %d.%d.%d.\n",
BMD_LAST_INCOMPATIBLE_ABI >> 24,
(BMD_LAST_INCOMPATIBLE_ABI >> 16) & 0xFF,
(BMD_LAST_INCOMPATIBLE_ABI >> 8) & 0xFF);
MSG(ERROR, "Vendor download page is "
"http://www.blackmagic-design.com/support\n");
print_decklink_version();
} else {
ret = true;
if (BLACKMAGIC_DECKLINK_API_VERSION > value) {
MSG(WARNING, "The DeckLink drivers are be outdated.\n");
MSG(WARNING,
"Although it will likely work, it is recommended "
"to use drivers at least as the API that "
"UltraGrid is linked with.\n");
print_decklink_version();
MSG(WARNING,
"Vendor download page is "
"http://www.blackmagic-design.com/support\n\n");
}
}
cleanup:
if (APIInformation) {
APIInformation->Release();
}
decklink_uninitialize(&com_initialized);
return ret;
}
void print_decklink_version()
{
BMD_STR current_version = NULL;
IDeckLinkAPIInformation *APIInformation = NULL;
HRESULT result;
char *currentVersionCString = nullptr;
const char *compat_status = TGREEN("compatible");
#ifdef _WIN32
bool com_initialized = false;
if (!com_initialize(&com_initialized, "[BMD] ")) {
goto cleanup;
}
result = CoCreateInstance(CLSID_CDeckLinkAPIInformation, NULL, CLSCTX_ALL,
IID_IDeckLinkAPIInformation, (void **) &APIInformation);
if(FAILED(result)) {
#else
APIInformation = CreateDeckLinkAPIInformationInstance();
if(APIInformation == NULL) {
#endif
MSG(ERROR, "Cannot get API information! Perhaps drivers not "
"installed.\n");
goto cleanup;
}
result = APIInformation->GetString(BMDDeckLinkAPIVersion, ¤t_version);
if (result != S_OK) {
MSG(ERROR, "Cannot get API version string!\n");
goto cleanup;
}
currentVersionCString = get_cstr_from_bmd_api_str(current_version);
if (BMDDeckLinkAPIVersion <= BMD_LAST_INCOMPATIBLE_ABI) {
compat_status = TRED("INCOMPATIBLE");
} else if (BMDDeckLinkAPIVersion < BLACKMAGIC_DECKLINK_API_VERSION) {
compat_status = "probably compatible";
}
color_printf("This UltraGrid version was compiled against DeckLink "
"SDK %s (system version %s is " TBOLD("%s") ").\n",
BLACKMAGIC_DECKLINK_API_VERSION_STRING,
currentVersionCString, compat_status);
release_bmd_api_str(current_version);
free(currentVersionCString);
cleanup:
if (APIInformation) {
APIInformation->Release();
}
#ifdef _WIN32
com_uninitialize(&com_initialized);
#endif
}
// Profile description map
static const map<BMDProfileID, pair<const char *, const char *>> kDeviceProfiles =
{
{ bmdProfileOneSubDeviceFullDuplex, { "1 sub-device full-duplex", "8K Pro, Duo 2, Quad 2" } },
{ bmdProfileOneSubDeviceHalfDuplex, { "1 sub-device half-duplex", "8K Pro" } },
{ bmdProfileTwoSubDevicesFullDuplex, { "2 sub-devices full-duplex", "8K Pro" } },
{ bmdProfileTwoSubDevicesHalfDuplex, { "2 sub-devices half-duplex", "Duo 2, Quad 2" } },
{ bmdProfileFourSubDevicesHalfDuplex, { "4 sub-devices half-duplex", "8K Pro" } },
};
#define EXIT_IF_FAILED(cmd, name) \
do {\
HRESULT result = cmd;\
if (FAILED(result)) {;\
LOG(LOG_LEVEL_ERROR) << MOD_NAME << name << ": " << bmd_hresult_to_string(result) << "\n";\
ret = {};\
goto cleanup;\
}\
} while (0)
#define RELEASE_IF_NOT_NULL(x) if (x != nullptr) { x->Release(); x = nullptr; }
static BMDProfileID GetDeckLinkProfileID(IDeckLinkProfile* profile)
{
IDeckLinkProfileAttributes* profileAttributes = nullptr;
if (HRESULT result = profile->QueryInterface(IID_IDeckLinkProfileAttributes, (void**)&profileAttributes); FAILED(result)) {
return {};
}
int64_t profileIDInt = 0;
// Get Profile ID attribute
const HRESULT res =
profileAttributes->GetInt(BMDDeckLinkProfileID, &profileIDInt);
if (SUCCEEDED(res)) {
profileAttributes->Release();
} else {
LOG(LOG_LEVEL_ERROR) << MOD_NAME << "BMDDeckLinkProfileID: "
<< bmd_hresult_to_string(res) << "\n";
}
return (BMDProfileID) profileIDInt;
}
class ProfileCallback : public IDeckLinkProfileCallback
{
public:
ProfileCallback(IDeckLinkProfile *requestedProfile) : m_requestedProfile(requestedProfile) {
m_requestedProfile->AddRef();
}
HRESULT ProfileChanging (/* in */ [[maybe_unused]] IDeckLinkProfile* profileToBeActivated, /* in */ [[maybe_unused]] BMD_BOOL streamsWillBeForcedToStop) override { return S_OK; }
HRESULT ProfileActivated (/* in */ [[maybe_unused]] IDeckLinkProfile* activatedProfile) override {
{
std::lock_guard<std::mutex> lock(m_profileActivatedMutex);
m_requestedProfileActivated = true;
}
m_profileActivatedCondition.notify_one();
return S_OK;
}
HRESULT STDMETHODCALLTYPE QueryInterface([[maybe_unused]] REFIID iid, [[maybe_unused]] LPVOID *ppv) override
{
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override { return ++m_refCount; }
ULONG STDMETHODCALLTYPE Release() override {
ULONG refCount = --m_refCount;
if (refCount == 0)
delete this;
return refCount;
}
bool WaitForProfileActivation(void) {
BMD_BOOL isActiveProfile = BMD_FALSE;
const char *profileName = kDeviceProfiles.find(GetDeckLinkProfileID(m_requestedProfile)) != kDeviceProfiles.end() ?
kDeviceProfiles.at(GetDeckLinkProfileID(m_requestedProfile)).first : "(unknown)";
if ((m_requestedProfile->IsActive(&isActiveProfile) == S_OK) && isActiveProfile) {
LOG(LOG_LEVEL_INFO) << "[DeckLink] Profile " << profileName << " already active.\n";
return true;
}
LOG(LOG_LEVEL_INFO) << "[DeckLink] Waiting for profile activation... (this may take few seconds)\n";
std::unique_lock<std::mutex> lock(m_profileActivatedMutex);
bool ret = m_profileActivatedCondition.wait_for(lock, std::chrono::seconds{5}, [&]{ return m_requestedProfileActivated; });
if (ret) {
LOG(LOG_LEVEL_NOTICE) << "[DeckLink] Profile " << profileName << " activated successfully.\n";
} else {
LOG(LOG_LEVEL_ERROR) << "[DeckLink] Profile " << profileName << " activation timeouted!\n";
}
return ret;
}
virtual ~ProfileCallback() {
m_requestedProfile->Release();
}
private:
IDeckLinkProfile *m_requestedProfile;
int m_refCount = 1;
std::condition_variable m_profileActivatedCondition;
std::mutex m_profileActivatedMutex;
bool m_requestedProfileActivated = false;
};
/**
* @param a value from BMDProfileID or bmdDuplexHalf (maximize number of IOs)
*/
bool decklink_set_profile(IDeckLink *deckLink, bmd_option const &req_profile, bool stereo) {
if (req_profile.is_default() && !stereo) {
return true;
}
if (req_profile.is_help()) {
printf("Available profiles:\n");
print_bmd_device_profiles("\t");
return false;
}
bool ret = true;
IDeckLinkProfileManager *manager = nullptr;
IDeckLinkProfileIterator *it = nullptr;
IDeckLinkProfile *profile = nullptr;
bool found = false;
ProfileCallback *p = nullptr;
if (HRESULT res = deckLink->QueryInterface(IID_IDeckLinkProfileManager, (void**)&manager)) {
const bool error = !(req_profile.is_default() && res == E_NOINTERFACE);
LOG(error ? LOG_LEVEL_ERROR : LOG_LEVEL_VERBOSE) << MOD_NAME << "Cannot set duplex - query profile manager: " << bmd_hresult_to_string(res) << "\n";
return error;
}
// set '1dfd' for stereo if profile is not set explicitly
assert(!req_profile.is_default() || stereo);
const uint32_t profileID = req_profile.is_default() ? (int64_t) bmdProfileOneSubDeviceFullDuplex : req_profile.get_int();
EXIT_IF_FAILED(manager->GetProfiles(&it), "Cannot set duplex - get profiles");
while (it->Next(&profile) == S_OK) {
IDeckLinkProfileAttributes *attributes;
int64_t id;
if (profile->QueryInterface(IID_IDeckLinkProfileAttributes,
(void**)&attributes) != S_OK) {
LOG(LOG_LEVEL_WARNING) << "[DeckLink] Cannot get profile attributes!\n";
continue;
}
if (attributes->GetInt(BMDDeckLinkProfileID, &id) == S_OK) {
if (profileID == bmdDuplexHalf) {
if (id == bmdProfileTwoSubDevicesHalfDuplex || id == bmdProfileFourSubDevicesHalfDuplex) {
found = true;
}
} else if (profileID == id) {
found = true;
}
if (found) {
p = new ProfileCallback(profile);
BMD_CHECK(manager->SetCallback(p), "IDeckLinkProfileManager::SetCallback", goto cleanup);
if (profile->SetActive() != S_OK) {
LOG(LOG_LEVEL_ERROR) << "[DeckLink] Cannot set profile!\n";
ret = false;
}
if (!p->WaitForProfileActivation()) {
ret = false;
}
}
} else {
LOG(LOG_LEVEL_WARNING) << "[DeckLink] Cannot get profile ID!\n";
}
attributes->Release();
profile->Release();
if (found) {
break;
}
}
if (ret) {
const char *fcc = (const char *) &profileID;
if (!found) {// no err but not found
MSG(WARNING,
"Did not find suitable profile for '%.4s'!\n", fcc);
ret = false;
} else {
MSG(VERBOSE, "Found/set profile for %.4s!\n", fcc);
}
}
cleanup:
RELEASE_IF_NOT_NULL(p);
RELEASE_IF_NOT_NULL(it);
RELEASE_IF_NOT_NULL(manager);
return ret;
}
static BMDProfileID decklink_get_active_profile_id(IDeckLink *decklink)
{
BMDProfileID ret{};
IDeckLinkProfileManager *manager = nullptr;
if (HRESULT result = decklink->QueryInterface(IID_IDeckLinkProfileManager, (void**)&manager); FAILED(result)) {
if (result != E_NOINTERFACE) {
LOG(LOG_LEVEL_ERROR) << "Cannot get IDeckLinkProfileManager: " << bmd_hresult_to_string(result) << "\n";
}
return {};
}
IDeckLinkProfileIterator *it = nullptr;
IDeckLinkProfile *profile = nullptr;
EXIT_IF_FAILED(manager->GetProfiles(&it), "Cannot get profiles iterator");
while (it->Next(&profile) == S_OK) {
BMD_BOOL isActiveProfile = BMD_FALSE;
if ((profile->IsActive(&isActiveProfile) == S_OK) && isActiveProfile) {
ret = GetDeckLinkProfileID(profile);
profile->Release();
break;
}
profile->Release();
}
cleanup:
RELEASE_IF_NOT_NULL(it);
RELEASE_IF_NOT_NULL(manager);
return ret;
}
bool bmd_check_stereo_profile(IDeckLink *deckLink) {
if (BMDProfileID profile_active = decklink_get_active_profile_id(deckLink)) {
if (profile_active != bmdProfileOneSubDeviceHalfDuplex &&
profile_active != bmdProfileOneSubDeviceFullDuplex) {
uint32_t profile_fcc_host = be32toh(profile_active);
log_msg(LOG_LEVEL_ERROR, MOD_NAME "Active profile '%.4s' may not be compatible with stereo mode.\n", (char *) &profile_fcc_host);
log_msg(LOG_LEVEL_INFO, MOD_NAME "Use 'profile=' parameter to set 1-subdevice mode in either '1dhd' (half) or '1dfd' (full) duplex.\n");
}
return false;
}
return true;
}
string bmd_get_device_name(IDeckLink *decklink) {
BMD_STR deviceNameString = NULL;
char * deviceNameCString = NULL;
string ret;
if (decklink->GetDisplayName((BMD_STR *) &deviceNameString) == S_OK) {
deviceNameCString = get_cstr_from_bmd_api_str(deviceNameString);
ret = deviceNameCString;
release_bmd_api_str(deviceNameString);
free(deviceNameCString);
}
return ret;
}
uint32_t bmd_read_fourcc(const char *str) {
union {
uint32_t fourcc;
char c4[4];
} u;
memset(u.c4, ' ', 4);
memcpy(u.c4, str, min(strlen(str), sizeof u.c4));
return htobe32(u.fourcc);
}
std::ostream &operator<<(std::ostream &output, REFIID iid)
{
#ifdef _WIN32
OLECHAR* guidString;
StringFromCLSID(iid, &guidString);
char buffer[128];
int ret = wcstombs(buffer, guidString, sizeof buffer);
if (ret == sizeof buffer) {
buffer[sizeof buffer - 1] = '\0';
}
output << buffer;
::CoTaskMemFree(guidString);
#else
auto flags = output.flags();
output << hex << uppercase << setfill('0') <<
setw(2) << static_cast<int>(iid.byte0) << setw(2) << static_cast<int>(iid.byte1) <<
setw(2) << static_cast<int>(iid.byte2) << setw(2) << static_cast<int>(iid.byte3) << "-" <<
setw(2) << static_cast<int>(iid.byte4) << setw(2) << static_cast<int>(iid.byte5) << "-" <<
setw(2) << static_cast<int>(iid.byte6) << setw(2) << static_cast<int>(iid.byte7) << "-" <<
setw(2) << static_cast<int>(iid.byte8) << setw(2) << static_cast<int>(iid.byte9) << "-" <<
setw(2) << static_cast<int>(iid.byte10) << setw(2) << static_cast<int>(iid.byte11) <<
setw(2) << static_cast<int>(iid.byte12) << setw(2) << static_cast<int>(iid.byte13) <<
setw(2) << static_cast<int>(iid.byte14) << setw(2) << static_cast<int>(iid.byte15);
output.flags(flags);
#endif
return output;
}
#define BMDFCC(x) {x,#x}
static const struct {
uint32_t fourcc;
const char *name;
} opt_name_map[] = {
{ 0, "Serial port Flags" },
BMDFCC(bmdDeckLinkConfigSwapSerialRxTx),
{ 0, "Video Input/Output Integers" },
BMDFCC(bmdDeckLinkConfigHDMI3DPackingFormat),
BMDFCC(bmdDeckLinkConfigBypass),
BMDFCC(bmdDeckLinkConfigClockTimingAdjustment),
{ 0, "Audio Input/Output Flags" },
BMDFCC(bmdDeckLinkConfigAnalogAudioConsumerLevels),
BMDFCC(bmdDeckLinkConfigSwapHDMICh3AndCh4OnInput),
BMDFCC(bmdDeckLinkConfigSwapHDMICh3AndCh4OnOutput),
{ 0, "Video Output Flags" },
BMDFCC(bmdDeckLinkConfigFieldFlickerRemoval),
BMDFCC(bmdDeckLinkConfigHD1080p24ToHD1080i5994Conversion),
BMDFCC(bmdDeckLinkConfig444SDIVideoOutput),
BMDFCC(bmdDeckLinkConfigBlackVideoOutputDuringCapture),
BMDFCC(bmdDeckLinkConfigLowLatencyVideoOutput),
BMDFCC(bmdDeckLinkConfigDownConversionOnAllAnalogOutput),
BMDFCC(bmdDeckLinkConfigSMPTELevelAOutput),
BMDFCC(bmdDeckLinkConfigRec2020Output),
BMDFCC(bmdDeckLinkConfigQuadLinkSDIVideoOutputSquareDivisionSplit),
BMDFCC(bmdDeckLinkConfigOutput1080pAsPsF),
{ 0, "Video Output Integers" },
BMDFCC(bmdDeckLinkConfigVideoOutputConnection),
BMDFCC(bmdDeckLinkConfigVideoOutputConversionMode),
BMDFCC(bmdDeckLinkConfigAnalogVideoOutputFlags),
BMDFCC(bmdDeckLinkConfigReferenceInputTimingOffset),
BMDFCC(bmdDeckLinkConfigReferenceOutputMode),
BMDFCC(bmdDeckLinkConfigVideoOutputIdleOperation),
BMDFCC(bmdDeckLinkConfigDefaultVideoOutputMode),
BMDFCC(bmdDeckLinkConfigDefaultVideoOutputModeFlags),
BMDFCC(bmdDeckLinkConfigSDIOutputLinkConfiguration),
BMDFCC(bmdDeckLinkConfigHDMITimecodePacking),
BMDFCC(bmdDeckLinkConfigPlaybackGroup),
{ 0, "Video Output Floats" },
BMDFCC(bmdDeckLinkConfigVideoOutputComponentLumaGain),
BMDFCC(bmdDeckLinkConfigVideoOutputComponentChromaBlueGain),
BMDFCC(bmdDeckLinkConfigVideoOutputComponentChromaRedGain),
BMDFCC(bmdDeckLinkConfigVideoOutputCompositeLumaGain),
BMDFCC(bmdDeckLinkConfigVideoOutputCompositeChromaGain),
BMDFCC(bmdDeckLinkConfigVideoOutputSVideoLumaGain),
BMDFCC(bmdDeckLinkConfigVideoOutputSVideoChromaGain),
{ 0, "Video Input Flags" },
BMDFCC(bmdDeckLinkConfigVideoInputScanning),
BMDFCC(bmdDeckLinkConfigUseDedicatedLTCInput),
BMDFCC(bmdDeckLinkConfigSDIInput3DPayloadOverride),
BMDFCC(bmdDeckLinkConfigCapture1080pAsPsF),
{ 0, "Video Input Integers" },
BMDFCC(bmdDeckLinkConfigVideoInputConnection),
BMDFCC(bmdDeckLinkConfigAnalogVideoInputFlags),
BMDFCC(bmdDeckLinkConfigVideoInputConversionMode),
BMDFCC(bmdDeckLinkConfig32PulldownSequenceInitialTimecodeFrame),
BMDFCC(bmdDeckLinkConfigVANCSourceLine1Mapping),
BMDFCC(bmdDeckLinkConfigVANCSourceLine2Mapping),
BMDFCC(bmdDeckLinkConfigVANCSourceLine3Mapping),
BMDFCC(bmdDeckLinkConfigCapturePassThroughMode),
BMDFCC(bmdDeckLinkConfigCaptureGroup),
{ 0, "Video Input Floats" },
BMDFCC(bmdDeckLinkConfigVideoInputComponentLumaGain),
BMDFCC(bmdDeckLinkConfigVideoInputComponentChromaBlueGain),
BMDFCC(bmdDeckLinkConfigVideoInputComponentChromaRedGain),
BMDFCC(bmdDeckLinkConfigVideoInputCompositeLumaGain),
BMDFCC(bmdDeckLinkConfigVideoInputCompositeChromaGain),
BMDFCC(bmdDeckLinkConfigVideoInputSVideoLumaGain),
BMDFCC(bmdDeckLinkConfigVideoInputSVideoChromaGain),
{ 0, "Keying Integers" },
BMDFCC(bmdDeckLinkConfigInternalKeyingAncillaryDataSource),
{ 0, "Audio Input Flags" },
BMDFCC(bmdDeckLinkConfigMicrophonePhantomPower),
{ 0, "Audio Input Integers" },
BMDFCC(bmdDeckLinkConfigAudioInputConnection),
{ 0, "Audio Input Floats" },
BMDFCC(bmdDeckLinkConfigAnalogAudioInputScaleChannel1),
BMDFCC(bmdDeckLinkConfigAnalogAudioInputScaleChannel2),
BMDFCC(bmdDeckLinkConfigAnalogAudioInputScaleChannel3),
BMDFCC(bmdDeckLinkConfigAnalogAudioInputScaleChannel4),
BMDFCC(bmdDeckLinkConfigDigitalAudioInputScale),
BMDFCC(bmdDeckLinkConfigMicrophoneInputGain),
{ 0, "Audio Output Integers" },
BMDFCC(bmdDeckLinkConfigAudioOutputAESAnalogSwitch),
{ 0, "Audio Output Floats" },
BMDFCC(bmdDeckLinkConfigAnalogAudioOutputScaleChannel1),
BMDFCC(bmdDeckLinkConfigAnalogAudioOutputScaleChannel2),
BMDFCC(bmdDeckLinkConfigAnalogAudioOutputScaleChannel3),
BMDFCC(bmdDeckLinkConfigAnalogAudioOutputScaleChannel4),
BMDFCC(bmdDeckLinkConfigDigitalAudioOutputScale),
BMDFCC(bmdDeckLinkConfigHeadphoneVolume),
{ 0, "Network Flags" },
BMDFCC(bmdDeckLinkConfigEthernetUseDHCP),
BMDFCC(bmdDeckLinkConfigEthernetPTPFollowerOnly),
BMDFCC(bmdDeckLinkConfigEthernetPTPUseUDPEncapsulation),
{ 0, "Network Integers" },
BMDFCC(bmdDeckLinkConfigEthernetPTPPriority1),
BMDFCC(bmdDeckLinkConfigEthernetPTPPriority2),
BMDFCC(bmdDeckLinkConfigEthernetPTPDomain),
{ 0, "Network Strings" },
BMDFCC(bmdDeckLinkConfigEthernetStaticLocalIPAddress),
BMDFCC(bmdDeckLinkConfigEthernetStaticSubnetMask),
BMDFCC(bmdDeckLinkConfigEthernetStaticGatewayIPAddress),
BMDFCC(bmdDeckLinkConfigEthernetStaticPrimaryDNS),
BMDFCC(bmdDeckLinkConfigEthernetStaticSecondaryDNS),
BMDFCC(bmdDeckLinkConfigEthernetVideoOutputAddress),
BMDFCC(bmdDeckLinkConfigEthernetAudioOutputAddress),
BMDFCC(bmdDeckLinkConfigEthernetAncillaryOutputAddress),
BMDFCC(bmdDeckLinkConfigEthernetAudioOutputChannelOrder),
{ 0, "Device Information Strings" },
BMDFCC(bmdDeckLinkConfigDeviceInformationLabel),
BMDFCC(bmdDeckLinkConfigDeviceInformationSerialNumber),
BMDFCC(bmdDeckLinkConfigDeviceInformationCompany),
BMDFCC(bmdDeckLinkConfigDeviceInformationPhone),
BMDFCC(bmdDeckLinkConfigDeviceInformationEmail),
BMDFCC(bmdDeckLinkConfigDeviceInformationDate),
{ 0, "Deck Control Integers" },
BMDFCC(bmdDeckLinkConfigDeckControlConnection),
};
static const struct {
uint32_t fourcc;
const char *name;
} val_name_map[] = {
BMDFCC(bmdVideo3DPackingSidebySideHalf),
BMDFCC(bmdVideo3DPackingLinebyLine),
BMDFCC(bmdVideo3DPackingTopAndBottom),
BMDFCC(bmdVideo3DPackingFramePacking),
BMDFCC(bmdVideo3DPackingRightOnly),
BMDFCC(bmdVideo3DPackingLeftOnly),
BMDFCC(bmdDeckLinkCapturePassthroughModeDisabled),
BMDFCC(bmdDeckLinkCapturePassthroughModeCleanSwitch),
BMDFCC(bmdIdleVideoOutputBlack),
BMDFCC(bmdIdleVideoOutputLastFrame),
BMDFCC(bmdLinkConfigurationSingleLink),
BMDFCC(bmdLinkConfigurationDualLink),
BMDFCC(bmdLinkConfigurationQuadLink),
};
#undef BMDFCC
static string fcc_to_string(uint32_t fourcc) {
for (unsigned i = 0; i < std::size(opt_name_map); ++i) {
if (opt_name_map[i].fourcc == fourcc) {
return opt_name_map[i].name;
}
}
for (unsigned i = 0; i < std::size(val_name_map); ++i) {
if (val_name_map[i].fourcc == fourcc) {
return val_name_map[i].name;
}
}
union {
char c[5];
uint32_t i;
} fcc{};
fcc.i = htobe32(fourcc);
return string("'") + fcc.c + "'";
}
bmd_option::bmd_option(bool val, bool user_spec) : m_type(type_tag::t_flag), m_user_specified(user_spec) {
m_val.b = val;
}
bmd_option::bmd_option(int64_t val, bool user_spec) : m_type(type_tag::t_int), m_user_specified(user_spec) {
m_val.i = val;
}
std::ostream &operator<<(std::ostream &output, const bmd_option &b) {
switch (b.m_type) {
case bmd_option::type_tag::t_default:
output << "(default)";
break;
case bmd_option::type_tag::t_keep:
output << "(keep)";
break;
case bmd_option::type_tag::t_flag:
output << (b.get_flag() ? "true" : "false");
break;
case bmd_option::type_tag::t_int:
if (IS_FCC(b.get_int())) {
output << fcc_to_string(b.get_int());
} else if (b.get_int() >= 0) {
auto flags = output.flags();
output << b.get_int() << " (0x" << hex
<< b.get_int() << ")";
output.flags(flags);
} else {
output << b.get_int();
}
break;
case bmd_option::type_tag::t_float: {
auto flags = output.flags();
output << fixed << b.m_val.f;
output.flags(flags);
break;
}
case bmd_option::type_tag::t_string:
output << b.m_val.s;
break;
}
return output;
}
void bmd_option::set_flag(bool val_) {
m_val.b = val_;
m_type = type_tag::t_flag;
}
void bmd_option::set_int(int64_t val_) {
m_val.i = val_;
m_type = type_tag::t_int;
m_user_specified = true;
}
void bmd_option::set_float(double val_) {
m_val.f = val_;
m_type = type_tag::t_float;
m_user_specified = true;
}
void bmd_option::set_string(const char *val_) {
strncpy(m_val.s, val_, sizeof m_val.s - 1);
m_type = type_tag::t_string;
m_user_specified = true;
}
void bmd_option::set_keep() {
m_type = type_tag::t_keep;
}
bool bmd_option::keep() const {
return m_type == type_tag::t_keep;
}
bool bmd_option::get_flag() const {
if (m_type != type_tag::t_flag) {
log_msg(LOG_LEVEL_WARNING, MOD_NAME "Option is not set to a flag but get_flag() called! Current type tag: %d\n", (int) m_type);
return {};
}
return m_val.b;
}
int64_t bmd_option::get_int() const {
if (m_type != type_tag::t_int) {
log_msg(LOG_LEVEL_WARNING, MOD_NAME "Option is not set to an int but get_int() called! Current type tag: %d\n", (int) m_type);
return {};
}
return m_val.i;
}
const char *bmd_option::get_string() const {
if (m_type != type_tag::t_string) {
MSG(WARNING,
"Option is not set to a string but get_string() called! Current "
"type tag: %d\n",
(int) m_type);
return {};
}
return m_val.s;
}
bool bmd_option::is_default() const {
return m_type == type_tag::t_default;
}
bool bmd_option::is_help() const {
return m_type == type_tag::t_string &&
strcmp(get_string(), "help") == 0;
}
bool bmd_option::is_user_set() const {
return m_user_specified;
}
static void
bmd_opt_help()
{
color_printf(TBOLD("BMD") " option syntax:\n");
color_printf("\t" TBOLD("<FourCC>=<val>") "\n\n");
color_printf(
TBOLD("<FourCC>") " must have exactly " TBOLD("4 characters") "\n");
color_printf("\n");
color_printf("The value must corresponding type is deduced accordingly:\n");
color_printf("- " TBOLD("flag") " - values on/of, true/false, yes/no\n");
color_printf("- literal " TBOLD("keep") " - keep the preset value\n");
color_printf("- literal " TBOLD(
"help") " - show help (applicable to profile only)\n");
color_printf("- " TBOLD(
"int") " - any number without decimal point\n");
color_printf("- " TBOLD(
"float") " - a number with a decimal point\n");
color_printf(
"- " TBOLD("FourCC") " - a value with len <= 4 not listed above\n");
color_printf("\n");
color_printf("If the type deduction is not working, you can use also "
"following syntax:\n");
color_printf("- \"value\" - assume the value is string\n");
color_printf("- 'vlue' - assume the value is FourCC\n");
color_printf("\n");
color_printf("List of keys:\n");
for (unsigned i = 0; i < std::size(opt_name_map); ++i) {
if (opt_name_map[i].fourcc == 0) {
color_printf("\n%s:\n", opt_name_map[0].name);
} else {
uint32_t val = htobe32(opt_name_map[i].fourcc);
color_printf("- " TBOLD("%.4s") " - %s\n",
(char *) &val, opt_name_map[i].name);
}
}
color_printf("\n");
color_printf("See also\n" TUNDERLINE(
"https://github.com/CESNET/UltraGrid/blob/master/ext-deps/"
"DeckLink/Linux/DeckLinkAPIConfiguration.h") "\nfor details.\n");
color_printf("\n");
color_printf("Incomplete " TBOLD("(!)") " list of values:\n");
color_printf("(note that the value belongs to its appropriate key)\n");
for (unsigned i = 0; i < std::size(val_name_map); ++i) {
uint32_t val = htobe32(val_name_map[i].fourcc);
color_printf("- " TBOLD("%.4s") " - %s\n", (char *) &val,
val_name_map[i].name);
}
color_printf("\n");
color_printf("Available values can be found here:\n" TUNDERLINE(
"https://github.com/CESNET/UltraGrid/blob/master/ext-deps/"
"DeckLink/Linux/DeckLinkAPI.h") "\n");
color_printf("\n");
color_printf("The actual key type and possible values must be, however "
"consutlted with:\n" TUNDERLINE(
"https://documents.blackmagicdesign.com/UserManuals/"
"DeckLinkSDKManual.pdf") "\n");
color_printf("\n");
color_printf("Examples:\n");
color_printf(TBOLD("aacl=on") " - set audio consumer levels (flag)\n");
color_printf(TBOLD("voio=blac") " - display black when no output\n");
color_printf(TBOLD("DHCP=yes") " - use DHCP config for DeckLink IP\n");
color_printf(TBOLD("DHCP=no:"
"nsip=10.0.0.3:nssm=255.255.255.0:nsgw=10.0.0.1") " - use static "
"net config for "
"DeckLink IP\n");
color_printf(TBOLD(
"noaa=239.255.194.26\\:16384:noav=239.255.194.26\\:"
"163888") " - set output "
"audio/video address\n(note that the shell will remove "
"backslash if not quoted, so you may use eg.:\nuv -t "
"'decklink:noaa=239.255.194.26\\:16384')\n");
color_printf("\n");
}