]> git.sesse.net Git - kdenlive/blob - src/blackmagic/capture.cpp
a9e5cf9a6b72f758a445b87534d5452c30365ced
[kdenlive] / src / blackmagic / capture.cpp
1 /* -LICENSE-START-
2 ** Copyright (c) 2009 Blackmagic Design
3 **
4 ** Permission is hereby granted, free of charge, to any person or organization
5 ** obtaining a copy of the software and accompanying documentation covered by
6 ** this license (the "Software") to use, reproduce, display, distribute,
7 ** execute, and transmit the Software, and to prepare derivative works of the
8 ** Software, and to permit third-parties to whom the Software is furnished to
9 ** do so, all subject to the following:
10 **
11 ** The copyright notices in the Software and this entire statement, including
12 ** the above license grant, this restriction and the following disclaimer,
13 ** must be included in all copies of the Software, in whole or in part, and
14 ** all derivative works of the Software, unless such copies or derivative
15 ** works are solely in the form of machine-executable object code generated by
16 ** a source language processor.
17 **
18 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 ** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
21 ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
22 ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
23 ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 ** DEALINGS IN THE SOFTWARE.
25 ** -LICENSE-END-
26 */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <pthread.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34
35 #include <QGLWidget>
36 #include <QDebug>
37 #include <QImage>
38 #include <QMutex>
39 #include <QPaintEvent>
40
41 #include <QtOpenGL>
42
43 #ifndef GL_TEXTURE_RECTANGLE_EXT
44 #define GL_TEXTURE_RECTANGLE_EXT GL_TEXTURE_RECTANGLE_NV
45 #endif
46
47 #include <KDebug>
48 #include <KLocale>
49
50 #include "capture.h"
51 #include "kdenlivesettings.h"
52
53 pthread_mutex_t             sleepMutex;
54 pthread_cond_t              sleepCond;
55 int                 videoOutputFile = -1;
56 int                 audioOutputFile = -1;
57
58 static BMDTimecodeFormat        g_timecodeFormat = 0;
59 static int              g_videoModeIndex = -1;
60 static int              g_audioChannels = 2;
61 static int              g_audioSampleDepth = 16;
62 static int              g_maxFrames = -1;
63 static QString              doCaptureFrame;
64 static double               g_aspect_ratio = 16.0 / 9.0;
65
66 static unsigned long            frameCount = 0;
67
68
69 class CDeckLinkGLWidget : public QGLWidget, public IDeckLinkScreenPreviewCallback
70 {
71 private:
72     QAtomicInt refCount;
73     QMutex mutex;
74     IDeckLinkInput* deckLinkIn;
75     IDeckLinkGLScreenPreviewHelper* deckLinkScreenPreviewHelper;
76     IDeckLinkVideoFrame* m_frame;
77     QColor m_backgroundColor;
78     GLuint m_texture;
79     QImage m_img;
80     double m_zx;
81     double m_zy;
82     int m_pictureWidth;
83     int m_pictureHeight;
84     bool m_transparentOverlay;
85
86 public:
87     CDeckLinkGLWidget(IDeckLinkInput* deckLinkInput, QWidget* parent);
88     // IDeckLinkScreenPreviewCallback
89     virtual HRESULT QueryInterface(REFIID iid, LPVOID *ppv);
90     virtual ULONG AddRef();
91     virtual ULONG Release();
92     virtual HRESULT DrawFrame(IDeckLinkVideoFrame* theFrame);
93     void showOverlay(QImage img, bool transparent);
94     void hideOverlay();
95
96 protected:
97     void initializeGL();
98     void paintGL();
99     void resizeGL(int width, int height);
100     /*void initializeOverlayGL();
101     void paintOverlayGL();
102     void resizeOverlayGL(int width, int height);*/
103 };
104
105 CDeckLinkGLWidget::CDeckLinkGLWidget(IDeckLinkInput* deckLinkInput, QWidget* parent) : QGLWidget(/*QGLFormat(QGL::HasOverlay | QGL::AlphaChannel),*/ parent)
106     , m_backgroundColor(KdenliveSettings::window_background())
107     , m_zx(1.0)
108     , m_zy(1.0)
109     , m_transparentOverlay(true)
110 {
111     refCount = 1;
112     deckLinkIn = deckLinkInput;
113     deckLinkScreenPreviewHelper = CreateOpenGLScreenPreviewHelper();
114 }
115
116 void CDeckLinkGLWidget::showOverlay(QImage img, bool transparent)
117 {
118     m_transparentOverlay = transparent;
119     m_img = convertToGLFormat(img);
120     m_zx = (double)m_pictureWidth / m_img.width();
121     m_zy = (double)m_pictureHeight / m_img.height();
122     if (m_transparentOverlay) {
123         glEnable(GL_BLEND);
124         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR);
125     } else {
126         glDisable(GL_BLEND);
127     }
128 }
129
130 void CDeckLinkGLWidget::hideOverlay()
131 {
132     m_img = QImage();
133     glDisable(GL_BLEND);
134 }
135
136 void    CDeckLinkGLWidget::initializeGL()
137 {
138     if (deckLinkScreenPreviewHelper != NULL) {
139         mutex.lock();
140         deckLinkScreenPreviewHelper->InitializeGL();
141         glShadeModel(GL_FLAT);
142         glDisable(GL_DEPTH_TEST);
143         glDisable(GL_CULL_FACE);
144         glDisable(GL_LIGHTING);
145         glDisable(GL_DITHER);
146         glDisable(GL_BLEND);
147
148         //Documents/images/alpha2.png");//
149         //m_texture = bindTexture(convertToGLFormat(img), GL_TEXTURE_RECTANGLE_EXT, GL_RGBA8, QGLContext::LinearFilteringBindOption);
150         mutex.unlock();
151     }
152 }
153
154 /*void CDeckLinkGLWidget::initializeOverlayGL ()
155 {
156   glDisable(GL_BLEND);
157   glEnable(GL_TEXTURE_RECTANGLE_EXT);
158
159 }
160
161 void    CDeckLinkGLWidget::paintOverlayGL()
162 {
163     makeOverlayCurrent();
164     glEnable(GL_BLEND);
165     //glClearDepth(0.5f);
166     //glPixelTransferf(GL_ALPHA_SCALE, 10);
167     //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
168
169
170 }*/
171
172 void    CDeckLinkGLWidget::paintGL()
173 {
174     mutex.lock();
175     glLoadIdentity();
176     qglClearColor(m_backgroundColor);
177     //glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
178     glClear(GL_COLOR_BUFFER_BIT);
179     deckLinkScreenPreviewHelper->PaintGL();
180     if (!m_img.isNull()) {
181         glPixelZoom(m_zx, m_zy);
182         glDrawPixels(m_img.width(), m_img.height(), GL_RGBA, GL_UNSIGNED_BYTE, m_img.bits());
183     }
184     mutex.unlock();
185 }
186 /*
187 void CDeckLinkGLWidget::paintEvent(QPaintEvent *event)
188 {
189     mutex.lock();
190     QPainter p(this);
191     QRect r = event->rect();
192     p.setClipRect(r);
193     void *frameBytes;
194     m_frame->GetBytes(&frameBytes);
195     QImage img((uchar*)frameBytes, m_frame->GetWidth(), m_frame->GetHeight(), QImage::Format_ARGB32);//m_frame->GetPixelFormat());
196     QRectF re(0, 0, width(), height());
197     p.drawImage(re, img);
198     p.end();
199     mutex.unlock();
200 }*/
201
202 void    CDeckLinkGLWidget::resizeGL(int width, int height)
203 {
204     mutex.lock();
205     m_pictureHeight = height;
206     m_pictureWidth = width;
207     int calculatedWidth = g_aspect_ratio * height;
208     if (calculatedWidth > width) m_pictureHeight = width / g_aspect_ratio;
209     else {
210         int calculatedHeight = width / g_aspect_ratio;
211         if (calculatedHeight > height) m_pictureWidth = height * g_aspect_ratio;
212     }
213     glViewport((width - m_pictureWidth) / 2, (height - m_pictureHeight) / 2, m_pictureWidth, m_pictureHeight);
214     glMatrixMode(GL_PROJECTION);
215     glLoadIdentity();
216     glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
217     glMatrixMode(GL_MODELVIEW);
218     glRasterPos2i(-1, -1);
219     if (!m_img.isNull()) {
220         m_zx = (double)m_pictureWidth / m_img.width();
221         m_zy = (double)m_pictureHeight / m_img.height();
222     }
223
224     mutex.unlock();
225 }
226
227 /*void CDeckLinkGLWidget::resizeOverlayGL ( int width, int height )
228 {
229   int newwidth = width;
230     int newheight = height;
231     int calculatedWidth = g_aspect_ratio * height;
232     if (calculatedWidth > width) newheight = width / g_aspect_ratio;
233     else {
234         int calculatedHeight = width / g_aspect_ratio;
235         if (calculatedHeight > height) newwidth = height * g_aspect_ratio;
236     }
237     glViewport((width - newwidth) / 2, (height - newheight) / 2, newwidth, newheight);
238     glMatrixMode(GL_PROJECTION);
239     glLoadIdentity();
240     glOrtho(0, width, 0, height, -1.0, 1.0);
241     glMatrixMode(GL_MODELVIEW);
242     updateOverlayGL ();
243 }*/
244
245 HRESULT     CDeckLinkGLWidget::QueryInterface(REFIID iid, LPVOID *ppv)
246 {
247     Q_UNUSED(iid);
248     *ppv = NULL;
249     return E_NOINTERFACE;
250 }
251
252 ULONG       CDeckLinkGLWidget::AddRef()
253 {
254     int     oldValue;
255
256     oldValue = refCount.fetchAndAddAcquire(1);
257     return (ULONG)(oldValue + 1);
258 }
259
260 ULONG       CDeckLinkGLWidget::Release()
261 {
262     int     oldValue;
263
264     oldValue = refCount.fetchAndAddAcquire(-1);
265     if (oldValue == 1) {
266         delete this;
267     }
268
269     return (ULONG)(oldValue - 1);
270 }
271
272 HRESULT     CDeckLinkGLWidget::DrawFrame(IDeckLinkVideoFrame* theFrame)
273 {
274     if (deckLinkScreenPreviewHelper != NULL && theFrame != NULL) {
275         /*mutex.lock();
276         m_frame = theFrame;
277         mutex.unlock();*/
278         deckLinkScreenPreviewHelper->SetFrame(theFrame);
279         update();
280     }
281     return S_OK;
282 }
283
284
285 DeckLinkCaptureDelegate::DeckLinkCaptureDelegate() : m_refCount(0)
286 {
287     pthread_mutex_init(&m_mutex, NULL);
288 }
289
290 DeckLinkCaptureDelegate::~DeckLinkCaptureDelegate()
291 {
292     pthread_mutex_destroy(&m_mutex);
293 }
294
295 ULONG DeckLinkCaptureDelegate::AddRef(void)
296 {
297     pthread_mutex_lock(&m_mutex);
298     m_refCount++;
299     pthread_mutex_unlock(&m_mutex);
300
301     return (ULONG)m_refCount;
302 }
303
304 ULONG DeckLinkCaptureDelegate::Release(void)
305 {
306     pthread_mutex_lock(&m_mutex);
307     m_refCount--;
308     pthread_mutex_unlock(&m_mutex);
309
310     if (m_refCount == 0) {
311         delete this;
312         return 0;
313     }
314
315     return (ULONG)m_refCount;
316 }
317
318 void DeckLinkCaptureDelegate::slotProcessFrame()
319 {
320     if (m_framesList.isEmpty()) return;
321     IDeckLinkVideoInputFrame* videoFrame = m_framesList.takeFirst();
322     QString capturePath = m_framePath.takeFirst();
323     void *frameBytes;
324     videoFrame->GetBytes(&frameBytes);
325     if (capturePath.endsWith("raw")) {
326         // Save as raw uyvy422 imgage
327         videoOutputFile = open(capturePath.toUtf8().constData(), O_WRONLY | O_CREAT/*|O_TRUNC*/, 0664);
328         write(videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());
329         close(videoOutputFile);
330         emit frameSaved(capturePath);
331     } else {
332         QImage image(videoFrame->GetWidth(), videoFrame->GetHeight(), QImage::Format_ARGB32_Premultiplied);
333         //convert from uyvy422 to rgba
334         CaptureHandler::uyvy2rgb((uchar *)frameBytes, (uchar *)image.bits(), videoFrame->GetWidth(), videoFrame->GetHeight());
335         image.save(capturePath);
336         emit frameSaved(capturePath);
337     }
338     videoFrame->Release();
339 }
340
341 void DeckLinkCaptureDelegate::setAnalyse(bool isOn)
342 {
343     m_analyseFrame = isOn;
344 }
345
346 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
347 {
348     IDeckLinkVideoFrame*                    rightEyeFrame = NULL;
349     IDeckLinkVideoFrame3DExtensions*        threeDExtensions = NULL;
350     void*                   frameBytes;
351     void*                   audioFrameBytes;
352
353     // Handle Video Frame
354     if (videoFrame) {
355         // If 3D mode is enabled we retreive the 3D extensions interface which gives.
356         // us access to the right eye frame by calling GetFrameForRightEye() .
357         if ((videoFrame->QueryInterface(IID_IDeckLinkVideoFrame3DExtensions, (void **) &threeDExtensions) != S_OK) ||
358                 (threeDExtensions->GetFrameForRightEye(&rightEyeFrame) != S_OK)) {
359             rightEyeFrame = NULL;
360         }
361
362         if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
363             emit gotMessage(i18n("Frame (%1) - No input signal", frameCount));
364             fprintf(stderr, "Frame received (#%lu) - No input signal detected\n", frameCount);
365         } else {
366             const char *timecodeString = NULL;
367             if (g_timecodeFormat != 0) {
368                 IDeckLinkTimecode *timecode;
369                 if (videoFrame->GetTimecode(g_timecodeFormat, &timecode) == S_OK) {
370                     timecode->GetString(&timecodeString);
371                 }
372             }
373             // There seems to be No timecode with HDMI... Using frame number
374             emit gotTimeCode(frameCount);
375             /*fprintf(stderr, "Frame received (#%lu) [%s] - %s - Size: %li bytes\n",
376                 frameCount,
377                 timecodeString != NULL ? timecodeString : "No timecode",
378                 rightEyeFrame != NULL ? "Valid Frame (3D left/right)" : "Valid Frame",
379                 videoFrame->GetRowBytes() * videoFrame->GetHeight());*/
380
381             if (timecodeString)
382                 free((void*)timecodeString);
383
384             if (!doCaptureFrame.isEmpty()) {
385                 videoFrame->AddRef();
386                 m_framesList.append(videoFrame);
387                 m_framePath.append(doCaptureFrame);
388                 doCaptureFrame.clear();
389                 QtConcurrent::run(this, &DeckLinkCaptureDelegate::slotProcessFrame);
390             }
391             if (m_analyseFrame) {
392                 QImage image(videoFrame->GetWidth(), videoFrame->GetHeight(), QImage::Format_ARGB32_Premultiplied);
393                 //convert from uyvy422 to rgba
394                 videoFrame->GetBytes(&frameBytes);
395                 CaptureHandler::uyvy2rgb((uchar *)frameBytes, (uchar *)image.bits(), videoFrame->GetWidth(), videoFrame->GetHeight());
396                 emit gotFrame(image);
397             }
398
399             if (videoOutputFile != -1) {
400                 if (!m_analyseFrame) videoFrame->GetBytes(&frameBytes);
401                 write(videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());
402
403                 if (rightEyeFrame) {
404                     rightEyeFrame->GetBytes(&frameBytes);
405                     write(videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());
406                 }
407             }
408         }
409         frameCount++;
410
411         if (g_maxFrames > 0 && frameCount >= g_maxFrames) {
412             pthread_cond_signal(&sleepCond);
413         }
414     }
415
416     // Handle Audio Frame
417     if (audioFrame) {
418         if (audioOutputFile != -1) {
419             audioFrame->GetBytes(&audioFrameBytes);
420             write(audioOutputFile, audioFrameBytes, audioFrame->GetSampleFrameCount() * g_audioChannels *(g_audioSampleDepth / 8));
421         }
422     }
423     return S_OK;
424 }
425
426 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
427 {
428     Q_UNUSED(events);
429     Q_UNUSED(mode);
430     return S_OK;
431 }
432
433 /*int usage(int status)
434 {
435     HRESULT result;
436     IDeckLinkDisplayMode *displayMode;
437     int displayModeCount = 0;
438
439     fprintf(stderr,
440         "Usage: Capture -m <mode id> [OPTIONS]\n"
441         "\n"
442         "    -m <mode id>:\n"
443     );
444
445     while (displayModeIterator->Next(&displayMode) == S_OK)
446     {
447         char *          displayModeString = NULL;
448
449         result = displayMode->GetName((const char **) &displayModeString);
450         if (result == S_OK)
451         {
452             BMDTimeValue frameRateDuration, frameRateScale;
453             displayMode->GetFrameRate(&frameRateDuration, &frameRateScale);
454
455             fprintf(stderr, "        %2d:  %-20s \t %li x %li \t %g FPS\n",
456                 displayModeCount, displayModeString, displayMode->GetWidth(), displayMode->GetHeight(), (double)frameRateScale / (double)frameRateDuration);
457
458             free(displayModeString);
459             displayModeCount++;
460         }
461
462         // Release the IDeckLinkDisplayMode object to prevent a leak
463         displayMode->Release();
464     }
465
466     fprintf(stderr,
467         "    -p <pixelformat>\n"
468         "         0:  8 bit YUV (4:2:2) (default)\n"
469         "         1:  10 bit YUV (4:2:2)\n"
470         "         2:  10 bit RGB (4:4:4)\n"
471         "    -t <format>          Print timecode\n"
472         "     rp188:  RP 188\n"
473         "      vitc:  VITC\n"
474         "    serial:  Serial Timecode\n"
475         "    -f <filename>        Filename raw video will be written to\n"
476         "    -a <filename>        Filename raw audio will be written to\n"
477         "    -c <channels>        Audio Channels (2, 8 or 16 - default is 2)\n"
478         "    -s <depth>           Audio Sample Depth (16 or 32 - default is 16)\n"
479         "    -n <frames>          Number of frames to capture (default is unlimited)\n"
480         "    -3                   Capture Stereoscopic 3D (Requires 3D Hardware support)\n"
481         "\n"
482         "Capture video and/or audio to a file. Raw video and/or audio can be viewed with mplayer eg:\n"
483         "\n"
484         "    Capture -m2 -n 50 -f video.raw -a audio.raw\n"
485         "    mplayer video.raw -demuxer rawvideo -rawvideo pal:uyvy -audiofile audio.raw -audio-demuxer 20 -rawaudio rate=48000\n"
486     );
487
488     exit(status);
489 }
490 */
491
492
493
494
495 BmdCaptureHandler::BmdCaptureHandler(QVBoxLayout *lay, QWidget *parent):
496     CaptureHandler(lay, parent),
497     previewView(NULL),
498     deckLinkIterator(NULL),
499     delegate(NULL),
500     displayMode(NULL),
501     deckLink(NULL),
502     deckLinkInput(NULL),
503     displayModeIterator(NULL)
504 {
505 }
506
507 QStringList BmdCaptureHandler::getDeviceName(QString)
508 {
509     return QStringList();
510 }
511
512 void BmdCaptureHandler::startPreview(int deviceId, int captureMode, bool audio)
513 {
514     deckLinkIterator = CreateDeckLinkIteratorInstance();
515     BMDVideoInputFlags          inputFlags = 0;
516     BMDDisplayMode              selectedDisplayMode = bmdModeNTSC;
517     BMDPixelFormat              pixelFormat = bmdFormat8BitYUV;
518     int                         displayModeCount = 0;
519     int                         exitStatus = 1;
520     //int                           ch;
521     bool                        foundDisplayMode = false;
522     HRESULT                     result = 1;
523
524     /*pthread_mutex_init(&sleepMutex, NULL);
525     pthread_cond_init(&sleepCond, NULL);*/
526     kDebug() << "/// INIT CAPTURE ON DEV: " << deviceId;
527
528     if (!deckLinkIterator) {
529         emit gotMessage(i18n("This application requires the DeckLink drivers installed."));
530         fprintf(stderr, "This application requires the DeckLink drivers installed.\n");
531         stopCapture();
532         return;
533     }
534
535     /* Connect to selected DeckLink instance */
536     for (int i = 0; i < deviceId + 1; i++)
537         result = deckLinkIterator->Next(&deckLink);
538     if (result != S_OK) {
539         fprintf(stderr, "No DeckLink PCI cards found.\n");
540         emit gotMessage(i18n("No DeckLink PCI cards found."));
541         stopCapture();
542         return;
543     }
544
545     if (deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&deckLinkInput) != S_OK) {
546         stopCapture();
547         return;
548     }
549
550     delegate = new DeckLinkCaptureDelegate();
551     delegate->setAnalyse(m_analyseFrame);
552     connect(delegate, SIGNAL(gotTimeCode(ulong)), this, SIGNAL(gotTimeCode(ulong)));
553     connect(delegate, SIGNAL(gotFrame(QImage)), this, SIGNAL(gotFrame(QImage)));
554     connect(delegate, SIGNAL(gotMessage(const QString &)), this, SIGNAL(gotMessage(const QString &)));
555     connect(delegate, SIGNAL(frameSaved(const QString)), this, SIGNAL(frameSaved(const QString)));
556     deckLinkInput->SetCallback(delegate);
557
558     previewView = new CDeckLinkGLWidget(deckLinkInput, m_parent);
559     m_layout->addWidget(previewView);
560     //previewView->resize(parent->size());
561     previewView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
562     previewView->DrawFrame(NULL);
563
564     // Obtain an IDeckLinkDisplayModeIterator to enumerate the display modes supported on output
565     result = deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
566     if (result != S_OK) {
567         emit gotMessage(i18n("Could not obtain the video output display mode iterator - result = ", result));
568         fprintf(stderr, "Could not obtain the video output display mode iterator - result = %08x\n", result);
569         stopCapture();
570         return;
571     }
572
573     g_videoModeIndex = captureMode;
574     /*g_audioChannels = 2;
575     g_audioSampleDepth = 16;*/
576
577     // Parse command line options
578     /*while ((ch = getopt(argc, argv, "?h3c:s:f:a:m:n:p:t:")) != -1)
579     {
580         switch (ch)
581         {
582             case 'm':
583                 g_videoModeIndex = atoi(optarg);
584                 break;
585             case 'c':
586                 g_audioChannels = atoi(optarg);
587                 if (g_audioChannels != 2 &&
588                     g_audioChannels != 8 &&
589                     g_audioChannels != 16)
590                 {
591                     fprintf(stderr, "Invalid argument: Audio Channels must be either 2, 8 or 16\n");
592      stopCapture();
593                 }
594                 break;
595             case 's':
596                 g_audioSampleDepth = atoi(optarg);
597                 if (g_audioSampleDepth != 16 && g_audioSampleDepth != 32)
598                 {
599                     fprintf(stderr, "Invalid argument: Audio Sample Depth must be either 16 bits or 32 bits\n");
600      stopCapture();
601                 }
602                 break;
603             case 'f':
604                 g_videoOutputFile = optarg;
605                 break;
606             case 'a':
607                 g_audioOutputFile = optarg;
608                 break;
609             case 'n':
610                 g_maxFrames = atoi(optarg);
611                 break;
612             case '3':
613                 inputFlags |= bmdVideoInputDualStream3D;
614                 break;
615             case 'p':
616                 switch(atoi(optarg))
617                 {
618                     case 0: pixelFormat = bmdFormat8BitYUV; break;
619                     case 1: pixelFormat = bmdFormat10BitYUV; break;
620                     case 2: pixelFormat = bmdFormat10BitRGB; break;
621                     default:
622                         fprintf(stderr, "Invalid argument: Pixel format %d is not valid", atoi(optarg));
623       stopCapture();
624                 }
625                 break;
626             case 't':
627                 if (!strcmp(optarg, "rp188"))
628                     g_timecodeFormat = bmdTimecodeRP188;
629                 else if (!strcmp(optarg, "vitc"))
630                     g_timecodeFormat = bmdTimecodeVITC;
631                 else if (!strcmp(optarg, "serial"))
632                     g_timecodeFormat = bmdTimecodeSerial;
633                 else
634                 {
635                     fprintf(stderr, "Invalid argument: Timecode format \"%s\" is invalid\n", optarg);
636      stopCapture();
637                 }
638                 break;
639             case '?':
640             case 'h':
641                 usage(0);
642         }
643     }*/
644
645     if (g_videoModeIndex < 0) {
646         emit gotMessage(i18n("No video mode specified"));
647         fprintf(stderr, "No video mode specified\n");
648         stopCapture();
649         return;
650     }
651
652     /*if (g_videoOutputFile != NULL)
653     {
654         videoOutputFile = open(g_videoOutputFile, O_WRONLY|O_CREAT|O_TRUNC, 0664);
655         if (videoOutputFile < 0)
656         {
657             emit gotMessage(i18n("Could not open video output file %1", g_videoOutputFile));
658             fprintf(stderr, "Could not open video output file \"%s\"\n", g_videoOutputFile);
659        stopCapture();
660         }
661     }
662     if (g_audioOutputFile != NULL)
663     {
664         audioOutputFile = open(g_audioOutputFile, O_WRONLY|O_CREAT|O_TRUNC, 0664);
665         if (audioOutputFile < 0)
666         {
667             emit gotMessage(i18n("Could not open audio output file %1", g_audioOutputFile));
668             fprintf(stderr, "Could not open audio output file \"%s\"\n", g_audioOutputFile);
669        stopCapture();
670         }
671     }*/
672
673     while (displayModeIterator->Next(&displayMode) == S_OK) {
674         if (g_videoModeIndex == displayModeCount) {
675             BMDDisplayModeSupport result;
676             const char *displayModeName;
677
678             foundDisplayMode = true;
679             displayMode->GetName(&displayModeName);
680             selectedDisplayMode = displayMode->GetDisplayMode();
681
682             g_aspect_ratio = (double) displayMode->GetWidth() / (double) displayMode->GetHeight();
683
684             deckLinkInput->DoesSupportVideoMode(selectedDisplayMode, pixelFormat, bmdVideoInputFlagDefault, &result, NULL);
685
686             if (result == bmdDisplayModeNotSupported) {
687                 emit gotMessage(i18n("The display mode %1 is not supported with the selected pixel format", displayModeName));
688                 fprintf(stderr, "The display mode %s is not supported with the selected pixel format\n", displayModeName);
689                 stopCapture();
690                 return;
691             }
692
693             if (inputFlags & bmdVideoInputDualStream3D) {
694                 if (!(displayMode->GetFlags() & bmdDisplayModeSupports3D)) {
695                     emit gotMessage(i18n("The display mode %1 is not supported with 3D", displayModeName));
696                     fprintf(stderr, "The display mode %s is not supported with 3D\n", displayModeName);
697                     stopCapture();
698                     return;
699                 }
700             }
701
702             break;
703         }
704         displayModeCount++;
705         displayMode->Release();
706     }
707
708     if (!foundDisplayMode) {
709         emit gotMessage(i18n("Invalid mode %1 specified", g_videoModeIndex));
710         fprintf(stderr, "Invalid mode %d specified\n", g_videoModeIndex);
711         stopCapture();
712         return;
713     }
714
715     result = deckLinkInput->EnableVideoInput(selectedDisplayMode, pixelFormat, inputFlags);
716     if (result != S_OK) {
717         emit gotMessage(i18n("Failed to enable video input. Is another application using the card?"));
718         fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
719         stopCapture();
720         return;
721     }
722
723     if (audio) {
724         result = deckLinkInput->EnableAudioInput(bmdAudioSampleRate48kHz, g_audioSampleDepth, g_audioChannels);
725         if (result != S_OK) {
726             stopCapture();
727             return;
728         }
729     }
730     deckLinkInput->SetScreenPreviewCallback(previewView);
731     result = deckLinkInput->StartStreams();
732     if (result != S_OK) {
733         qDebug() << "/// CAPTURE FAILED....";
734         emit gotMessage(i18n("Capture failed"));
735     }
736
737     // All Okay.
738     exitStatus = 0;
739
740     // Block main thread until signal occurs
741     /*  pthread_mutex_lock(&sleepMutex);
742         pthread_cond_wait(&sleepCond, &sleepMutex);
743         pthread_mutex_unlock(&sleepMutex);*/
744
745     /*bail:
746
747         if (videoOutputFile)
748             close(videoOutputFile);
749         if (audioOutputFile)
750             close(audioOutputFile);
751
752         if (displayModeIterator != NULL)
753         {
754             displayModeIterator->Release();
755             displayModeIterator = NULL;
756         }
757
758         if (deckLinkInput != NULL)
759         {
760             deckLinkInput->Release();
761             deckLinkInput = NULL;
762         }
763
764         if (deckLink != NULL)
765         {
766             deckLink->Release();
767             deckLink = NULL;
768         }
769
770         if (deckLinkIterator != NULL)
771             deckLinkIterator->Release();
772     */
773 }
774
775 BmdCaptureHandler::~BmdCaptureHandler()
776 {
777     stopCapture();
778 }
779
780 void BmdCaptureHandler::startCapture(const QString &path)
781 {
782     int i = 0;
783     QString videopath = path + "_video_" + QString::number(i).rightJustified(4, '0', false) + ".raw";
784     QString audiopath = path + "_audio_" + QString::number(i).rightJustified(4, '0', false) + ".raw";
785     while (QFile::exists(videopath) || QFile::exists(audiopath)) {
786         i++;
787         videopath = path + "_video_" + QString::number(i).rightJustified(4, '0', false) + ".raw";
788         audiopath = path + "_audio_" + QString::number(i).rightJustified(4, '0', false) + ".raw";
789     }
790     videoOutputFile = open(videopath.toUtf8().constData(), O_WRONLY | O_CREAT | O_TRUNC, 0664);
791     if (videoOutputFile < 0) {
792         emit gotMessage(i18n("Could not open video output file %1", videopath));
793         fprintf(stderr, "Could not open video output file \"%s\"\n", videopath.toUtf8().constData());
794         return;
795     }
796     if (KdenliveSettings::hdmicaptureaudio()) {
797         audioOutputFile = open(audiopath.toUtf8().constData(), O_WRONLY | O_CREAT | O_TRUNC, 0664);
798         if (audioOutputFile < 0) {
799             emit gotMessage(i18n("Could not open audio output file %1", audiopath));
800             fprintf(stderr, "Could not open video output file \"%s\"\n", audiopath.toUtf8().constData());
801             return;
802         }
803     }
804 }
805
806 void BmdCaptureHandler::stopCapture()
807 {
808     if (videoOutputFile)
809         close(videoOutputFile);
810     if (audioOutputFile)
811         close(audioOutputFile);
812     videoOutputFile = -1;
813     audioOutputFile = -1;
814 }
815
816 void BmdCaptureHandler::captureFrame(const QString &fname)
817 {
818     doCaptureFrame = fname;
819 }
820
821 void BmdCaptureHandler::showOverlay(QImage img, bool transparent)
822 {
823     if (previewView) previewView->showOverlay(img, transparent);
824 }
825
826 void BmdCaptureHandler::hideOverlay()
827 {
828     if (previewView) previewView->hideOverlay();
829 }
830
831 void BmdCaptureHandler::setDevice(const QString , QString)
832 {
833 }
834
835 void BmdCaptureHandler::hidePreview(bool hide)
836 {
837     if (previewView) previewView->setHidden(hide);
838 }
839
840 void BmdCaptureHandler::stopPreview()
841 {
842     if (!previewView) return;
843     if (deckLinkInput != NULL) deckLinkInput->StopStreams();
844     if (videoOutputFile)
845         close(videoOutputFile);
846     if (audioOutputFile)
847         close(audioOutputFile);
848
849     if (displayModeIterator != NULL) {
850         displayModeIterator->Release();
851         displayModeIterator = NULL;
852     }
853
854     if (deckLinkInput != NULL) {
855         deckLinkInput->Release();
856         deckLinkInput = NULL;
857     }
858
859     if (deckLink != NULL) {
860         deckLink->Release();
861         deckLink = NULL;
862     }
863
864     if (deckLinkIterator != NULL) {
865         deckLinkIterator->Release();
866         deckLinkIterator = NULL;
867     }
868
869     if (previewView != NULL) {
870         delete previewView;
871         previewView = NULL;
872     }
873
874     /*if (delegate != NULL)
875     delete delegate;*/
876
877 }