]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Fix firewire 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(slotStartPreview()));
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     
139     QString videoDriver = KdenliveSettings::videodrivername();
140 #if QT_VERSION >= 0x040600
141     QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
142     env.insert("SDL_WINDOWID", QString::number(video_frame->winId()));
143     if (!videoDriver.isEmpty()) {
144         if (videoDriver == "x11_noaccel") {
145             env.insert("SDL_VIDEO_YUV_HWACCEL", "0");
146             env.insert("SDL_VIDEODRIVER", "x11");
147         } else env.insert("SDL_VIDEODRIVER", videoDriver);
148     }
149     m_displayProcess->setProcessEnvironment(env);
150 #else
151     QStringList env = QProcess::systemEnvironment();
152     env << "SDL_WINDOWID=" + QString::number(video_frame->winId());
153     if (!videoDriver.isEmpty()) {
154         if (videoDriver == "x11_noaccel") {
155             env << "SDL_VIDEO_YUV_HWACCEL=0";
156             env << "SDL_VIDEODRIVER=x11";
157         } else env << "SDL_VIDEODRIVER=" + videoDriver;
158     }
159     m_displayProcess->setEnvironment(env);
160 #endif
161     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
162
163     kDebug() << "/////// BUILDING MONITOR, ID: " << video_frame->winId();
164 }
165
166 RecMonitor::~RecMonitor()
167 {
168 #if KDE_IS_VERSION(4,2,0)
169     m_spaceTimer.stop();
170 #endif
171     delete m_captureProcess;
172     delete m_displayProcess;
173     if (m_captureDevice) delete m_captureDevice;
174 }
175
176 const QString RecMonitor::name() const
177 {
178     return m_name;
179 }
180
181 void RecMonitor::stop()
182 {
183     slotStopCapture();
184 }
185
186 void RecMonitor::start()
187 {
188 }
189
190 void RecMonitor::slotConfigure()
191 {
192     emit showConfigDialog(4, device_selector->currentIndex());
193 }
194
195 void RecMonitor::slotUpdateCaptureFolder(const QString currentProjectFolder)
196 {
197     if (KdenliveSettings::capturetoprojectfolder()) m_capturePath = currentProjectFolder;
198     else m_capturePath = KdenliveSettings::capturefolder();
199     if (m_captureProcess) m_captureProcess->setWorkingDirectory(m_capturePath);
200     if (m_captureProcess->state() != QProcess::NotRunning) {
201         if (device_selector->currentIndex() == FIREWIRE)
202             KMessageBox::information(this, i18n("You need to disconnect and reconnect in the capture monitor to apply your changes"), i18n("Capturing"));
203         else KMessageBox::information(this, i18n("You need to stop capture before your changes can be applied"), i18n("Capturing"));
204     } else slotVideoDeviceChanged(device_selector->currentIndex());
205
206 #if KDE_IS_VERSION(4,2,0)
207     // update free space info
208     slotUpdateFreeSpace();
209 #endif
210 }
211
212 void RecMonitor::slotVideoDeviceChanged(int ix)
213 {
214     QString capturefile;
215     QString capturename;
216     video_capture->setHidden(true);
217     video_frame->setHidden(false);
218     m_videoBox->setHidden(true);
219     enable_preview->setHidden(ix != VIDEO4LINUX && ix != BLACKMAGIC);
220     m_fwdAction->setVisible(ix == FIREWIRE);
221     m_discAction->setVisible(ix == FIREWIRE);
222     m_rewAction->setVisible(ix == FIREWIRE);
223     m_recAction->setEnabled(ix != FIREWIRE);
224     m_logger.setVisible(ix == BLACKMAGIC);
225     if (m_captureDevice) {
226         // MLT capture still running, abort
227         m_captureDevice->stop();
228         delete m_captureDevice;
229         m_captureDevice = NULL;
230         m_manager->clearScopeSource();
231     }
232     switch (ix) {
233     case SCREENGRAB:
234         m_discAction->setEnabled(false);
235         m_rewAction->setEnabled(false);
236         m_fwdAction->setEnabled(false);
237         m_stopAction->setEnabled(false);
238         m_playAction->setEnabled(false);
239         if (KdenliveSettings::rmd_path().isEmpty()) {
240             QString rmdpath = KStandardDirs::findExe("recordmydesktop");
241             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")));
242             else KdenliveSettings::setRmd_path(rmdpath);
243         }
244         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)));
245         //video_frame->setText(i18n("Press record button\nto start screen capture"));
246         break;
247     case VIDEO4LINUX:
248         m_stopAction->setEnabled(false);
249         m_playAction->setEnabled(true);
250         checkDeviceAvailability();
251         break;
252     case BLACKMAGIC:
253         m_stopAction->setEnabled(false);
254         m_playAction->setEnabled(true);
255         capturefile = m_capturePath;
256         if (!capturefile.endsWith("/")) capturefile.append("/");
257         capturename = KdenliveSettings::decklink_filename();
258         capturename.append("xxx.");
259         capturename.append(KdenliveSettings::decklink_extension());
260         capturefile.append(capturename);
261         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)));
262         break;
263     default: // FIREWIRE
264         m_discAction->setEnabled(true);
265         m_stopAction->setEnabled(false);
266         m_playAction->setEnabled(false);
267         m_rewAction->setEnabled(false);
268         m_fwdAction->setEnabled(false);
269
270         // Check that dvgab is available
271         if (KdenliveSettings::dvgrab_path().isEmpty()) {
272             QString dvgrabpath = KStandardDirs::findExe("dvgrab");
273             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")));
274             else KdenliveSettings::setDvgrab_path(dvgrabpath);
275         } else {
276             // Show capture info
277             capturefile = m_capturePath;
278             if (!capturefile.endsWith("/")) capturefile.append("/");
279             capturename = KdenliveSettings::dvgrabfilename();
280             if (capturename.isEmpty()) capturename = "capture";
281             QString extension;
282             switch (KdenliveSettings::firewireformat()) {
283             case 0:
284                 extension = ".dv";
285                 break;
286             case 1:
287             case 2:
288                 extension = ".avi";
289                 break;
290             case 3:
291                 extension = ".m2t";
292                 break;
293             }
294             capturename.append("xxx" + extension);
295             capturefile.append(capturename);
296             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)));
297         }
298         break;
299     }
300 }
301
302 void RecMonitor::slotGotBlackmagicFrameNumber(ulong ix)
303 {
304     m_dvinfo.setText(QString::number(ix));
305 }
306
307 void RecMonitor::slotSetInfoMessage(const QString &message)
308 {
309     m_logger.insertItem(0, message);
310 }
311
312 QPixmap RecMonitor::mergeSideBySide(const QPixmap& pix, const QString txt)
313 {
314     QPainter p;
315     QRect r = QApplication::fontMetrics().boundingRect(QRect(0, 0, video_frame->width(), video_frame->height()), Qt::AlignLeft, txt);
316     int strWidth = r.width();
317     int strHeight = r.height();
318     int pixWidth = pix.width();
319     int pixHeight = pix.height();
320     QPixmap res(strWidth + 8 + pixWidth, qMax(strHeight, pixHeight));
321     res.fill(Qt::transparent);
322     p.begin(&res);
323     p.drawPixmap(0, 0, pix);
324     p.setPen(kapp->palette().text().color());
325     p.drawText(QRect(pixWidth + 8, 0, strWidth, strHeight), 0, txt);
326     p.end();
327     return res;
328 }
329
330
331 void RecMonitor::checkDeviceAvailability()
332 {
333     if (!KIO::NetAccess::exists(KUrl(KdenliveSettings::video4vdevice()), KIO::NetAccess::SourceSide , this)) {
334         m_playAction->setEnabled(false);
335         m_recAction->setEnabled(false);
336         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())));
337         //video_frame->setText(i18n("Cannot read from device %1\nPlease check drivers and access rights.", KdenliveSettings::video4vdevice()));
338     } else //video_frame->setText(i18n("Press play or record button\nto start video capture"));
339         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)));
340 }
341
342 void RecMonitor::slotDisconnect()
343 {
344     if (m_captureProcess->state() == QProcess::NotRunning) {
345         m_captureTime = KDateTime::currentLocalDateTime();
346         kDebug() << "CURRENT TIME: " << m_captureTime.toString();
347         m_didCapture = false;
348         slotStartPreview(false);
349         m_discAction->setIcon(KIcon("network-disconnect"));
350         m_discAction->setText(i18n("Disconnect"));
351         m_recAction->setEnabled(true);
352         m_stopAction->setEnabled(true);
353         m_playAction->setEnabled(true);
354         m_rewAction->setEnabled(true);
355         m_fwdAction->setEnabled(true);
356     } else {
357         m_captureProcess->write("q", 1);
358         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
359         if (m_didCapture) manageCapturedFiles();
360         m_didCapture = false;
361     }
362 }
363
364 void RecMonitor::slotRewind()
365 {
366     m_captureProcess->write("a", 1);
367 }
368
369 void RecMonitor::slotForward()
370 {
371     m_captureProcess->write("z", 1);
372 }
373
374 void RecMonitor::slotStopCapture()
375 {
376     // stop capture
377     if (!m_isCapturing && !m_isPlaying) return;
378     video_capture->setHidden(true);
379     video_frame->setHidden(false);
380     m_videoBox->setHidden(true);
381     switch (device_selector->currentIndex()) {
382     case FIREWIRE:
383         m_captureProcess->write("\e", 2);
384         m_playAction->setIcon(m_playIcon);
385         m_isPlaying = false;
386         break;
387     case SCREENGRAB:
388         m_captureProcess->write("q\n", 3);
389         m_captureProcess->terminate();
390         video_frame->setText(i18n("Encoding captured video..."));
391         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
392         break;
393     case VIDEO4LINUX:
394     case BLACKMAGIC:
395         if (m_captureDevice) {
396             m_captureDevice->stop();
397         }
398         m_isCapturing = false;
399         m_isPlaying = false;
400         m_playAction->setEnabled(true);
401         m_stopAction->setEnabled(false);
402         m_recAction->setEnabled(true);
403         slotSetInfoMessage(i18n("Capture stopped"));
404         m_isCapturing = false;
405         m_recAction->setChecked(false);
406         if (autoaddbox->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
407             emit addProjectClip(m_captureFile);
408             m_captureFile.clear();
409         }
410         break;
411     default:
412         break;
413     }
414 }
415
416 void RecMonitor::slotStartPreview(bool play)
417 {
418     if (m_captureProcess->state() != QProcess::NotRunning) {
419         if (device_selector->currentIndex() == FIREWIRE) {
420             if (m_isPlaying) {
421                 m_captureProcess->write("k", 1);
422                 //captureProcess->write("\e", 2);
423                 m_playAction->setIcon(m_playIcon);
424                 m_isPlaying = false;
425             } else {
426                 m_captureProcess->write("p", 1);
427                 m_playAction->setIcon(m_pauseIcon);
428                 m_isPlaying = true;
429             }
430         }
431         return;
432     }
433     m_captureArgs.clear();
434     m_displayArgs.clear();
435     m_isPlaying = false;
436     QString capturename = KdenliveSettings::dvgrabfilename();
437     QString path;
438     MltVideoProfile profile;
439     QString producer;
440     QStringList dvargs = KdenliveSettings::dvgrabextra().simplified().split(" ", QString::SkipEmptyParts);
441     //video_capture->setVisible(device_selector->currentIndex() == BLACKMAGIC);
442     //video_frame->setHidden(device_selector->currentIndex() == BLACKMAGIC);
443     int ix = device_selector->currentIndex();
444     m_videoBox->setHidden(ix != VIDEO4LINUX && ix != BLACKMAGIC);
445     switch (ix) {
446     case FIREWIRE:
447         switch (KdenliveSettings::firewireformat()) {
448         case 0:
449             // RAW DV CAPTURE
450             m_captureArgs << "--format" << "raw";
451             m_displayArgs << "-f" << "dv";
452             break;
453         case 1:
454             // DV type 1
455             m_captureArgs << "--format" << "dv1";
456             m_displayArgs << "-f" << "dv";
457             break;
458         case 2:
459             // DV type 2
460             m_captureArgs << "--format" << "dv2";
461             m_displayArgs << "-f" << "dv";
462             break;
463         case 3:
464             // HDV CAPTURE
465             m_captureArgs << "--format" << "hdv";
466             m_displayArgs << "-f" << "mpegts";
467             break;
468         }
469         if (KdenliveSettings::firewireautosplit()) m_captureArgs << "--autosplit";
470         if (KdenliveSettings::firewiretimestamp()) m_captureArgs << "--timestamp";
471         if (!dvargs.isEmpty()) {
472             m_captureArgs << dvargs;
473         }
474         m_captureArgs << "-i";
475         if (capturename.isEmpty()) capturename = "capture";
476         m_captureArgs << capturename << "-";
477
478         m_displayArgs << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
479
480         m_captureProcess->setStandardOutputProcess(m_displayProcess);
481         m_captureProcess->setWorkingDirectory(m_capturePath);
482         kDebug() << "Capture: Running dvgrab " << m_captureArgs.join(" ");
483
484         m_captureProcess->start(KdenliveSettings::dvgrab_path(), m_captureArgs);
485         if (play) m_captureProcess->write(" ", 1);
486         m_discAction->setEnabled(true);
487         break;
488     case VIDEO4LINUX:
489         path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
490         m_manager->activateMonitor("record");
491         if (m_captureDevice == NULL) {
492             m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
493             connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
494             m_captureDevice->sendFrameForAnalysis = m_analyse;
495             m_manager->updateScopeSource();
496         }
497         profile = ProfilesDialog::getVideoProfile(path);
498         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);
499         kDebug()<< "PROD: "<<producer;
500         if (!m_captureDevice->slotStartPreview(producer)) {
501             // v4l capture failed to start
502             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
503             m_videoBox->setHidden(true);
504             
505         } else {
506             m_videoBox->setHidden(false);
507             m_playAction->setEnabled(false);
508             m_stopAction->setEnabled(true);
509             m_isPlaying = true;
510         }
511         
512         break;
513     case BLACKMAGIC:
514         path = KdenliveSettings::current_profile();
515         m_manager->activateMonitor("record");
516         if (m_captureDevice == NULL) {
517             m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
518             m_captureDevice->sendFrameForAnalysis = m_analyse;
519             m_manager->updateScopeSource();
520         }
521         profile = ProfilesDialog::getVideoProfile(path);
522         producer = QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice());
523         if (!m_captureDevice->slotStartPreview(producer)) {
524             // v4l capture failed to start
525             video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
526             m_videoBox->setHidden(true);
527             
528         } else {
529             m_videoBox->setHidden(false);
530             m_playAction->setEnabled(false);
531             m_stopAction->setEnabled(true);
532             m_isPlaying = true;
533         }
534         break;
535     default:
536         break;
537     }
538
539     if (device_selector->currentIndex() == FIREWIRE) {
540         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
541         m_displayProcess->start("ffplay", m_displayArgs);
542         video_frame->setText(i18n("Initialising..."));
543     } else {
544         // do something when starting screen grab
545     }
546 }
547
548 void RecMonitor::slotRecord()
549 {
550     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == FIREWIRE) {
551         slotStartPreview();
552     }
553     if (m_isCapturing) {
554         // User stopped capture
555         slotStopCapture();
556         return;
557     } else if (device_selector->currentIndex() == FIREWIRE) {
558         m_isCapturing = true;
559         m_didCapture = true;
560         m_captureProcess->write("c\n", 3);
561 #if KDE_IS_VERSION(4,2,0)
562         m_spaceTimer.start();
563 #endif
564         return;
565     }
566     if (m_captureProcess->state() == QProcess::NotRunning) {
567         m_recAction->setChecked(true);
568         QString extension = "mpg";
569         if (device_selector->currentIndex() == SCREENGRAB) extension = "ogv"; //KdenliveSettings::screengrabextension();
570         else if (device_selector->currentIndex() == VIDEO4LINUX) extension = KdenliveSettings::v4l_extension();
571         else if (device_selector->currentIndex() == BLACKMAGIC) extension = KdenliveSettings::decklink_extension();
572         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
573         int i = 1;
574         while (QFile::exists(path)) {
575             QString num = QString::number(i).rightJustified(4, '0', false);
576             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
577             i++;
578         }
579         m_captureFile = KUrl(path);
580
581         m_captureArgs.clear();
582         m_displayArgs.clear();
583         QString args;
584         QString playlist;
585         MltVideoProfile profile;
586         QString capturename = KdenliveSettings::dvgrabfilename();
587         if (capturename.isEmpty()) capturename = "capture";
588
589         switch (device_selector->currentIndex()) {
590         case VIDEO4LINUX:
591             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
592             profile = ProfilesDialog::getVideoProfile(path);
593             if (m_captureDevice == NULL) {
594                 m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
595                 m_captureDevice->sendFrameForAnalysis = m_analyse;
596                 m_manager->updateScopeSource();
597             }
598             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);
599
600             // Add alsa audio capture
601             if (KdenliveSettings::v4l_captureaudio()) {
602                 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()));
603             }
604             
605
606             playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
607
608             playlist.append("<track producer=\"playlist0\"/>");            
609
610             // Audio mix
611             if (KdenliveSettings::v4l_captureaudio()) {
612                 playlist.append("<track producer=\"playlist1\"/>");
613                 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>");
614             }
615
616             playlist.append("</tractor></mlt>");
617
618             if (m_captureDevice->slotStartCapture(KdenliveSettings::v4l_parameters(), m_captureFile.path(), playlist, enable_preview->isChecked())) {
619                 m_videoBox->setHidden(false);
620                 m_isCapturing = true;
621                 m_recAction->setEnabled(false);
622                 m_stopAction->setEnabled(true);
623             }
624             else {
625                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));                
626                 m_videoBox->setHidden(true);
627                 m_isCapturing = false;
628             }
629
630             /*
631             m_captureArgs << KdenliveSettings::video4capture().simplified().split(' ') << KdenliveSettings::video4encoding().simplified().split(' ') << "-y" << m_captureFile.path() << "-f" << KdenliveSettings::video4container() << "-acodec" << KdenliveSettings::video4acodec() << "-vcodec" << KdenliveSettings::video4vcodec() << "-";
632             m_displayArgs << "-f" << KdenliveSettings::video4container() << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
633             m_captureProcess->setStandardOutputProcess(m_displayProcess);
634             kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
635             m_captureProcess->start("ffmpeg", m_captureArgs);*/
636             break;
637             
638         case BLACKMAGIC:
639             path = KdenliveSettings::current_profile();
640             profile = ProfilesDialog::getVideoProfile(path);
641             if (m_captureDevice == NULL) {
642                 m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
643                 connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
644                 m_captureDevice->sendFrameForAnalysis = m_analyse;
645                 m_manager->updateScopeSource();
646             }
647                
648             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());
649
650             if (m_captureDevice->slotStartCapture(KdenliveSettings::decklink_parameters(), m_captureFile.path(), QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice()), enable_preview->isChecked(), false)) {
651                 m_videoBox->setHidden(false);
652                 m_isCapturing = true;
653                 slotSetInfoMessage(i18n("Capturing to %1", m_captureFile.fileName()));
654                 m_recAction->setEnabled(false);
655                 m_stopAction->setEnabled(true);
656             }
657             else {
658                 video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
659                 slotSetInfoMessage(i18n("Failed to start capture"));
660                 m_videoBox->setHidden(true);
661                 m_isCapturing = false;
662             }
663             break;
664             
665         case SCREENGRAB:
666             switch (KdenliveSettings::rmd_capture_type()) {
667             case 0:
668                 // Full screen capture, nothing special to do
669                 break;
670             default:
671                 // Region capture
672                 m_captureArgs << "--width" << QString::number(KdenliveSettings::rmd_width()) << "--height" << QString::number(KdenliveSettings::rmd_height());
673                 if (!KdenliveSettings::rmd_follow_mouse()) {
674                     m_captureArgs << "-x" << QString::number(KdenliveSettings::rmd_offsetx()) << "-y" << QString::number(KdenliveSettings::rmd_offsety());
675                 } else {
676                     m_captureArgs << "--follow-mouse";
677                     if (KdenliveSettings::rmd_hide_frame()) m_captureArgs << "--no-frame";
678                 }
679                 break;
680             }
681             if (KdenliveSettings::rmd_hide_mouse()) m_captureArgs << "--no-cursor";
682             m_isCapturing = true;
683             if (KdenliveSettings::rmd_capture_audio()) {
684                 m_captureArgs << "--freq" << KdenliveSettings::rmd_freq();
685                 m_captureArgs << "--channels" << QString::number(KdenliveSettings::rmd_audio_channels());
686                 if (KdenliveSettings::rmd_use_jack()) {
687                     m_captureArgs << "--use-jack";
688                     QStringList ports = KdenliveSettings::rmd_jackports().split(" ", QString::SkipEmptyParts);
689                     for (int i = 0; i < ports.count(); ++i) {
690                         m_captureArgs << ports.at(i);
691                     }
692                     if (KdenliveSettings::rmd_jack_buffer() > 0.0)
693                         m_captureArgs << "--ring-buffer-size" << QString::number(KdenliveSettings::rmd_jack_buffer());
694                 } else {
695                     if (!KdenliveSettings::rmd_alsadevicename().isEmpty())
696                         m_captureArgs << "--device" << KdenliveSettings::rmd_alsadevicename();
697                     if (KdenliveSettings::rmd_alsa_buffer() > 0)
698                         m_captureArgs << "--buffer-size" << QString::number(KdenliveSettings::rmd_alsa_buffer());
699                 }
700             } else m_captureArgs << "--no-sound";
701
702             if (KdenliveSettings::rmd_fullshots()) m_captureArgs << "--full-shots";
703             m_captureArgs << "--v_bitrate" << QString::number(KdenliveSettings::rmd_bitrate());
704             m_captureArgs << "--v_quality" << QString::number(KdenliveSettings::rmd_quality());
705             m_captureArgs << "--workdir" << KdenliveSettings::currenttmpfolder();
706             m_captureArgs << "--fps" << QString::number(KdenliveSettings::rmd_fps()) << "-o" << m_captureFile.path();
707             m_captureProcess->start(KdenliveSettings::rmd_path(), m_captureArgs);
708             kDebug() << "// RecordMyDesktop params: " << m_captureArgs;
709             break;
710         default:
711             break;
712         }
713
714
715         if (device_selector->currentIndex() == FIREWIRE) {
716             m_isCapturing = true;
717             kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
718             m_displayProcess->start("ffplay", m_displayArgs);
719             video_frame->setText(i18n("Initialising..."));
720         }
721     } else {
722         // stop capture
723         m_displayProcess->kill();
724         //captureProcess->kill();
725         QTimer::singleShot(1000, this, SLOT(slotRecord()));
726     }
727 }
728
729 /*
730 void RecMonitor::slotStartGrab(const QRect &rect) {
731     rgnGrab->deleteLater();
732     QApplication::restoreOverrideCursor();
733     show();
734     if (rect.isNull()) return;
735     int width = rect.width();
736     int height = rect.height();
737     if (width % 2 != 0) width--;
738     if (height % 2 != 0) height--;
739     QString args = KdenliveSettings::screengrabcapture().replace("%size", QString::number(width) + "x" + QString::number(height)).replace("%offset", "+" + QString::number(rect.x()) + "," + QString::number(rect.y()));
740     if (KdenliveSettings::screengrabenableaudio()) {
741         // also capture audio
742         if (KdenliveSettings::useosscapture()) m_captureArgs << KdenliveSettings::screengrabosscapture().simplified().split(' ');
743         else m_captureArgs << KdenliveSettings::screengrabalsacapture2().simplified().split(' ');
744     }
745     m_captureArgs << args.simplified().split(' ') << KdenliveSettings::screengrabencoding().simplified().split(' ') << m_captureFile.path();
746     m_isCapturing = true;
747     video_frame->setText(i18n("Capturing..."));
748     if (KdenliveSettings::screengrabenableaudio() && !KdenliveSettings::useosscapture()) {
749         QStringList alsaArgs = KdenliveSettings::screengrabalsacapture().simplified().split(' ');
750         alsaProcess->setStandardOutputProcess(captureProcess);
751         kDebug() << "Capture: Running arecord " << alsaArgs.join(" ");
752         alsaProcess->start("arecord", alsaArgs);
753     }
754     kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
755     captureProcess->start("ffmpeg", m_captureArgs);
756 }*/
757
758 void RecMonitor::slotProcessStatus(QProcess::ProcessState status)
759 {
760     if (status == QProcess::NotRunning) {
761         m_displayProcess->kill();
762         if (m_isCapturing && device_selector->currentIndex() != FIREWIRE)
763             if (autoaddbox->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
764                 emit addProjectClip(m_captureFile);
765                 m_captureFile.clear();
766             }
767         if (device_selector->currentIndex() == FIREWIRE) {
768             m_discAction->setIcon(KIcon("network-connect"));
769             m_discAction->setText(i18n("Connect"));
770             m_playAction->setEnabled(false);
771             m_rewAction->setEnabled(false);
772             m_fwdAction->setEnabled(false);
773             m_recAction->setEnabled(false);
774         }
775         m_isPlaying = false;
776         m_playAction->setIcon(m_playIcon);
777         m_recAction->setChecked(false);
778         m_stopAction->setEnabled(false);
779         device_selector->setEnabled(true);
780         if (m_captureProcess && m_captureProcess->exitStatus() == QProcess::CrashExit) {
781             video_frame->setText(i18n("Capture crashed, please check your parameters"));
782         } else {
783             if (device_selector->currentIndex() != SCREENGRAB) {
784                 video_frame->setText(i18n("Not connected"));
785             } else {
786                 if (m_captureProcess->exitCode() != 0) {
787                     video_frame->setText(i18n("Capture crashed, please check your parameters\nRecordMyDesktop exit code: %1", QString::number(m_captureProcess->exitCode())));
788                 } else {
789                     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)));
790                 }
791             }
792         }
793         m_isCapturing = false;
794
795 #if KDE_IS_VERSION(4,2,0)
796         m_spaceTimer.stop();
797         // update free space info
798         slotUpdateFreeSpace();
799 #endif
800
801     } else {
802         if (device_selector->currentIndex() != SCREENGRAB) m_stopAction->setEnabled(true);
803         device_selector->setEnabled(false);
804     }
805 }
806
807 void RecMonitor::manageCapturedFiles()
808 {
809     QString extension;
810     switch (KdenliveSettings::firewireformat()) {
811     case 0:
812         extension = ".dv";
813         break;
814     case 1:
815     case 2:
816         extension = ".avi";
817         break;
818     case 3:
819         extension = ".m2t";
820         break;
821     }
822     QDir dir(m_capturePath);
823     QStringList filters;
824     QString capturename = KdenliveSettings::dvgrabfilename();
825     if (capturename.isEmpty()) capturename = "capture";
826     filters << capturename + "*" + extension;
827     const QStringList result = dir.entryList(filters, QDir::Files, QDir::Time);
828     KUrl::List capturedFiles;
829     foreach(const QString & name, result) {
830         KUrl url = KUrl(dir.filePath(name));
831         if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, this)) {
832             KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url, true);
833             if (file.time(KFileItem::ModificationTime) > m_captureTime) capturedFiles.append(url);
834         }
835     }
836     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
837     kDebug() << capturedFiles;
838
839     if (capturedFiles.count() > 0) {
840         ManageCapturesDialog *d = new ManageCapturesDialog(capturedFiles, this);
841         if (d->exec() == QDialog::Accepted) {
842             capturedFiles = d->importFiles();
843             foreach(const KUrl & url, capturedFiles) {
844                 emit addProjectClip(url);
845             }
846         }
847         delete d;
848     }
849 }
850
851 // virtual
852 void RecMonitor::mousePressEvent(QMouseEvent * /*event*/)
853 {
854 #if KDE_IS_VERSION(4,2,0)
855     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
856 #endif
857 }
858
859 void RecMonitor::slotUpdateFreeSpace()
860 {
861 #if KDE_IS_VERSION(4,2,0)
862     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
863     if (info.isValid()) {
864         m_freeSpace->setValue(100 * info.used() / info.size());
865         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
866         m_freeSpace->update();
867     }
868 #endif
869 }
870
871 void RecMonitor::refreshRecMonitor(bool visible)
872 {
873     if (visible) {
874         //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
875
876     }
877 }
878
879 void RecMonitor::slotPlay()
880 {
881
882     //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
883
884 }
885
886 void RecMonitor::slotReadDvgrabInfo()
887 {
888     QString data = m_captureProcess->readAllStandardError().simplified();
889     data = data.section('"', 2, 2).simplified();
890     m_dvinfo.setText(data.left(11));
891     m_dvinfo.updateGeometry();
892 }
893
894 AbstractRender *RecMonitor::abstractRender()
895 {
896     return m_captureDevice;
897 }
898
899
900 void RecMonitor::analyseFrames(bool analyse)
901 {
902     m_analyse = analyse;
903     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
904 }
905
906 void RecMonitor::slotDroppedFrames(int dropped)
907 {
908     slotSetInfoMessage(i18n("%1 dropped frames", dropped));
909 }
910
911 #include "recmonitor.moc"
912