]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Report dropped frame on decklink capture
[kdenlive] / src / recmonitor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "recmonitor.h"
22 #include "gentime.h"
23 #include "mltdevicecapture.h"
24 #include "kdenlivesettings.h"
25 #include "managecapturesdialog.h"
26 #include "monitormanager.h"
27 #include "monitor.h"
28 #include "profilesdialog.h"
29
30 #include <KDebug>
31 #include <KLocale>
32 #include <KStandardDirs>
33 #include <KComboBox>
34 #include <KIO/NetAccess>
35 #include <KFileItem>
36 #include <KMessageBox>
37 #include <KApplication>
38
39 #if KDE_IS_VERSION(4,2,0)
40 #include <KDiskFreeSpaceInfo>
41 #endif
42
43 #include <QMouseEvent>
44 #include <QMenu>
45 #include <QToolButton>
46 #include <QFile>
47 #include <QDir>
48
49
50 RecMonitor::RecMonitor(QString name, MonitorManager *manager, QWidget *parent) :
51     AbstractMonitor(parent),
52     m_name(name),
53     m_isCapturing(false),
54     m_didCapture(false),
55     m_isPlaying(false),
56     m_bmCapture(NULL),
57     m_blackmagicCapturing(false),
58     m_manager(manager),
59     m_captureDevice(NULL),
60     m_analyse(false)
61 {
62     setupUi(this);
63
64     video_frame->setAttribute(Qt::WA_PaintOnScreen);
65     device_selector->setCurrentIndex(KdenliveSettings::defaultcapture());
66     connect(device_selector, SIGNAL(currentIndexChanged(int)), this, SLOT(slotVideoDeviceChanged(int)));
67
68     // Video widget holder
69     QVBoxLayout *l = new QVBoxLayout;
70     l->setContentsMargins(0, 0, 0, 0);
71     l->setSpacing(0);
72     m_videoBox = new VideoPreviewContainer();
73     m_videoBox->setContentsMargins(0, 0, 0, 0);
74     m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
75     l->addWidget(m_videoBox);
76     video_frame->setLayout(l);
77
78     QToolBar *toolbar = new QToolBar(this);
79     QHBoxLayout *layout = new QHBoxLayout;
80     layout->setContentsMargins(0, 0, 0, 0);
81     m_playIcon = KIcon("media-playback-start");
82     m_pauseIcon = KIcon("media-playback-pause");
83
84     m_discAction = toolbar->addAction(KIcon("network-connect"), i18n("Connect"));
85     connect(m_discAction, SIGNAL(triggered()), this, SLOT(slotDisconnect()));
86
87     m_rewAction = toolbar->addAction(KIcon("media-seek-backward"), i18n("Rewind"));
88     connect(m_rewAction, SIGNAL(triggered()), this, SLOT(slotRewind()));
89
90     m_playAction = toolbar->addAction(m_playIcon, i18n("Play"));
91     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotStartCapture()));
92
93     m_stopAction = toolbar->addAction(KIcon("media-playback-stop"), i18n("Stop"));
94     connect(m_stopAction, SIGNAL(triggered()), this, SLOT(slotStopCapture()));
95     m_stopAction->setEnabled(false);
96     m_fwdAction = toolbar->addAction(KIcon("media-seek-forward"), i18n("Forward"));
97     connect(m_fwdAction, SIGNAL(triggered()), this, SLOT(slotForward()));
98
99     m_recAction = toolbar->addAction(KIcon("media-record"), i18n("Record"));
100     connect(m_recAction, SIGNAL(triggered()), this, SLOT(slotRecord()));
101     m_recAction->setCheckable(true);
102
103     toolbar->addSeparator();
104
105     QAction *configAction = toolbar->addAction(KIcon("configure"), i18n("Configure"));
106     connect(configAction, SIGNAL(triggered()), this, SLOT(slotConfigure()));
107     configAction->setCheckable(false);
108
109     layout->addWidget(toolbar);
110     layout->addWidget(&m_logger);
111     layout->addWidget(&m_dvinfo);
112     m_logger.setMaxCount(10);
113     m_logger.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
114     m_logger.setFrame(false);
115     //m_logger.setInsertPolicy(QComboBox::InsertAtTop);
116
117 #if KDE_IS_VERSION(4,2,0)
118     m_freeSpace = new KCapacityBar(KCapacityBar::DrawTextInline, this);
119     m_freeSpace->setMaximumWidth(150);
120     QFontMetricsF fontMetrics(font());
121     m_freeSpace->setMaximumHeight(fontMetrics.height() * 1.2);
122     slotUpdateFreeSpace();
123     layout->addWidget(m_freeSpace);
124     connect(&m_spaceTimer, SIGNAL(timeout()), this, SLOT(slotUpdateFreeSpace()));
125     m_spaceTimer.setInterval(30000);
126     m_spaceTimer.setSingleShot(false);
127 #endif
128
129     control_frame_firewire->setLayout(layout);
130
131     slotVideoDeviceChanged(device_selector->currentIndex());
132     m_displayProcess = new QProcess;
133     m_captureProcess = new QProcess;
134
135     connect(m_captureProcess, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(slotProcessStatus(QProcess::ProcessState)));
136     connect(m_captureProcess, SIGNAL(readyReadStandardError()), this, SLOT(slotReadDvgrabInfo()));
137
138     QStringList env = QProcess::systemEnvironment();
139     env << "SDL_WINDOWID=" + QString::number(video_frame->winId());
140
141     QString videoDriver = KdenliveSettings::videodrivername();
142     if (!videoDriver.isEmpty()) {
143         if (videoDriver == "x11_noaccel") {
144             env << "SDL_VIDEO_YUV_HWACCEL=0";
145             env << "SDL_VIDEODRIVER=x11";
146         } else env << "SDL_VIDEODRIVER=" + videoDriver;
147     }
148     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
149
150     m_displayProcess->setEnvironment(env);
151
152     kDebug() << "/////// BUILDING MONITOR, ID: " << video_frame->winId();
153 }
154
155 RecMonitor::~RecMonitor()
156 {
157 #if KDE_IS_VERSION(4,2,0)
158     m_spaceTimer.stop();
159 #endif
160     delete m_captureProcess;
161     delete m_displayProcess;
162     if (m_captureDevice) delete m_captureDevice;
163 }
164
165 const QString RecMonitor::name() const
166 {
167     return m_name;
168 }
169
170 void RecMonitor::stop()
171 {
172     slotStopCapture();
173 }
174
175 void RecMonitor::start()
176 {
177 }
178
179 void RecMonitor::slotConfigure()
180 {
181     emit showConfigDialog(4, device_selector->currentIndex());
182 }
183
184 void RecMonitor::slotUpdateCaptureFolder(const QString currentProjectFolder)
185 {
186     if (KdenliveSettings::capturetoprojectfolder()) m_capturePath = currentProjectFolder;
187     else m_capturePath = KdenliveSettings::capturefolder();
188     if (m_captureProcess) m_captureProcess->setWorkingDirectory(m_capturePath);
189     if (m_captureProcess->state() != QProcess::NotRunning) {
190         if (device_selector->currentIndex() == FIREWIRE)
191             KMessageBox::information(this, i18n("You need to disconnect and reconnect in the capture monitor to apply your changes"), i18n("Capturing"));
192         else KMessageBox::information(this, i18n("You need to stop capture before your changes can be applied"), i18n("Capturing"));
193     } else slotVideoDeviceChanged(device_selector->currentIndex());
194
195 #if KDE_IS_VERSION(4,2,0)
196     // update free space info
197     slotUpdateFreeSpace();
198 #endif
199 }
200
201 void RecMonitor::slotVideoDeviceChanged(int ix)
202 {
203     QString capturefile;
204     QString capturename;
205     video_capture->setHidden(true);
206     video_frame->setHidden(false);
207     m_fwdAction->setVisible(ix == FIREWIRE);
208     m_discAction->setVisible(ix == FIREWIRE);
209     m_rewAction->setVisible(ix == FIREWIRE);
210     m_logger.setVisible(ix == BLACKMAGIC);
211     if (m_captureDevice) {
212         // MLT capture still running, abort
213         m_captureDevice->stop();
214         delete m_captureDevice;
215         m_captureDevice = NULL;
216     }
217     switch (ix) {
218     case SCREENGRAB:
219         m_discAction->setEnabled(false);
220         m_rewAction->setEnabled(false);
221         m_fwdAction->setEnabled(false);
222         m_recAction->setEnabled(true);
223         m_stopAction->setEnabled(false);
224         m_playAction->setEnabled(false);
225         if (KdenliveSettings::rmd_path().isEmpty()) {
226             QString rmdpath = KStandardDirs::findExe("recordmydesktop");
227             if (rmdpath.isEmpty()) video_frame->setPixmap(mergeSideBySide(KIcon("dialog-warning").pixmap(QSize(50, 50)), i18n("Recordmydesktop utility not found,\n please install it for screen grabs")));
228             else KdenliveSettings::setRmd_path(rmdpath);
229         }
230         if (!KdenliveSettings::rmd_path().isEmpty()) video_frame->setPixmap(mergeSideBySide(KIcon("video-display").pixmap(QSize(50, 50)), i18n("Press record button\nto start screen capture\nFiles will be saved in:\n%1", m_capturePath)));
231         //video_frame->setText(i18n("Press record button\nto start screen capture"));
232         break;
233     case VIDEO4LINUX:
234         m_discAction->setEnabled(false);
235         m_rewAction->setEnabled(false);
236         m_fwdAction->setEnabled(false);
237         m_recAction->setEnabled(true);
238         m_stopAction->setEnabled(false);
239         m_playAction->setEnabled(true);
240         checkDeviceAvailability();
241         break;
242     case BLACKMAGIC:
243         m_recAction->setEnabled(true);
244         m_stopAction->setEnabled(false);
245         m_playAction->setEnabled(true);
246
247         capturefile = m_capturePath;
248         if (!capturefile.endsWith("/")) capturefile.append("/");
249         capturename = KdenliveSettings::decklink_filename();
250         capturename.append("xxx.raw");
251         capturefile.append(capturename);
252         video_frame->setPixmap(mergeSideBySide(KIcon("camera-photo").pixmap(QSize(50, 50)), i18n("Plug your camcorder and\npress play button\nto start preview.\nFiles will be saved in:\n%1", capturefile)));
253         break;
254     default: // FIREWIRE
255         m_discAction->setEnabled(true);
256         m_recAction->setEnabled(false);
257         m_stopAction->setEnabled(false);
258         m_playAction->setEnabled(false);
259         m_rewAction->setEnabled(false);
260         m_fwdAction->setEnabled(false);
261
262         // Check that dvgab is available
263         if (KdenliveSettings::dvgrab_path().isEmpty()) {
264             QString dvgrabpath = KStandardDirs::findExe("dvgrab");
265             if (dvgrabpath.isEmpty()) video_frame->setPixmap(mergeSideBySide(KIcon("dialog-warning").pixmap(QSize(50, 50)), i18n("dvgrab utility not found,\n please install it for firewire capture")));
266             else KdenliveSettings::setDvgrab_path(dvgrabpath);
267         } else {
268             // Show capture info
269             capturefile = m_capturePath;
270             if (!capturefile.endsWith("/")) capturefile.append("/");
271             capturename = KdenliveSettings::dvgrabfilename();
272             if (capturename.isEmpty()) capturename = "capture";
273             QString extension;
274             switch (KdenliveSettings::firewireformat()) {
275             case 0:
276                 extension = ".dv";
277                 break;
278             case 1:
279             case 2:
280                 extension = ".avi";
281                 break;
282             case 3:
283                 extension = ".m2t";
284                 break;
285             }
286             capturename.append("xxx" + extension);
287             capturefile.append(capturename);
288             video_frame->setPixmap(mergeSideBySide(KIcon("network-connect").pixmap(QSize(50, 50)), i18n("Plug your camcorder and\npress connect button\nto initialize connection\nFiles will be saved in:\n%1", capturefile)));
289         }
290         break;
291     }
292 }
293
294 void RecMonitor::slotGotBlackmagicFrameNumber(ulong ix)
295 {
296     m_dvinfo.setText(QString::number(ix));
297 }
298
299 void RecMonitor::slotSetInfoMessage(const QString &message)
300 {
301     m_logger.insertItem(0, message);
302 }
303
304 QPixmap RecMonitor::mergeSideBySide(const QPixmap& pix, const QString txt)
305 {
306     QPainter p;
307     QRect r = QApplication::fontMetrics().boundingRect(QRect(0, 0, video_frame->width(), video_frame->height()), Qt::AlignLeft, txt);
308     int strWidth = r.width();
309     int strHeight = r.height();
310     int pixWidth = pix.width();
311     int pixHeight = pix.height();
312     QPixmap res(strWidth + 8 + pixWidth, qMax(strHeight, pixHeight));
313     res.fill(Qt::transparent);
314     p.begin(&res);
315     p.drawPixmap(0, 0, pix);
316     p.setPen(kapp->palette().text().color());
317     p.drawText(QRect(pixWidth + 8, 0, strWidth, strHeight), 0, txt);
318     p.end();
319     return res;
320 }
321
322
323 void RecMonitor::checkDeviceAvailability()
324 {
325     if (!KIO::NetAccess::exists(KUrl(KdenliveSettings::video4vdevice()), KIO::NetAccess::SourceSide , this)) {
326         m_playAction->setEnabled(false);
327         m_recAction->setEnabled(false);
328         video_frame->setPixmap(mergeSideBySide(KIcon("camera-web").pixmap(QSize(50, 50)), i18n("Cannot read from device %1\nPlease check drivers and access rights.", KdenliveSettings::video4vdevice())));
329         //video_frame->setText(i18n("Cannot read from device %1\nPlease check drivers and access rights.", KdenliveSettings::video4vdevice()));
330     } else //video_frame->setText(i18n("Press play or record button\nto start video capture"));
331         video_frame->setPixmap(mergeSideBySide(KIcon("camera-web").pixmap(QSize(50, 50)), i18n("Press play or record button\nto start video capture\nFiles will be saved in:\n%1", m_capturePath)));
332 }
333
334 void RecMonitor::slotDisconnect()
335 {
336     if (m_captureProcess->state() == QProcess::NotRunning) {
337         m_captureTime = KDateTime::currentLocalDateTime();
338         kDebug() << "CURRENT TIME: " << m_captureTime.toString();
339         m_didCapture = false;
340         slotStartCapture(false);
341         m_discAction->setIcon(KIcon("network-disconnect"));
342         m_discAction->setText(i18n("Disconnect"));
343         m_recAction->setEnabled(true);
344         m_stopAction->setEnabled(true);
345         m_playAction->setEnabled(true);
346         m_rewAction->setEnabled(true);
347         m_fwdAction->setEnabled(true);
348     } else {
349         m_captureProcess->write("q", 1);
350         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
351         if (m_didCapture) manageCapturedFiles();
352         m_didCapture = false;
353     }
354 }
355
356 void RecMonitor::slotRewind()
357 {
358     m_captureProcess->write("a", 1);
359 }
360
361 void RecMonitor::slotForward()
362 {
363     m_captureProcess->write("z", 1);
364 }
365
366 void RecMonitor::slotStopCapture()
367 {
368     // stop capture
369     video_capture->setHidden(true);
370     video_frame->setHidden(false);
371     switch (device_selector->currentIndex()) {
372     case FIREWIRE:
373         m_captureProcess->write("\e", 2);
374         m_playAction->setIcon(m_playIcon);
375         m_isPlaying = false;
376         break;
377     case VIDEO4LINUX:
378         if (m_captureDevice) {
379             m_captureDevice->stop();
380         }
381         m_playAction->setEnabled(true);
382         m_stopAction->setEnabled(false);
383         break;
384     case SCREENGRAB:
385         m_captureProcess->write("q\n", 3);
386         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
387         break;
388     case BLACKMAGIC:
389         if (m_captureDevice) {
390             m_captureDevice->stop();
391         }
392         //m_bmCapture->stopPreview();
393         m_playAction->setEnabled(true);
394         m_stopAction->setEnabled(false);
395         m_recAction->setEnabled(true);
396         break;
397     default:
398         break;
399     }
400 }
401
402 void RecMonitor::slotStartCapture(bool play)
403 {
404     if (m_captureProcess->state() != QProcess::NotRunning) {
405         if (device_selector->currentIndex() == FIREWIRE) {
406             if (m_isPlaying) {
407                 m_captureProcess->write("k", 1);
408                 //captureProcess->write("\e", 2);
409                 m_playAction->setIcon(m_playIcon);
410                 m_isPlaying = false;
411             } else {
412                 m_captureProcess->write("p", 1);
413                 m_playAction->setIcon(m_pauseIcon);
414                 m_isPlaying = true;
415             }
416         }
417         return;
418     }
419     m_captureArgs.clear();
420     m_displayArgs.clear();
421     m_isPlaying = false;
422     QString capturename = KdenliveSettings::dvgrabfilename();
423     QString path;
424     MltVideoProfile profile;
425     QString producer;
426     QStringList dvargs = KdenliveSettings::dvgrabextra().simplified().split(" ", QString::SkipEmptyParts);
427     //video_capture->setVisible(device_selector->currentIndex() == BLACKMAGIC);
428     //video_frame->setHidden(device_selector->currentIndex() == BLACKMAGIC);
429
430     switch (device_selector->currentIndex()) {
431     case FIREWIRE:
432         switch (KdenliveSettings::firewireformat()) {
433         case 0:
434             // RAW DV CAPTURE
435             m_captureArgs << "--format" << "raw";
436             m_displayArgs << "-f" << "dv";
437             break;
438         case 1:
439             // DV type 1
440             m_captureArgs << "--format" << "dv1";
441             m_displayArgs << "-f" << "dv";
442             break;
443         case 2:
444             // DV type 2
445             m_captureArgs << "--format" << "dv2";
446             m_displayArgs << "-f" << "dv";
447             break;
448         case 3:
449             // HDV CAPTURE
450             m_captureArgs << "--format" << "hdv";
451             m_displayArgs << "-f" << "mpegts";
452             break;
453         }
454         if (KdenliveSettings::firewireautosplit()) m_captureArgs << "--autosplit";
455         if (KdenliveSettings::firewiretimestamp()) m_captureArgs << "--timestamp";
456         if (!dvargs.isEmpty()) {
457             m_captureArgs << dvargs;
458         }
459         m_captureArgs << "-i";
460         if (capturename.isEmpty()) capturename = "capture";
461         m_captureArgs << capturename << "-";
462
463         m_displayArgs << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
464
465         m_captureProcess->setStandardOutputProcess(m_displayProcess);
466         m_captureProcess->setWorkingDirectory(m_capturePath);
467         kDebug() << "Capture: Running dvgrab " << m_captureArgs.join(" ");
468
469         m_captureProcess->start(KdenliveSettings::dvgrab_path(), m_captureArgs);
470         if (play) m_captureProcess->write(" ", 1);
471         m_discAction->setEnabled(true);
472         break;
473     case VIDEO4LINUX:
474         path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
475         m_manager->activateMonitor("record");
476         if (m_captureDevice == NULL) {
477             m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
478             connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
479             m_captureDevice->sendFrameForAnalysis = m_analyse;
480             m_manager->updateScopeSource();
481         }
482         profile = ProfilesDialog::getVideoProfile(path);
483         producer = QString("avformat-novalidate:video4linux2:%1?width:%2&height:%3&frame_rate:%4").arg(KdenliveSettings::video4vdevice()).arg(profile.width).arg(profile.height).arg((double) profile.frame_rate_num / profile.frame_rate_den);
484         kDebug()<< "PROD: "<<producer;
485         if (!m_captureDevice->slotStartPreview(producer)) {
486             // v4l capture failed to start
487             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
488             m_videoBox->setHidden(true);
489             
490         } else {
491             m_videoBox->setHidden(false);
492             m_playAction->setEnabled(false);
493             m_stopAction->setEnabled(true);
494         }
495         
496         /*m_captureArgs << KdenliveSettings::video4capture().simplified().split(' ') << KdenliveSettings::video4encoding().simplified().split(' ') << "-f" << KdenliveSettings::video4container() << "-";
497         m_displayArgs << "-f" << KdenliveSettings::video4container() << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
498         m_captureProcess->setStandardOutputProcess(m_displayProcess);
499         kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
500         m_captureProcess->start("ffmpeg", m_captureArgs);*/
501         break;
502     case BLACKMAGIC:
503         path = KdenliveSettings::current_profile();
504         m_manager->activateMonitor("record");
505         if (m_captureDevice == NULL) {
506             m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
507             m_captureDevice->sendFrameForAnalysis = m_analyse;
508             m_manager->updateScopeSource();
509         }
510         profile = ProfilesDialog::getVideoProfile(path);
511         producer = QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice());
512         if (!m_captureDevice->slotStartPreview(producer)) {
513             // v4l capture failed to start
514             video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
515             m_videoBox->setHidden(true);
516             
517         } else {
518             m_videoBox->setHidden(false);
519             m_playAction->setEnabled(false);
520             m_stopAction->setEnabled(true);
521         }
522         //m_bmCapture->startPreview(KdenliveSettings::decklink_capturedevice(), KdenliveSettings::hdmi_capturemode());
523         m_playAction->setEnabled(false);
524         m_stopAction->setEnabled(true);
525         m_recAction->setEnabled(true);
526         break;
527     default:
528         break;
529     }
530
531     if (device_selector->currentIndex() == FIREWIRE) {
532         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
533         m_displayProcess->start("ffplay", m_displayArgs);
534         video_frame->setText(i18n("Initialising..."));
535     } else {
536         // do something when starting screen grab
537     }
538 }
539
540 void RecMonitor::slotRecord()
541 {
542     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == FIREWIRE) {
543         slotStartCapture();
544     }
545     if (m_isCapturing) {
546         // User stopped capture
547         switch (device_selector->currentIndex()) {
548         case FIREWIRE:
549             m_captureProcess->write("\e", 2);
550             m_playAction->setIcon(m_playIcon);
551             m_isCapturing = false;
552             m_isPlaying = false;
553             m_recAction->setChecked(false);
554             break;
555         case VIDEO4LINUX:
556         case BLACKMAGIC:
557             slotStopCapture();
558             slotSetInfoMessage(i18n("Capture stopped"));
559             m_isCapturing = false;
560             m_recAction->setChecked(false);
561             if (autoaddbox->isChecked() && QFile::exists(m_captureFile.path())) emit addProjectClip(m_captureFile);
562             //QTimer::singleShot(1000, this, SLOT(slotStartCapture()));
563             break;
564         case SCREENGRAB:
565             //captureProcess->write("q\n", 3);
566             m_captureProcess->terminate();
567             video_frame->setText(i18n("Encoding captured video..."));
568             // in case ffmpeg doesn't exit with the 'q' command, kill it one second later
569             //QTimer::singleShot(1000, captureProcess, SLOT(kill()));
570             break;
571         }
572         return;
573     } else if (device_selector->currentIndex() == FIREWIRE) {
574         m_isCapturing = true;
575         m_didCapture = true;
576         m_captureProcess->write("c\n", 3);
577 #if KDE_IS_VERSION(4,2,0)
578         m_spaceTimer.start();
579 #endif
580         return;
581     }
582     if (m_captureProcess->state() == QProcess::NotRunning) {
583         m_recAction->setChecked(true);
584         QString extension = "mpg";
585         if (device_selector->currentIndex() == SCREENGRAB) extension = "ogv"; //KdenliveSettings::screengrabextension();
586         else if (device_selector->currentIndex() == VIDEO4LINUX) extension = KdenliveSettings::v4l_extension();
587         else if (device_selector->currentIndex() == BLACKMAGIC) extension = KdenliveSettings::decklink_extension();
588         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
589         int i = 1;
590         while (QFile::exists(path)) {
591             QString num = QString::number(i).rightJustified(4, '0', false);
592             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
593             i++;
594         }
595         m_captureFile = KUrl(path);
596
597         m_captureArgs.clear();
598         m_displayArgs.clear();
599         QString args;
600         QString playlist;
601         MltVideoProfile profile;
602         QString capturename = KdenliveSettings::dvgrabfilename();
603         if (capturename.isEmpty()) capturename = "capture";
604
605         switch (device_selector->currentIndex()) {
606         case VIDEO4LINUX:
607             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
608             profile = ProfilesDialog::getVideoProfile(path);
609             if (m_captureDevice == NULL) {
610                 m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
611                 m_captureDevice->sendFrameForAnalysis = m_analyse;
612                 m_manager->updateScopeSource();
613             }
614             playlist = QString("<mlt title=\"capture\"><producer id=\"producer0\" in=\"0\" out=\"99999\"><property name=\"mlt_type\">producer</property><property name=\"length\">100000</property><property name=\"eof\">pause</property><property name=\"resource\">video4linux2:%1?width:%2&amp;height:%3&amp;frame_rate:%4</property><property name=\"mlt_service\">avformat-novalidate</property></producer><playlist id=\"playlist0\"><entry producer=\"producer0\" in=\"0\" out=\"99999\"/></playlist>").arg(KdenliveSettings::video4vdevice()).arg(profile.width).arg(profile.height).arg((double) profile.frame_rate_num / profile.frame_rate_den);
615
616             // Add alsa audio capture
617             if (KdenliveSettings::v4l_captureaudio()) {
618                 playlist.append(QString("<producer id=\"producer1\" in=\"0\" out=\"99999\"><property name=\"mlt_type\">producer</property><property name=\"length\">100000</property><property name=\"eof\">pause</property><property name=\"resource\">alsa:%5</property><property name=\"audio_index\">0</property><property name=\"video_index\">-1</property><property name=\"mlt_service\">avformat</property></producer><playlist id=\"playlist1\"><entry producer=\"producer1\" in=\"0\" out=\"99999\"/></playlist>").arg(KdenliveSettings::v4l_alsadevicename()));
619             }
620             
621
622             playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
623
624             playlist.append("<track producer=\"playlist0\"/>");            
625
626             // Audio mix
627             if (KdenliveSettings::v4l_captureaudio()) {
628                 playlist.append("<track producer=\"playlist1\"/>");
629                 playlist.append("<transition id=\"transition0\" in=\"0\" out=\"0\"><property name=\"a_track\">0</property><property name=\"b_track\">1</property><property name=\"mlt_type\">transition</property><property name=\"mlt_service\">mix</property></transition>");
630             }
631
632             playlist.append("</tractor></mlt>");
633
634             if (m_captureDevice->slotStartCapture(KdenliveSettings::v4l_parameters(), m_captureFile.path(), playlist, enable_preview->isChecked())) {
635                 m_videoBox->setHidden(false);
636                 m_isCapturing = true;
637             }
638             else {
639                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));                
640                 m_videoBox->setHidden(true);
641                 m_isCapturing = false;
642                 m_recAction->setChecked(false);
643             }
644
645             /*
646             m_captureArgs << KdenliveSettings::video4capture().simplified().split(' ') << KdenliveSettings::video4encoding().simplified().split(' ') << "-y" << m_captureFile.path() << "-f" << KdenliveSettings::video4container() << "-acodec" << KdenliveSettings::video4acodec() << "-vcodec" << KdenliveSettings::video4vcodec() << "-";
647             m_displayArgs << "-f" << KdenliveSettings::video4container() << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
648             m_captureProcess->setStandardOutputProcess(m_displayProcess);
649             kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
650             m_captureProcess->start("ffmpeg", m_captureArgs);*/
651             break;
652             
653         case BLACKMAGIC:
654             path = KdenliveSettings::current_profile();
655             profile = ProfilesDialog::getVideoProfile(path);
656             if (m_captureDevice == NULL) {
657                 m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
658                 connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
659                 m_captureDevice->sendFrameForAnalysis = m_analyse;
660                 m_manager->updateScopeSource();
661             }
662                
663             playlist = QString("<producer id=\"producer0\" in=\"0\" out=\"99999\"><property name=\"mlt_type\">producer</property><property name=\"length\">100000</property><property name=\"eof\">pause</property><property name=\"resource\">%1</property><property name=\"mlt_service\">decklink</property></producer>").arg(KdenliveSettings::decklink_capturedevice());
664
665             if (m_captureDevice->slotStartCapture(KdenliveSettings::decklink_parameters(), m_captureFile.path(), QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice()), enable_preview->isChecked(), false)) {
666                 m_videoBox->setHidden(false);
667                 m_isCapturing = true;
668                 slotSetInfoMessage(i18n("Capturing to %1", m_captureFile.fileName()));
669             }
670             else {
671                 video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
672                 slotSetInfoMessage(i18n("Failed to start capture"));
673                 m_videoBox->setHidden(true);
674                 m_isCapturing = false;
675                 m_recAction->setChecked(false);
676             }
677             break;
678             
679         case SCREENGRAB:
680             switch (KdenliveSettings::rmd_capture_type()) {
681             case 0:
682                 // Full screen capture, nothing special to do
683                 break;
684             default:
685                 // Region capture
686                 m_captureArgs << "--width" << QString::number(KdenliveSettings::rmd_width()) << "--height" << QString::number(KdenliveSettings::rmd_height());
687                 if (!KdenliveSettings::rmd_follow_mouse()) {
688                     m_captureArgs << "-x" << QString::number(KdenliveSettings::rmd_offsetx()) << "-y" << QString::number(KdenliveSettings::rmd_offsety());
689                 } else {
690                     m_captureArgs << "--follow-mouse";
691                     if (KdenliveSettings::rmd_hide_frame()) m_captureArgs << "--no-frame";
692                 }
693                 break;
694             }
695             if (KdenliveSettings::rmd_hide_mouse()) m_captureArgs << "--no-cursor";
696             m_isCapturing = true;
697             if (KdenliveSettings::rmd_capture_audio()) {
698                 m_captureArgs << "--freq" << KdenliveSettings::rmd_freq();
699                 m_captureArgs << "--channels" << QString::number(KdenliveSettings::rmd_audio_channels());
700                 if (KdenliveSettings::rmd_use_jack()) {
701                     m_captureArgs << "--use-jack";
702                     QStringList ports = KdenliveSettings::rmd_jackports().split(" ", QString::SkipEmptyParts);
703                     for (int i = 0; i < ports.count(); ++i) {
704                         m_captureArgs << ports.at(i);
705                     }
706                     if (KdenliveSettings::rmd_jack_buffer() > 0.0)
707                         m_captureArgs << "--ring-buffer-size" << QString::number(KdenliveSettings::rmd_jack_buffer());
708                 } else {
709                     if (!KdenliveSettings::rmd_alsadevicename().isEmpty())
710                         m_captureArgs << "--device" << KdenliveSettings::rmd_alsadevicename();
711                     if (KdenliveSettings::rmd_alsa_buffer() > 0)
712                         m_captureArgs << "--buffer-size" << QString::number(KdenliveSettings::rmd_alsa_buffer());
713                 }
714             } else m_captureArgs << "--no-sound";
715
716             if (KdenliveSettings::rmd_fullshots()) m_captureArgs << "--full-shots";
717             m_captureArgs << "--v_bitrate" << QString::number(KdenliveSettings::rmd_bitrate());
718             m_captureArgs << "--v_quality" << QString::number(KdenliveSettings::rmd_quality());
719             m_captureArgs << "--workdir" << KdenliveSettings::currenttmpfolder();
720             m_captureArgs << "--fps" << QString::number(KdenliveSettings::rmd_fps()) << "-o" << m_captureFile.path();
721             m_captureProcess->start(KdenliveSettings::rmd_path(), m_captureArgs);
722             kDebug() << "// RecordMyDesktop params: " << m_captureArgs;
723             break;
724         default:
725             break;
726         }
727
728
729         if (device_selector->currentIndex() == FIREWIRE) {
730             m_isCapturing = true;
731             kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
732             m_displayProcess->start("ffplay", m_displayArgs);
733             video_frame->setText(i18n("Initialising..."));
734         }
735     } else {
736         // stop capture
737         m_displayProcess->kill();
738         //captureProcess->kill();
739         QTimer::singleShot(1000, this, SLOT(slotRecord()));
740     }
741 }
742
743 /*
744 void RecMonitor::slotStartGrab(const QRect &rect) {
745     rgnGrab->deleteLater();
746     QApplication::restoreOverrideCursor();
747     show();
748     if (rect.isNull()) return;
749     int width = rect.width();
750     int height = rect.height();
751     if (width % 2 != 0) width--;
752     if (height % 2 != 0) height--;
753     QString args = KdenliveSettings::screengrabcapture().replace("%size", QString::number(width) + "x" + QString::number(height)).replace("%offset", "+" + QString::number(rect.x()) + "," + QString::number(rect.y()));
754     if (KdenliveSettings::screengrabenableaudio()) {
755         // also capture audio
756         if (KdenliveSettings::useosscapture()) m_captureArgs << KdenliveSettings::screengrabosscapture().simplified().split(' ');
757         else m_captureArgs << KdenliveSettings::screengrabalsacapture2().simplified().split(' ');
758     }
759     m_captureArgs << args.simplified().split(' ') << KdenliveSettings::screengrabencoding().simplified().split(' ') << m_captureFile.path();
760     m_isCapturing = true;
761     video_frame->setText(i18n("Capturing..."));
762     if (KdenliveSettings::screengrabenableaudio() && !KdenliveSettings::useosscapture()) {
763         QStringList alsaArgs = KdenliveSettings::screengrabalsacapture().simplified().split(' ');
764         alsaProcess->setStandardOutputProcess(captureProcess);
765         kDebug() << "Capture: Running arecord " << alsaArgs.join(" ");
766         alsaProcess->start("arecord", alsaArgs);
767     }
768     kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
769     captureProcess->start("ffmpeg", m_captureArgs);
770 }*/
771
772 void RecMonitor::slotProcessStatus(QProcess::ProcessState status)
773 {
774     if (status == QProcess::NotRunning) {
775         m_displayProcess->kill();
776         if (m_isCapturing && device_selector->currentIndex() != FIREWIRE)
777             if (autoaddbox->isChecked() && QFile::exists(m_captureFile.path())) emit addProjectClip(m_captureFile);
778         if (device_selector->currentIndex() == FIREWIRE) {
779             m_discAction->setIcon(KIcon("network-connect"));
780             m_discAction->setText(i18n("Connect"));
781             m_playAction->setEnabled(false);
782             m_rewAction->setEnabled(false);
783             m_fwdAction->setEnabled(false);
784             m_recAction->setEnabled(false);
785         }
786         m_isPlaying = false;
787         m_playAction->setIcon(m_playIcon);
788         m_recAction->setChecked(false);
789         m_stopAction->setEnabled(false);
790         device_selector->setEnabled(true);
791         if (m_captureProcess && m_captureProcess->exitStatus() == QProcess::CrashExit) {
792             video_frame->setText(i18n("Capture crashed, please check your parameters"));
793         } else {
794             if (device_selector->currentIndex() != SCREENGRAB) {
795                 video_frame->setText(i18n("Not connected"));
796             } else {
797                 if (m_captureProcess->exitCode() != 0) {
798                     video_frame->setText(i18n("Capture crashed, please check your parameters\nRecordMyDesktop exit code: %1", QString::number(m_captureProcess->exitCode())));
799                 } else {
800                     video_frame->setPixmap(mergeSideBySide(KIcon("video-display").pixmap(QSize(50, 50)), i18n("Press record button\nto start screen capture\nFiles will be saved in:\n%1", m_capturePath)));
801                 }
802             }
803         }
804         m_isCapturing = false;
805
806 #if KDE_IS_VERSION(4,2,0)
807         m_spaceTimer.stop();
808         // update free space info
809         slotUpdateFreeSpace();
810 #endif
811
812     } else {
813         if (device_selector->currentIndex() != SCREENGRAB) m_stopAction->setEnabled(true);
814         device_selector->setEnabled(false);
815     }
816 }
817
818 void RecMonitor::manageCapturedFiles()
819 {
820     QString extension;
821     switch (KdenliveSettings::firewireformat()) {
822     case 0:
823         extension = ".dv";
824         break;
825     case 1:
826     case 2:
827         extension = ".avi";
828         break;
829     case 3:
830         extension = ".m2t";
831         break;
832     }
833     QDir dir(m_capturePath);
834     QStringList filters;
835     QString capturename = KdenliveSettings::dvgrabfilename();
836     if (capturename.isEmpty()) capturename = "capture";
837     filters << capturename + "*" + extension;
838     const QStringList result = dir.entryList(filters, QDir::Files, QDir::Time);
839     KUrl::List capturedFiles;
840     foreach(const QString & name, result) {
841         KUrl url = KUrl(dir.filePath(name));
842         if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, this)) {
843             KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url, true);
844             if (file.time(KFileItem::ModificationTime) > m_captureTime) capturedFiles.append(url);
845         }
846     }
847     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
848     kDebug() << capturedFiles;
849
850     if (capturedFiles.count() > 0) {
851         ManageCapturesDialog *d = new ManageCapturesDialog(capturedFiles, this);
852         if (d->exec() == QDialog::Accepted) {
853             capturedFiles = d->importFiles();
854             foreach(const KUrl & url, capturedFiles) {
855                 emit addProjectClip(url);
856             }
857         }
858         delete d;
859     }
860 }
861
862 // virtual
863 void RecMonitor::mousePressEvent(QMouseEvent * /*event*/)
864 {
865 #if KDE_IS_VERSION(4,2,0)
866     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
867 #endif
868 }
869
870 void RecMonitor::slotUpdateFreeSpace()
871 {
872 #if KDE_IS_VERSION(4,2,0)
873     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
874     if (info.isValid()) {
875         m_freeSpace->setValue(100 * info.used() / info.size());
876         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
877         m_freeSpace->update();
878     }
879 #endif
880 }
881
882 void RecMonitor::refreshRecMonitor(bool visible)
883 {
884     if (visible) {
885         //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
886
887     }
888 }
889
890 void RecMonitor::slotPlay()
891 {
892
893     //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
894
895 }
896
897 void RecMonitor::slotReadDvgrabInfo()
898 {
899     QString data = m_captureProcess->readAllStandardError().simplified();
900     data = data.section('"', 2, 2).simplified();
901     m_dvinfo.setText(data.left(11));
902     m_dvinfo.updateGeometry();
903 }
904
905 AbstractRender *RecMonitor::abstractRender()
906 {
907     return m_captureDevice;
908 }
909
910
911 void RecMonitor::analyseFrames(bool analyse)
912 {
913     m_analyse = analyse;
914     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
915 }
916
917 void RecMonitor::slotDroppedFrames(int dropped)
918 {
919     slotSetInfoMessage(i18n("%1 dropped frames", dropped));
920 }
921
922 #include "recmonitor.moc"
923