forked from lu-zero/bmdtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bmdcapture.cpp
1018 lines (887 loc) · 30 KB
/
bmdcapture.cpp
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
/*
* Blackmagic Devices Decklink capture
* Copyright (c) 2013 Luca Barbato.
*
* This file is part of bmdtools.
*
* bmdtools is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* bmdtools is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with bmdtools; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include "compat.h"
#include "DeckLinkAPI.h"
#include "Capture.h"
extern "C" {
#include "libavformat/avformat.h"
}
pthread_mutex_t sleepMutex;
pthread_cond_t sleepCond;
int videoOutputFile = -1;
int audioOutputFile = -1;
IDeckLink *deckLink;
IDeckLinkInput *deckLinkInput;
IDeckLinkDisplayModeIterator *displayModeIterator;
IDeckLinkDisplayMode *displayMode;
IDeckLinkConfiguration *deckLinkConfiguration;
static int g_videoModeIndex = -1;
static int g_audioChannels = 2;
static int g_audioSampleDepth = 16;
const char *g_videoOutputFile = NULL;
const char *g_audioOutputFile = NULL;
static int g_maxFrames = -1;
static int serial_fd = -1;
bool g_verbose = false;
unsigned long long g_memoryLimit = 1024 * 1024 * 1024; // 1GByte(>50 sec)
static unsigned long frameCount = 0;
static unsigned int dropped = 0, totaldropped = 0;
static enum PixelFormat pix_fmt = PIX_FMT_UYVY422;
static enum AVSampleFormat sample_fmt = AV_SAMPLE_FMT_S16;
typedef struct AVPacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
unsigned long long size;
int abort_request;
pthread_mutex_t mutex;
pthread_cond_t cond;
} AVPacketQueue;
static AVPacketQueue queue;
static AVPacket flush_pkt;
static void avpacket_queue_init(AVPacketQueue *q)
{
memset(q, 0, sizeof(AVPacketQueue));
pthread_mutex_init(&q->mutex, NULL);
pthread_cond_init(&q->cond, NULL);
}
static void avpacket_queue_flush(AVPacketQueue *q)
{
AVPacketList *pkt, *pkt1;
pthread_mutex_lock(&q->mutex);
for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
pkt1 = pkt->next;
av_free_packet(&pkt->pkt);
av_freep(&pkt);
}
q->last_pkt = NULL;
q->first_pkt = NULL;
q->nb_packets = 0;
q->size = 0;
pthread_mutex_unlock(&q->mutex);
}
static void avpacket_queue_end(AVPacketQueue *q)
{
avpacket_queue_flush(q);
pthread_mutex_destroy(&q->mutex);
pthread_cond_destroy(&q->cond);
}
static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
{
AVPacketList *pkt1;
/* duplicate the packet */
if (pkt != &flush_pkt && av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
if (!pkt1) {
return -1;
}
pkt1->pkt = *pkt;
pkt1->next = NULL;
pthread_mutex_lock(&q->mutex);
if (!q->last_pkt) {
q->first_pkt = pkt1;
} else {
q->last_pkt->next = pkt1;
}
q->last_pkt = pkt1;
q->nb_packets++;
q->size += pkt1->pkt.size + sizeof(*pkt1);
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
return 0;
}
static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret;
pthread_mutex_lock(&q->mutex);
for (;; ) {
pkt1 = q->first_pkt;
if (pkt1) {
if (pkt1->pkt.data == flush_pkt.data) {
ret = 0;
break;
}
q->first_pkt = pkt1->next;
if (!q->first_pkt) {
q->last_pkt = NULL;
}
q->nb_packets--;
q->size -= pkt1->pkt.size + sizeof(*pkt1);
*pkt = pkt1->pkt;
av_free(pkt1);
ret = 1;
break;
} else if (!block) {
ret = 0;
break;
} else {
pthread_cond_wait(&q->cond, &q->mutex);
}
}
pthread_mutex_unlock(&q->mutex);
return ret;
}
static unsigned long long avpacket_queue_size(AVPacketQueue *q)
{
unsigned long long size;
pthread_mutex_lock(&q->mutex);
size = q->size;
pthread_mutex_unlock(&q->mutex);
return size;
}
AVOutputFormat *fmt = NULL;
AVFormatContext *oc;
AVStream *audio_st, *video_st, *data_st;
BMDTimeValue frameRateDuration, frameRateScale;
static AVStream *add_audio_stream(AVFormatContext *oc, enum AVCodecID codec_id)
{
AVCodecContext *c;
AVCodec *codec;
AVStream *st;
st = avformat_new_stream(oc, NULL);
if (!st) {
fprintf(stderr, "Could not alloc stream\n");
exit(1);
}
c = st->codec;
c->codec_id = codec_id;
c->codec_type = AVMEDIA_TYPE_AUDIO;
/* put sample parameters */
c->sample_fmt = sample_fmt;
// c->bit_rate = 64000;
c->sample_rate = 48000;
c->channels = g_audioChannels;
// some formats want stream headers to be separate
if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
codec = avcodec_find_encoder(c->codec_id);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
return st;
}
static AVStream *add_video_stream(AVFormatContext *oc, enum AVCodecID codec_id)
{
AVCodecContext *c;
AVCodec *codec;
AVStream *st;
st = avformat_new_stream(oc, NULL);
if (!st) {
fprintf(stderr, "Could not alloc stream\n");
exit(1);
}
c = st->codec;
c->codec_id = codec_id;
c->codec_type = AVMEDIA_TYPE_VIDEO;
/* put sample parameters */
// c->bit_rate = 400000;
/* resolution must be a multiple of two */
c->width = displayMode->GetWidth();
c->height = displayMode->GetHeight();
/* time base: this is the fundamental unit of time (in seconds) in terms
* of which frame timestamps are represented. for fixed-fps content,
* timebase should be 1/framerate and timestamp increments should be
* identically 1.*/
displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
c->time_base.den = frameRateScale;
c->time_base.num = frameRateDuration;
c->pix_fmt = pix_fmt;
if (codec_id == AV_CODEC_ID_V210)
c->bits_per_raw_sample = 10;
// some formats want stream headers to be separate
if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
/* find the video encoder */
codec = avcodec_find_encoder(c->codec_id);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
/* open the codec */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
return st;
}
static AVStream *add_data_stream(AVFormatContext *oc, enum AVCodecID codec_id)
{
AVCodec *codec;
AVCodecContext *c;
AVStream *st;
st = avformat_new_stream(oc, NULL);
if (!st) {
fprintf(stderr, "Could not alloc stream\n");
exit(1);
}
c = st->codec;
c->codec_id = codec_id;
c->codec_type = AVMEDIA_TYPE_DATA;
displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
c->time_base.den = frameRateScale;
c->time_base.num = frameRateDuration;
// some formats want stream headers to be separate
if(oc->oformat->flags & AVFMT_GLOBALHEADER)
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
/* find the video encoder */
codec = (AVCodec*)av_malloc(sizeof(AVCodec));
memset(codec, 0, sizeof(AVCodec));
codec->id = c->codec_id;
/* open the codec */
c->codec = codec;
return st;
}
DeckLinkCaptureDelegate::DeckLinkCaptureDelegate() : m_refCount(0)
{
pthread_mutex_init(&m_mutex, NULL);
}
DeckLinkCaptureDelegate::~DeckLinkCaptureDelegate()
{
pthread_mutex_destroy(&m_mutex);
}
ULONG DeckLinkCaptureDelegate::AddRef(void)
{
pthread_mutex_lock(&m_mutex);
m_refCount++;
pthread_mutex_unlock(&m_mutex);
return (ULONG)m_refCount;
}
ULONG DeckLinkCaptureDelegate::Release(void)
{
pthread_mutex_lock(&m_mutex);
m_refCount--;
pthread_mutex_unlock(&m_mutex);
if (m_refCount == 0) {
delete this;
return 0;
}
return (ULONG)m_refCount;
}
int64_t initial_video_pts = AV_NOPTS_VALUE;
int64_t initial_audio_pts = AV_NOPTS_VALUE;
static int no_video = 0;
HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(
IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
{
void *frameBytes;
void *audioFrameBytes;
BMDTimeValue frameTime;
BMDTimeValue frameDuration;
time_t cur_time;
frameCount++;
// Handle Video Frame
if (videoFrame) {
AVPacket pkt;
AVCodecContext *c;
av_init_packet(&pkt);
c = video_st->codec;
if (g_verbose && frameCount % 25 == 0) {
unsigned long long qsize = avpacket_queue_size(&queue);
fprintf(stderr,
"Frame received (#%lu) - Valid (%liB) - QSize %f\n",
frameCount,
videoFrame->GetRowBytes() * videoFrame->GetHeight(),
(double)qsize / 1024 / 1024);
}
videoFrame->GetBytes(&frameBytes);
videoFrame->GetStreamTime(&frameTime, &frameDuration,
video_st->time_base.den);
if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
unsigned bars[8] = {
0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
int width = videoFrame->GetWidth();
int height = videoFrame->GetHeight();
unsigned *p = (unsigned *)frameBytes;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x += 2)
*p++ = bars[(x * 8) / width];
}
if (!no_video) {
time(&cur_time);
fprintf(stderr,"%s "
"Frame received (#%lu) - No input signal detected "
"- Frames dropped %u - Total dropped %u\n",
ctime(&cur_time),
frameCount, ++dropped, ++totaldropped);
}
no_video = 1;
} else {
if (no_video) {
time(&cur_time);
fprintf(stderr, "%s "
"Frame received (#%lu) - Input returned "
"- Frames dropped %u - Total dropped %u\n",
ctime(&cur_time),
frameCount, ++dropped, ++totaldropped);
}
no_video = 0;
}
pkt.pts = frameTime / video_st->time_base.num;
if (initial_video_pts == AV_NOPTS_VALUE) {
initial_video_pts = pkt.pts;
}
pkt.pts -= initial_video_pts;
pkt.dts = pkt.pts;
pkt.duration = frameDuration;
//To be made sure it still applies
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = video_st->index;
pkt.data = (uint8_t *)frameBytes;
pkt.size = videoFrame->GetRowBytes() *
videoFrame->GetHeight();
//fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
c->frame_number++;
avpacket_queue_put(&queue, &pkt);
}
// Handle Audio Frame
if (audioFrame) {
AVCodecContext *c;
AVPacket pkt;
BMDTimeValue audio_pts;
av_init_packet(&pkt);
c = audio_st->codec;
//hack among hacks
pkt.size = audioFrame->GetSampleFrameCount() *
g_audioChannels * (g_audioSampleDepth / 8);
audioFrame->GetBytes(&audioFrameBytes);
audioFrame->GetPacketTime(&audio_pts, audio_st->time_base.den);
pkt.pts = audio_pts / audio_st->time_base.num;
if (initial_audio_pts == AV_NOPTS_VALUE) {
initial_audio_pts = pkt.pts;
}
pkt.pts -= initial_audio_pts;
pkt.dts = pkt.pts;
//fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = audio_st->index;
pkt.data = (uint8_t *)audioFrameBytes;
//pkt.size= avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);
c->frame_number++;
//write(audioOutputFile, audioFrameBytes, audioFrame->GetSampleFrameCount() * g_audioChannels * (g_audioSampleDepth / 8));
/* if (av_interleaved_write_frame(oc, &pkt) != 0) {
* fprintf(stderr, "Error while writing audio frame\n");
* exit(1);
* } */
avpacket_queue_put(&queue, &pkt);
}
if (serial_fd > 0) {
AVPacket pkt;
char line[8] = {0};
int count = read(serial_fd, line, 7);
if (count > 0)
fprintf(stderr, "read %d bytes: %s \n", count, line);
else line[0] = ' ';
av_init_packet(&pkt);
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index= data_st->index;
pkt.data = (uint8_t*)line;
pkt.size = 7;
pkt.pts = frameTime / video_st->time_base.num;
pkt.pts -= initial_video_pts;
pkt.dts = pkt.pts;
avpacket_queue_put(&queue, &pkt);
}
return S_OK;
}
HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(
BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
BMDDetectedVideoInputFormatFlags)
{
return S_OK;
}
void print_output_modes(IDeckLink *deckLink)
{
IDeckLinkInput *deckLinkInput = NULL;
IDeckLinkDisplayModeIterator *displayModeIterator = NULL;
IDeckLinkDisplayMode *displayMode = NULL;
HRESULT result;
int displayModeCount = 0;
// Query the DeckLink for its configuration interface
result = deckLink->QueryInterface(IID_IDeckLinkInput,
(void **)&deckLinkInput);
if (result != S_OK) {
fprintf(
stderr,
"Could not obtain the IDeckLinkInput interface - result = %08x\n",
result);
goto bail;
}
// Obtain an IDeckLinkDisplayModeIterator to enumerate the display modes supported on output
result = deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
if (result != S_OK) {
fprintf(
stderr,
"Could not obtain the video output display mode iterator - result = %08x\n",
result);
goto bail;
}
// List all supported output display modes
printf("Supported video output display modes and pixel formats:\n");
while (displayModeIterator->Next(&displayMode) == S_OK) {
BMDProbeString str;
result = displayMode->GetName(&str);
if (result == S_OK) {
char modeName[64];
int modeWidth;
int modeHeight;
BMDTimeValue frameRateDuration;
BMDTimeScale frameRateScale;
int pixelFormatIndex = 0; // index into the gKnownPixelFormats / gKnownFormatNames arrays
BMDDisplayModeSupport displayModeSupport;
// Obtain the display mode's properties
modeWidth = displayMode->GetWidth();
modeHeight = displayMode->GetHeight();
displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
printf(" %2d: %-20s \t %d x %d \t %7g FPS\n",
displayModeCount++, ToStr(str), modeWidth, modeHeight,
(double)frameRateScale / (double)frameRateDuration);
FreeStr(str);
}
// Release the IDeckLinkDisplayMode object to prevent a leak
displayMode->Release();
}
// printf("\n");
bail:
// Ensure that the interfaces we obtained are released to prevent a memory leak
if (displayModeIterator != NULL) {
displayModeIterator->Release();
}
if (deckLinkInput != NULL) {
deckLinkInput->Release();
}
}
int usage(int status)
{
HRESULT result;
IDeckLinkIterator *deckLinkIterator;
IDeckLink *deckLink;
int numDevices = 0;
// int displayModeCount = 0;
fprintf(stderr,
"Usage: bmdcapture -m <mode id> [OPTIONS]\n"
"\n"
" -m <mode id>:\n"
);
// Create an IDeckLinkIterator object to enumerate all DeckLink cards in the system
deckLinkIterator = CreateDeckLinkIteratorInstance();
if (deckLinkIterator == NULL) {
fprintf(
stderr,
"A DeckLink iterator could not be created. The DeckLink drivers may not be installed.\n");
return 1;
}
// Enumerate all cards in this system
while (deckLinkIterator->Next(&deckLink) == S_OK) {
BMDProbeString str;
// Increment the total number of DeckLink cards found
numDevices++;
if (numDevices > 1) {
printf("\n\n");
}
// *** Print the model name of the DeckLink card
result = deckLink->GetModelName(&str);
if (result == S_OK) {
printf("-> %s (-C %d )\n\n",
ToStr(str),
numDevices - 1);
FreeStr(str);
}
print_output_modes(deckLink);
// Release the IDeckLink instance when we've finished with it to prevent leaks
deckLink->Release();
}
deckLinkIterator->Release();
// If no DeckLink cards were found in the system, inform the user
if (numDevices == 0) {
printf("No Blackmagic Design devices were found.\n");
}
printf("\n");
/*
* if (displayModeIterator)
* {
* // we try to print out some useful information about the chosen
* // card, but this only works if a card has been selected successfully
*
* while (displayModeIterator->Next(&displayMode) == S_OK)
* {
* char * displayModeString = NULL;
*
* result = displayMode->GetName((const char **) &displayModeString);
* if (result == S_OK)
* {
* BMDTimeValue frameRateDuration, frameRateScale;
* displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
* fprintf(stderr, " %2d: %-20s \t %li x %li \t %g FPS\n",
* displayModeCount, displayModeString, displayMode->GetWidth(), displayMode->GetHeight(), (double)frameRateScale / (double)frameRateDuration);
* free(displayModeString);
* displayModeCount++;
* }
*
* // Release the IDeckLinkDisplayMode object to prevent a leak
* displayMode->Release();
* }
* }
*/
fprintf(
stderr,
" -v Be verbose (report each 25 frames)\n"
" -f <filename> Filename raw video will be written to\n"
" -F <format> Define the file format to be used\n"
" -c <channels> Audio Channels (2, 8 or 16 - default is 2)\n"
" -s <depth> Audio Sample Depth (16 or 32 - default is 16)\n"
" -p <pixel> PixelFormat Depth (8 or 10 - default is 8)\n"
" -n <frames> Number of frames to capture (default is unlimited)\n"
" -M <memlimit> Maximum queue size in GB (default is 1 GB)\n"
" -C <num> number of card to be used\n"
" -S <serial_device> data input serial\n"
" -A <audio-in> Audio input:\n"
" 1: Analog (RCA or XLR)\n"
" 2: Embedded Audio (HDMI/SDI)\n"
" 3: Digital Audio (AES/EBU)\n"
" -V <video-in> Video input:\n"
" 1: Composite\n"
" 2: Component\n"
" 3: HDMI\n"
" 4: SDI\n"
" 5: Optical SDI\n"
" 6: S-Video\n"
"Capture video and audio to a file. Raw video and audio can be sent to a pipe to avconv or vlc e.g.:\n"
"\n"
" bmdcapture -m 2 -A 1 -V 1 -F nut -f pipe:1\n\n\n"
);
exit(status);
}
static void *push_packet(void *ctx)
{
AVFormatContext *s = (AVFormatContext *)ctx;
AVPacket pkt;
int ret;
while (avpacket_queue_get(&queue, &pkt, 1)) {
av_interleaved_write_frame(s, &pkt);
if (g_maxFrames > 0 && frameCount >= g_maxFrames ||
avpacket_queue_size(&queue) > g_memoryLimit) {
pthread_cond_signal(&sleepCond);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
IDeckLinkIterator *deckLinkIterator = CreateDeckLinkIteratorInstance();
DeckLinkCaptureDelegate *delegate;
BMDDisplayMode selectedDisplayMode = bmdModeNTSC;
int displayModeCount = 0;
int exitStatus = 1;
int aconnection = 0, vconnection = 0, camera = 0, i = 0;
int ch;
BMDPixelFormat pix = bmdFormat8BitYUV;
HRESULT result;
pthread_t th;
pthread_mutex_init(&sleepMutex, NULL);
pthread_cond_init(&sleepCond, NULL);
av_register_all();
if (!deckLinkIterator) {
fprintf(stderr,
"This application requires the DeckLink drivers installed.\n");
goto bail;
}
// Parse command line options
while ((ch = getopt(argc, argv, "?hvc:s:f:a:m:n:p:M:F:C:A:V:")) != -1) {
switch (ch) {
case 'v':
g_verbose = true;
break;
case 'm':
g_videoModeIndex = atoi(optarg);
break;
case 'c':
g_audioChannels = atoi(optarg);
if (g_audioChannels != 2 &&
g_audioChannels != 8 &&
g_audioChannels != 16) {
fprintf(
stderr,
"Invalid argument: Audio Channels must be either 2, 8 or 16\n");
goto bail;
}
break;
case 's':
g_audioSampleDepth = atoi(optarg);
switch (g_audioSampleDepth) {
case 16:
sample_fmt = AV_SAMPLE_FMT_S16;
break;
case 32:
sample_fmt = AV_SAMPLE_FMT_S32;
break;
default:
fprintf(stderr,
"Invalid argument:"
" Audio Sample Depth must be either 16 bits"
" or 32 bits\n");
goto bail;
}
break;
case 'p':
switch (atoi(optarg)) {
case 8:
pix = bmdFormat8BitYUV;
pix_fmt = PIX_FMT_UYVY422;
break;
case 10:
pix = bmdFormat10BitYUV;
pix_fmt = PIX_FMT_YUV422P10;
break;
default:
fprintf(
stderr,
"Invalid argument: Pixel Format Depth must be either 8 bits or 10 bits\n");
goto bail;
}
break;
case 'f':
g_videoOutputFile = optarg;
break;
case 'n':
g_maxFrames = atoi(optarg);
break;
case 'M':
g_memoryLimit = atoi(optarg) * 1024 * 1024 * 1024L;
break;
case 'F':
fmt = av_guess_format(optarg, NULL, NULL);
break;
case 'A':
aconnection = atoi(optarg);
break;
case 'V':
vconnection = atoi(optarg);
break;
case 'C':
camera = atoi(optarg);
break;
case 'S':
serial_fd = open(optarg, O_RDWR | O_NONBLOCK);
break;
case '?':
case 'h':
usage(0);
}
}
/* Connect to the first DeckLink instance */
do
result = deckLinkIterator->Next(&deckLink);
while (i++ < camera);
if (result != S_OK) {
fprintf(stderr, "No DeckLink PCI cards found.\n");
goto bail;
}
if (deckLink->QueryInterface(IID_IDeckLinkInput,
(void **)&deckLinkInput) != S_OK) {
goto bail;
}
result = deckLink->QueryInterface(IID_IDeckLinkConfiguration,
(void **)&deckLinkConfiguration);
if (result != S_OK) {
fprintf(
stderr,
"Could not obtain the IDeckLinkConfiguration interface - result = %08x\n",
result);
goto bail;
}
result = S_OK;
switch (aconnection) {
case 1:
result = DECKLINK_SET_AUDIO_CONNECTION(bmdAudioConnectionAnalog);
break;
case 2:
result = DECKLINK_SET_AUDIO_CONNECTION(bmdAudioConnectionEmbedded);
break;
case 3:
result = DECKLINK_SET_AUDIO_CONNECTION(bmdAudioConnectionAESEBU);
break;
default:
// do not change it
break;
}
if (result != S_OK) {
fprintf(stderr, "Failed to set audio input - result = %08x\n", result);
goto bail;
}
result = S_OK;
switch (vconnection) {
case 1:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionComposite);
break;
case 2:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionComponent);
break;
case 3:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionHDMI);
break;
case 4:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionSDI);
break;
case 5:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionOpticalSDI);
break;
case 6:
result = DECKLINK_SET_VIDEO_CONNECTION(bmdVideoConnectionSVideo);
break;
default:
// do not change it
break;
}
if (result != S_OK) {
fprintf(stderr, "Failed to set video input - result %08x\n", result);
goto bail;
}
delegate = new DeckLinkCaptureDelegate();
deckLinkInput->SetCallback(delegate);
// Obtain an IDeckLinkDisplayModeIterator to enumerate the display modes supported on output
result = deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
if (result != S_OK) {
fprintf(
stderr,
"Could not obtain the video output display mode iterator - result = %08x\n",
result);
goto bail;
}
if (!g_videoOutputFile) {
fprintf(stderr,
"Missing argument: Please specify output path using -f\n");
goto bail;
}
if (!fmt) {
fmt = av_guess_format(NULL, g_videoOutputFile, NULL);
if (!fmt) {
fprintf(
stderr,
"Unable to guess output format, please specify explicitly using -F\n");
goto bail;
}
}
if (g_videoModeIndex < 0) {
fprintf(stderr, "No video mode specified\n");
usage(0);
}
selectedDisplayMode = -1;
while (displayModeIterator->Next(&displayMode) == S_OK) {
if (g_videoModeIndex == displayModeCount) {
selectedDisplayMode = displayMode->GetDisplayMode();
break;
}
displayModeCount++;
displayMode->Release();
}
if (selectedDisplayMode < 0) {
fprintf(stderr, "Invalid mode %d specified\n", g_videoModeIndex);
goto bail;
}
result = deckLinkInput->EnableVideoInput(selectedDisplayMode, pix, 0);
if (result != S_OK) {
fprintf(stderr,
"Failed to enable video input. Is another application using "
"the card?\n");
goto bail;
}
result = deckLinkInput->EnableAudioInput(bmdAudioSampleRate48kHz,
g_audioSampleDepth,
g_audioChannels);
if (result != S_OK) {
fprintf(stderr,
"Failed to enable audio input. Is another application using "
"the card?\n");
goto bail;
}
oc = avformat_alloc_context();
oc->oformat = fmt;
snprintf(oc->filename, sizeof(oc->filename), "%s", g_videoOutputFile);
fmt->video_codec = (pix == bmdFormat8BitYUV ? AV_CODEC_ID_RAWVIDEO : AV_CODEC_ID_V210);
fmt->audio_codec = (sample_fmt == AV_SAMPLE_FMT_S16 ? AV_CODEC_ID_PCM_S16LE : AV_CODEC_ID_PCM_S32LE);
video_st = add_video_stream(oc, fmt->video_codec);
audio_st = add_audio_stream(oc, fmt->audio_codec);
if (serial_fd > 0)
data_st = add_data_stream(oc, AV_CODEC_ID_TEXT);
if (!(fmt->flags & AVFMT_NOFILE)) {
if (avio_open(&oc->pb, oc->filename, AVIO_FLAG_WRITE) < 0) {
fprintf(stderr, "Could not open '%s'\n", oc->filename);
exit(1);
}
}
avformat_write_header(oc, NULL);
avpacket_queue_init(&queue);
result = deckLinkInput->StartStreams();
if (result != S_OK) {
goto bail;
}
// All Okay.
exitStatus = 0;
if (pthread_create(&th, NULL, push_packet, oc))
goto bail;
// Block main thread until signal occurs
pthread_mutex_lock(&sleepMutex);
pthread_cond_wait(&sleepCond, &sleepMutex);
pthread_mutex_unlock(&sleepMutex);
deckLinkInput->StopStreams();
fprintf(stderr, "Stopping Capture\n");
avpacket_queue_end(&queue);
bail:
if (displayModeIterator != NULL) {
displayModeIterator->Release();
displayModeIterator = NULL;
}
if (deckLinkInput != NULL) {
deckLinkInput->Release();
deckLinkInput = NULL;
}
if (deckLink != NULL) {