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