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