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