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