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