]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Cleanup dvgrab group 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_manager(manager),
57     m_captureDevice(NULL),
58     m_analyse(false)
59 {
60     setupUi(this);
61
62     video_frame->setAttribute(Qt::WA_PaintOnScreen);
63     device_selector->setCurrentIndex(KdenliveSettings::defaultcapture());
64     connect(device_selector, SIGNAL(currentIndexChanged(int)), this, SLOT(slotVideoDeviceChanged(int)));
65
66     // Video widget holder
67     QVBoxLayout *l = new QVBoxLayout;
68     l->setContentsMargins(0, 0, 0, 0);
69     l->setSpacing(0);
70     m_videoBox = new VideoPreviewContainer();
71     m_videoBox->setContentsMargins(0, 0, 0, 0);
72     m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
73     l->addWidget(m_videoBox);
74     video_frame->setLayout(l);
75
76     QToolBar *toolbar = new QToolBar(this);
77     QHBoxLayout *layout = new QHBoxLayout;
78     layout->setContentsMargins(0, 0, 0, 0);
79     m_playIcon = KIcon("media-playback-start");
80     m_pauseIcon = KIcon("media-playback-pause");
81
82     m_discAction = toolbar->addAction(KIcon("network-connect"), i18n("Connect"));
83     connect(m_discAction, SIGNAL(triggered()), this, SLOT(slotDisconnect()));
84
85     m_rewAction = toolbar->addAction(KIcon("media-seek-backward"), i18n("Rewind"));
86     connect(m_rewAction, SIGNAL(triggered()), this, SLOT(slotRewind()));
87
88     m_playAction = toolbar->addAction(m_playIcon, i18n("Play"));
89     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotStartPreview()));
90
91     m_stopAction = toolbar->addAction(KIcon("media-playback-stop"), i18n("Stop"));
92     connect(m_stopAction, SIGNAL(triggered()), this, SLOT(slotStopCapture()));
93     m_stopAction->setEnabled(false);
94     m_fwdAction = toolbar->addAction(KIcon("media-seek-forward"), i18n("Forward"));
95     connect(m_fwdAction, SIGNAL(triggered()), this, SLOT(slotForward()));
96
97     m_recAction = toolbar->addAction(KIcon("media-record"), i18n("Record"));
98     connect(m_recAction, SIGNAL(triggered()), this, SLOT(slotRecord()));
99     m_recAction->setCheckable(true);
100
101     toolbar->addSeparator();
102
103     QAction *configAction = toolbar->addAction(KIcon("configure"), i18n("Configure"));
104     connect(configAction, SIGNAL(triggered()), this, SLOT(slotConfigure()));
105     configAction->setCheckable(false);
106
107     layout->addWidget(toolbar);
108     layout->addWidget(&m_logger);
109     layout->addWidget(&m_dvinfo);
110     m_logger.setMaxCount(10);
111     m_logger.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
112     m_logger.setFrame(false);
113     //m_logger.setInsertPolicy(QComboBox::InsertAtTop);
114
115 #if KDE_IS_VERSION(4,2,0)
116     m_freeSpace = new KCapacityBar(KCapacityBar::DrawTextInline, this);
117     m_freeSpace->setMaximumWidth(150);
118     QFontMetricsF fontMetrics(font());
119     m_freeSpace->setMaximumHeight(fontMetrics.height() * 1.2);
120     slotUpdateFreeSpace();
121     layout->addWidget(m_freeSpace);
122     connect(&m_spaceTimer, SIGNAL(timeout()), this, SLOT(slotUpdateFreeSpace()));
123     m_spaceTimer.setInterval(30000);
124     m_spaceTimer.setSingleShot(false);
125 #endif
126
127     control_frame_firewire->setLayout(layout);
128     m_displayProcess = new QProcess;
129     m_captureProcess = new QProcess;
130
131     connect(m_captureProcess, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(slotProcessStatus(QProcess::ProcessState)));
132     connect(m_captureProcess, SIGNAL(readyReadStandardError()), this, SLOT(slotReadDvgrabInfo()));
133
134     
135     QString videoDriver = KdenliveSettings::videodrivername();
136 #if QT_VERSION >= 0x040600
137     QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
138     env.insert("SDL_WINDOWID", QString::number(video_frame->winId()));
139     if (!videoDriver.isEmpty()) {
140         if (videoDriver == "x11_noaccel") {
141             env.insert("SDL_VIDEO_YUV_HWACCEL", "0");
142             env.insert("SDL_VIDEODRIVER", "x11");
143         } else env.insert("SDL_VIDEODRIVER", videoDriver);
144     }
145     m_displayProcess->setProcessEnvironment(env);
146 #else
147     QStringList env = QProcess::systemEnvironment();
148     env << "SDL_WINDOWID=" + QString::number(video_frame->winId());
149     if (!videoDriver.isEmpty()) {
150         if (videoDriver == "x11_noaccel") {
151             env << "SDL_VIDEO_YUV_HWACCEL=0";
152             env << "SDL_VIDEODRIVER=x11";
153         } else env << "SDL_VIDEODRIVER=" + videoDriver;
154     }
155     m_displayProcess->setEnvironment(env);
156 #endif
157     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
158
159     kDebug() << "/////// BUILDING MONITOR, ID: " << video_frame->winId();
160     slotVideoDeviceChanged(device_selector->currentIndex());
161     recording_preview->setToolTip(i18n("Capture preview settings"));
162     recording_preview->setCurrentIndex(KdenliveSettings::recording_preview());
163     connect(recording_preview, SIGNAL(currentIndexChanged(int)), this, SLOT(slotChangeRecordingPreview(int)));
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     recording_preview->setHidden(ix != VIDEO4LINUX && ix != BLACKMAGIC);
217     m_fwdAction->setVisible(ix == FIREWIRE);
218     m_discAction->setVisible(ix == FIREWIRE);
219     m_rewAction->setVisible(ix == FIREWIRE);
220     m_recAction->setEnabled(ix != FIREWIRE);
221     m_logger.setVisible(ix == BLACKMAGIC);
222     if (m_captureDevice) {
223         // MLT capture still running, abort
224         m_captureDevice->stop();
225         delete m_captureDevice;
226         m_captureDevice = NULL;
227         m_manager->clearScopeSource();
228     }
229
230     // The m_videoBox container has to be shown once before the MLT consumer is build, or preview will fail
231     m_videoBox->setHidden(ix != VIDEO4LINUX && ix != BLACKMAGIC);
232     m_videoBox->setHidden(true);
233     switch (ix) {
234     case SCREENGRAB:
235         m_discAction->setEnabled(false);
236         m_rewAction->setEnabled(false);
237         m_fwdAction->setEnabled(false);
238         m_stopAction->setEnabled(false);
239         m_playAction->setEnabled(false);
240         if (KdenliveSettings::rmd_path().isEmpty()) {
241             QString rmdpath = KStandardDirs::findExe("recordmydesktop");
242             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")));
243             else KdenliveSettings::setRmd_path(rmdpath);
244         }
245         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)));
246         //video_frame->setText(i18n("Press record button\nto start screen capture"));
247         break;
248     case VIDEO4LINUX:
249         m_stopAction->setEnabled(false);
250         m_playAction->setEnabled(true);
251         checkDeviceAvailability();
252         break;
253     case BLACKMAGIC:
254         m_stopAction->setEnabled(false);
255         m_playAction->setEnabled(true);
256         capturefile = m_capturePath;
257         if (!capturefile.endsWith("/")) capturefile.append("/");
258         capturename = KdenliveSettings::decklink_filename();
259         capturename.append("xxx.");
260         capturename.append(KdenliveSettings::decklink_extension());
261         capturefile.append(capturename);
262         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)));
263         break;
264     default: // FIREWIRE
265         m_discAction->setEnabled(true);
266         m_stopAction->setEnabled(false);
267         m_playAction->setEnabled(false);
268         m_rewAction->setEnabled(false);
269         m_fwdAction->setEnabled(false);
270
271         // Check that dvgab is available
272         if (KdenliveSettings::dvgrab_path().isEmpty()) {
273             QString dvgrabpath = KStandardDirs::findExe("dvgrab");
274             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")));
275             else KdenliveSettings::setDvgrab_path(dvgrabpath);
276         } else {
277             // Show capture info
278             capturefile = m_capturePath;
279             if (!capturefile.endsWith("/")) capturefile.append("/");
280             capturename = KdenliveSettings::dvgrabfilename();
281             if (capturename.isEmpty()) capturename = "capture";
282             QString extension;
283             switch (KdenliveSettings::firewireformat()) {
284             case 0:
285                 extension = ".dv";
286                 break;
287             case 1:
288             case 2:
289                 extension = ".avi";
290                 break;
291             case 3:
292                 extension = ".m2t";
293                 break;
294             }
295             capturename.append("xxx" + extension);
296             capturefile.append(capturename);
297             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)));
298         }
299         break;
300     }
301 }
302
303 void RecMonitor::slotSetInfoMessage(const QString &message)
304 {
305     m_logger.insertItem(0, message);
306 }
307
308 QPixmap RecMonitor::mergeSideBySide(const QPixmap& pix, const QString &txt)
309 {
310     QPainter p;
311     QRect r = QApplication::fontMetrics().boundingRect(QRect(0, 0, video_frame->width(), video_frame->height()), Qt::AlignLeft, txt);
312     int strWidth = r.width();
313     int strHeight = r.height();
314     int pixWidth = pix.width();
315     int pixHeight = pix.height();
316     QPixmap res(strWidth + 8 + pixWidth, qMax(strHeight, pixHeight));
317     res.fill(Qt::transparent);
318     p.begin(&res);
319     p.drawPixmap(0, 0, pix);
320     p.setPen(kapp->palette().text().color());
321     p.drawText(QRect(pixWidth + 8, 0, strWidth, strHeight), 0, txt);
322     p.end();
323     return res;
324 }
325
326
327 void RecMonitor::checkDeviceAvailability()
328 {
329     if (!KIO::NetAccess::exists(KUrl(KdenliveSettings::video4vdevice()), KIO::NetAccess::SourceSide , this)) {
330         m_playAction->setEnabled(false);
331         m_recAction->setEnabled(false);
332         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())));
333     } else {
334         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)));
335     }
336 }
337
338 void RecMonitor::slotDisconnect()
339 {
340     if (m_captureProcess->state() == QProcess::NotRunning) {
341         m_captureTime = KDateTime::currentLocalDateTime();
342         kDebug() << "CURRENT TIME: " << m_captureTime.toString();
343         m_didCapture = false;
344         slotStartPreview(false);
345         m_discAction->setIcon(KIcon("network-disconnect"));
346         m_discAction->setText(i18n("Disconnect"));
347         m_recAction->setEnabled(true);
348         m_stopAction->setEnabled(true);
349         m_playAction->setEnabled(true);
350         m_rewAction->setEnabled(true);
351         m_fwdAction->setEnabled(true);
352     } else {
353         m_captureProcess->write("q", 1);
354         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
355         if (m_didCapture) manageCapturedFiles();
356         m_didCapture = false;
357     }
358 }
359
360 void RecMonitor::slotRewind()
361 {
362     m_captureProcess->write("a", 1);
363 }
364
365 void RecMonitor::slotForward()
366 {
367     m_captureProcess->write("z", 1);
368 }
369
370 void RecMonitor::slotStopCapture()
371 {
372     // stop capture
373     if (!m_isCapturing && !m_isPlaying) return;
374     m_videoBox->setHidden(true);
375     switch (device_selector->currentIndex()) {
376     case FIREWIRE:
377         m_captureProcess->write("\e", 2);
378         m_playAction->setIcon(m_playIcon);
379         m_isPlaying = false;
380         break;
381     case SCREENGRAB:
382         m_captureProcess->write("q\n", 3);
383         m_captureProcess->terminate();
384         video_frame->setText(i18n("Encoding captured video..."));
385         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
386         break;
387     case VIDEO4LINUX:
388     case BLACKMAGIC:
389         if (m_captureDevice) {
390             m_captureDevice->stop();
391         }
392         recording_preview->setEnabled(true);
393         m_isCapturing = false;
394         m_isPlaying = false;
395         m_playAction->setEnabled(true);
396         m_stopAction->setEnabled(false);
397         m_recAction->setEnabled(true);
398         slotSetInfoMessage(i18n("Capture stopped"));
399         m_isCapturing = false;
400         m_recAction->setChecked(false);
401         if (autoaddbox->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
402             emit addProjectClip(m_captureFile);
403             m_captureFile.clear();
404         }
405         break;
406     default:
407         break;
408     }
409 }
410
411 void RecMonitor::slotStartPreview(bool play)
412 {
413     if (m_captureProcess->state() != QProcess::NotRunning) {
414         if (device_selector->currentIndex() == FIREWIRE) {
415             if (m_isPlaying) {
416                 m_captureProcess->write("k", 1);
417                 //captureProcess->write("\e", 2);
418                 m_playAction->setIcon(m_playIcon);
419                 m_isPlaying = false;
420             } else {
421                 m_captureProcess->write("p", 1);
422                 m_playAction->setIcon(m_pauseIcon);
423                 m_isPlaying = true;
424             }
425         }
426         return;
427     }
428     m_captureArgs.clear();
429     m_displayArgs.clear();
430     m_isPlaying = false;
431     QString capturename = KdenliveSettings::dvgrabfilename();
432     QString path;
433     MltVideoProfile profile;
434     QString producer;
435     QStringList dvargs = KdenliveSettings::dvgrabextra().simplified().split(" ", QString::SkipEmptyParts);
436     int ix = device_selector->currentIndex();
437     m_videoBox->setHidden(ix != VIDEO4LINUX && ix != BLACKMAGIC);
438     switch (ix) {
439     case FIREWIRE:
440         switch (KdenliveSettings::firewireformat()) {
441         case 0:
442             // RAW DV CAPTURE
443             m_captureArgs << "--format" << "raw";
444             m_displayArgs << "-f" << "dv";
445             break;
446         case 1:
447             // DV type 1
448             m_captureArgs << "--format" << "dv1";
449             m_displayArgs << "-f" << "dv";
450             break;
451         case 2:
452             // DV type 2
453             m_captureArgs << "--format" << "dv2";
454             m_displayArgs << "-f" << "dv";
455             break;
456         case 3:
457             // HDV CAPTURE
458             m_captureArgs << "--format" << "hdv";
459             m_displayArgs << "-f" << "mpegts";
460             break;
461         }
462         if (KdenliveSettings::firewireautosplit()) m_captureArgs << "--autosplit";
463         if (KdenliveSettings::firewiretimestamp()) m_captureArgs << "--timestamp";
464         if (!dvargs.isEmpty()) {
465             m_captureArgs << dvargs;
466         }
467         m_captureArgs << "-i";
468         if (capturename.isEmpty()) capturename = "capture";
469         m_captureArgs << capturename << "-";
470
471         m_displayArgs << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
472
473         m_captureProcess->setStandardOutputProcess(m_displayProcess);
474         m_captureProcess->setWorkingDirectory(m_capturePath);
475         kDebug() << "Capture: Running dvgrab " << m_captureArgs.join(" ");
476
477         m_captureProcess->start(KdenliveSettings::dvgrab_path(), m_captureArgs);
478         if (play) m_captureProcess->write(" ", 1);
479         m_discAction->setEnabled(true);
480         break;
481     case VIDEO4LINUX:
482         path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
483         m_manager->activateMonitor("record");
484         buildMltDevice(path);
485         profile = ProfilesDialog::getVideoProfile(path);
486         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);
487         if (!m_captureDevice->slotStartPreview(producer)) {
488             // v4l capture failed to start
489             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
490             m_videoBox->setHidden(true);
491             
492         } else {
493             m_playAction->setEnabled(false);
494             m_stopAction->setEnabled(true);
495             m_isPlaying = true;
496         }
497         
498         break;
499     case BLACKMAGIC:
500         path = KdenliveSettings::current_profile();
501         m_manager->activateMonitor("record");
502         buildMltDevice(path);
503         profile = ProfilesDialog::getVideoProfile(path);
504         producer = QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice());
505         if (!m_captureDevice->slotStartPreview(producer)) {
506             // v4l capture failed to start
507             video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
508             m_videoBox->setHidden(true);
509             
510         } else {
511             m_playAction->setEnabled(false);
512             m_stopAction->setEnabled(true);
513             m_isPlaying = true;
514         }
515         break;
516     default:
517         break;
518     }
519
520     if (device_selector->currentIndex() == FIREWIRE) {
521         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
522         m_displayProcess->start("ffplay", m_displayArgs);
523         video_frame->setText(i18n("Initialising..."));
524     } else {
525         // do something when starting screen grab
526     }
527 }
528
529 void RecMonitor::slotRecord()
530 {
531     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == FIREWIRE) {
532         slotStartPreview();
533     }
534     if (m_isCapturing) {
535         // User stopped capture
536         slotStopCapture();
537         return;
538     } else if (device_selector->currentIndex() == FIREWIRE) {
539         m_isCapturing = true;
540         m_didCapture = true;
541         m_captureProcess->write("c\n", 3);
542 #if KDE_IS_VERSION(4,2,0)
543         m_spaceTimer.start();
544 #endif
545         return;
546     }
547     if (m_captureProcess->state() == QProcess::NotRunning) {
548         m_logger.clear();
549         m_recAction->setChecked(true);
550         QString extension = "mpg";
551         if (device_selector->currentIndex() == SCREENGRAB) extension = "ogv"; //KdenliveSettings::screengrabextension();
552         else if (device_selector->currentIndex() == VIDEO4LINUX) extension = KdenliveSettings::v4l_extension();
553         else if (device_selector->currentIndex() == BLACKMAGIC) extension = KdenliveSettings::decklink_extension();
554         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
555         int i = 1;
556         while (QFile::exists(path)) {
557             QString num = QString::number(i).rightJustified(4, '0', false);
558             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
559             i++;
560         }
561         m_captureFile = KUrl(path);
562
563         m_captureArgs.clear();
564         m_displayArgs.clear();
565         QString args;
566         QString playlist;
567         QString v4lparameters;
568         MltVideoProfile profile;
569         QString capturename = KdenliveSettings::dvgrabfilename();
570         if (capturename.isEmpty()) capturename = "capture";
571
572         switch (device_selector->currentIndex()) {
573         case VIDEO4LINUX:
574             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
575             profile = ProfilesDialog::getVideoProfile(path);
576             m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
577             buildMltDevice(path);
578             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);
579
580             v4lparameters = KdenliveSettings::v4l_parameters();
581
582             // Add alsa audio capture
583             if (KdenliveSettings::v4l_captureaudio()) {
584                 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()));
585             }
586             else {
587                 // if we do not want audio, make sure that we don't have audio encoding parameters
588                 // this is required otherwise the MLT avformat consumer will not close properly
589                 if (v4lparameters.contains("acodec")) {
590                     QString endParam = v4lparameters.section("acodec", 1);
591                     int vcodec = endParam.indexOf(" vcodec");
592                     int format = endParam.indexOf(" f=");
593                     int cutPosition = -1;
594                     if (vcodec > -1) {
595                         if (format  > -1) {
596                             cutPosition = qMin(vcodec, format);
597                         }
598                         else cutPosition = vcodec;
599                     }
600                     else if (format  > -1) {
601                         cutPosition = format;
602                     }
603                     else {
604                         // nothing interesting in end params
605                         endParam.clear();
606                     }
607                     if (cutPosition > -1) {
608                         endParam.remove(0, cutPosition);
609                     }
610                     v4lparameters = QString(v4lparameters.section("acodec", 0, 0) + "an=1 " + endParam).simplified();
611                 }
612             }
613             
614
615             playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
616
617             playlist.append("<track producer=\"playlist0\"/>");            
618
619             // Audio mix
620             if (KdenliveSettings::v4l_captureaudio()) {
621                 playlist.append("<track producer=\"playlist1\"/>");
622                 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>");
623             }
624
625             playlist.append("</tractor></mlt>");
626
627             if (m_captureDevice->slotStartCapture(v4lparameters, m_captureFile.path(), playlist, recording_preview->currentIndex())) {
628                 m_videoBox->setHidden(false);
629                 m_isCapturing = true;
630                 m_recAction->setEnabled(false);
631                 m_stopAction->setEnabled(true);
632                 recording_preview->setEnabled(false);
633             }
634             else {
635                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));                
636                 m_videoBox->setHidden(true);
637                 m_isCapturing = false;
638             }
639             break;
640             
641         case BLACKMAGIC:
642             path = KdenliveSettings::current_profile();
643             profile = ProfilesDialog::getVideoProfile(path);
644             m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
645             buildMltDevice(path);
646                
647             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());
648
649             if (m_captureDevice->slotStartCapture(KdenliveSettings::decklink_parameters(), m_captureFile.path(), QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice()), recording_preview->currentIndex(), false)) {
650                 m_videoBox->setHidden(false);
651                 m_isCapturing = true;
652                 slotSetInfoMessage(i18n("Capturing to %1", m_captureFile.fileName()));
653                 m_recAction->setEnabled(false);
654                 m_stopAction->setEnabled(true);
655                 recording_preview->setEnabled(false);
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) {
834                 // The file was captured in the last batch
835                 if (url.fileName().contains(':')) {
836                     // Several dvgrab options (--timecode,...) use : in the file name, which is
837                     // not supported by MLT, so rename them
838                     QString newUrl = url.directory(KUrl::AppendTrailingSlash) + url.fileName().replace(':', '_');
839                     if (QFile::rename(url.path(), newUrl)) {
840                         url = KUrl(newUrl);
841                     }
842                     
843                 }
844                 capturedFiles.append(url);
845             }
846         }
847     }
848     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
849     kDebug() << capturedFiles;
850
851     if (capturedFiles.count() > 0) {
852         ManageCapturesDialog *d = new ManageCapturesDialog(capturedFiles, this);
853         if (d->exec() == QDialog::Accepted) {
854             emit addProjectClipList(d->importFiles());
855         }
856         delete d;
857     }
858 }
859
860 // virtual
861 void RecMonitor::mousePressEvent(QMouseEvent * /*event*/)
862 {
863 #if KDE_IS_VERSION(4,2,0)
864     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
865 #endif
866 }
867
868 void RecMonitor::slotUpdateFreeSpace()
869 {
870 #if KDE_IS_VERSION(4,2,0)
871     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
872     if (info.isValid() && info.size() > 0) {
873         m_freeSpace->setValue(100 * info.used() / info.size());
874         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
875         m_freeSpace->update();
876     }
877 #endif
878 }
879
880 void RecMonitor::refreshRecMonitor(bool visible)
881 {
882     if (visible) {
883         //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
884
885     }
886 }
887
888 void RecMonitor::slotPlay()
889 {
890
891     //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
892
893 }
894
895 void RecMonitor::slotReadDvgrabInfo()
896 {
897     QString data = m_captureProcess->readAllStandardError().simplified();
898     data = data.section('"', 2, 2).simplified();
899     m_dvinfo.setText(data.left(11));
900     m_dvinfo.updateGeometry();
901 }
902
903 AbstractRender *RecMonitor::abstractRender()
904 {
905     return m_captureDevice;
906 }
907
908
909 void RecMonitor::analyseFrames(bool analyse)
910 {
911     m_analyse = analyse;
912     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
913 }
914
915 void RecMonitor::slotDroppedFrames(int dropped)
916 {
917     slotSetInfoMessage(i18n("%1 dropped frames", dropped));
918 }
919
920 void RecMonitor::buildMltDevice(const QString &path)
921 {
922     if (m_captureDevice == NULL) {
923         m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
924         connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
925         m_captureDevice->sendFrameForAnalysis = m_analyse;
926         m_manager->updateScopeSource();
927     }
928 }
929
930 void RecMonitor::slotChangeRecordingPreview(int ix)
931 {
932     KdenliveSettings::setRecording_preview(ix);
933 }
934
935 #include "recmonitor.moc"
936