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