]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Merge branch 'master' into buildsystem
[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 = 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);
477         if (!m_captureDevice->slotStartPreview(producer)) {
478             // v4l capture failed to start
479             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
480             m_videoBox->setHidden(true);
481             
482         } else {
483             m_playAction->setEnabled(false);
484             m_stopAction->setEnabled(true);
485             m_isPlaying = true;
486         }
487         
488         break;
489     case BLACKMAGIC:
490         path = KdenliveSettings::current_profile();
491         m_manager->activateMonitor("record");
492         buildMltDevice(path);
493         profile = ProfilesDialog::getVideoProfile(path);
494         producer = QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice());
495         if (!m_captureDevice->slotStartPreview(producer)) {
496             // v4l capture failed to start
497             video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
498             m_videoBox->setHidden(true);
499             
500         } else {
501             m_playAction->setEnabled(false);
502             m_stopAction->setEnabled(true);
503             m_isPlaying = true;
504         }
505         break;
506     default:
507         break;
508     }
509
510     if (device_selector->currentIndex() == FIREWIRE) {
511         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
512         m_displayProcess->start("ffplay", m_displayArgs);
513         video_frame->setText(i18n("Initialising..."));
514     } else {
515         // do something when starting screen grab
516     }
517 }
518
519 void RecMonitor::slotRecord()
520 {
521     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == FIREWIRE) {
522         slotStartPreview();
523     }
524     if (m_isCapturing) {
525         // User stopped capture
526         slotStopCapture();
527         return;
528     } else if (device_selector->currentIndex() == FIREWIRE) {
529         m_isCapturing = true;
530         m_didCapture = true;
531         m_captureProcess->write("c\n", 3);
532         m_spaceTimer.start();
533         return;
534     }
535     if (m_captureProcess->state() == QProcess::NotRunning) {
536         m_logger.clear();
537         m_recAction->setChecked(true);
538         QString extension = "mpg";
539         if (device_selector->currentIndex() == SCREENGRAB) extension = "ogv"; //KdenliveSettings::screengrabextension();
540         else if (device_selector->currentIndex() == VIDEO4LINUX) extension = KdenliveSettings::v4l_extension();
541         else if (device_selector->currentIndex() == BLACKMAGIC) extension = KdenliveSettings::decklink_extension();
542         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
543         int i = 1;
544         while (QFile::exists(path)) {
545             QString num = QString::number(i).rightJustified(4, '0', false);
546             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
547             i++;
548         }
549         m_captureFile = KUrl(path);
550
551         m_captureArgs.clear();
552         m_displayArgs.clear();
553         QString args;
554         QString playlist;
555         QString v4lparameters;
556         MltVideoProfile profile;
557         QString capturename = KdenliveSettings::dvgrabfilename();
558         if (capturename.isEmpty()) capturename = "capture";
559
560         switch (device_selector->currentIndex()) {
561         case VIDEO4LINUX:
562             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
563             profile = ProfilesDialog::getVideoProfile(path);
564             m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
565             buildMltDevice(path);
566             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);
567
568             v4lparameters = KdenliveSettings::v4l_parameters();
569
570             // Add alsa audio capture
571             if (KdenliveSettings::v4l_captureaudio()) {
572                 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()));
573             }
574             else {
575                 // if we do not want audio, make sure that we don't have audio encoding parameters
576                 // this is required otherwise the MLT avformat consumer will not close properly
577                 if (v4lparameters.contains("acodec")) {
578                     QString endParam = v4lparameters.section("acodec", 1);
579                     int vcodec = endParam.indexOf(" vcodec");
580                     int format = endParam.indexOf(" f=");
581                     int cutPosition = -1;
582                     if (vcodec > -1) {
583                         if (format  > -1) {
584                             cutPosition = qMin(vcodec, format);
585                         }
586                         else cutPosition = vcodec;
587                     }
588                     else if (format  > -1) {
589                         cutPosition = format;
590                     }
591                     else {
592                         // nothing interesting in end params
593                         endParam.clear();
594                     }
595                     if (cutPosition > -1) {
596                         endParam.remove(0, cutPosition);
597                     }
598                     v4lparameters = QString(v4lparameters.section("acodec", 0, 0) + "an=1 " + endParam).simplified();
599                 }
600             }
601             
602
603             playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
604
605             playlist.append("<track producer=\"playlist0\"/>");            
606
607             // Audio mix
608             if (KdenliveSettings::v4l_captureaudio()) {
609                 playlist.append("<track producer=\"playlist1\"/>");
610                 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>");
611             }
612
613             playlist.append("</tractor></mlt>");
614
615             if (m_captureDevice->slotStartCapture(v4lparameters, m_captureFile.path(), playlist, recording_preview->currentIndex())) {
616                 m_videoBox->setHidden(false);
617                 m_isCapturing = true;
618                 m_recAction->setEnabled(false);
619                 m_stopAction->setEnabled(true);
620                 recording_preview->setEnabled(false);
621             }
622             else {
623                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));                
624                 m_videoBox->setHidden(true);
625                 m_isCapturing = false;
626             }
627             break;
628             
629         case BLACKMAGIC:
630             path = KdenliveSettings::current_profile();
631             profile = ProfilesDialog::getVideoProfile(path);
632             m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
633             buildMltDevice(path);
634                
635             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());
636
637             if (m_captureDevice->slotStartCapture(KdenliveSettings::decklink_parameters(), m_captureFile.path(), QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice()), recording_preview->currentIndex(), false)) {
638                 m_videoBox->setHidden(false);
639                 m_isCapturing = true;
640                 slotSetInfoMessage(i18n("Capturing to %1", m_captureFile.fileName()));
641                 m_recAction->setEnabled(false);
642                 m_stopAction->setEnabled(true);
643                 recording_preview->setEnabled(false);
644             }
645             else {
646                 video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
647                 slotSetInfoMessage(i18n("Failed to start capture"));
648                 m_videoBox->setHidden(true);
649                 m_isCapturing = false;
650             }
651             break;
652             
653         case SCREENGRAB:
654             switch (KdenliveSettings::rmd_capture_type()) {
655             case 0:
656                 // Full screen capture, nothing special to do
657                 break;
658             default:
659                 // Region capture
660                 m_captureArgs << "--width" << QString::number(KdenliveSettings::rmd_width()) << "--height" << QString::number(KdenliveSettings::rmd_height());
661                 if (!KdenliveSettings::rmd_follow_mouse()) {
662                     m_captureArgs << "-x" << QString::number(KdenliveSettings::rmd_offsetx()) << "-y" << QString::number(KdenliveSettings::rmd_offsety());
663                 } else {
664                     m_captureArgs << "--follow-mouse";
665                     if (KdenliveSettings::rmd_hide_frame()) m_captureArgs << "--no-frame";
666                 }
667                 break;
668             }
669             if (KdenliveSettings::rmd_hide_mouse()) m_captureArgs << "--no-cursor";
670             m_isCapturing = true;
671             if (KdenliveSettings::rmd_capture_audio()) {
672                 m_captureArgs << "--freq" << KdenliveSettings::rmd_freq();
673                 m_captureArgs << "--channels" << QString::number(KdenliveSettings::rmd_audio_channels());
674                 if (KdenliveSettings::rmd_use_jack()) {
675                     m_captureArgs << "--use-jack";
676                     QStringList ports = KdenliveSettings::rmd_jackports().split(" ", QString::SkipEmptyParts);
677                     for (int i = 0; i < ports.count(); ++i) {
678                         m_captureArgs << ports.at(i);
679                     }
680                     if (KdenliveSettings::rmd_jack_buffer() > 0.0)
681                         m_captureArgs << "--ring-buffer-size" << QString::number(KdenliveSettings::rmd_jack_buffer());
682                 } else {
683                     if (!KdenliveSettings::rmd_alsadevicename().isEmpty())
684                         m_captureArgs << "--device" << KdenliveSettings::rmd_alsadevicename();
685                     if (KdenliveSettings::rmd_alsa_buffer() > 0)
686                         m_captureArgs << "--buffer-size" << QString::number(KdenliveSettings::rmd_alsa_buffer());
687                 }
688             } else m_captureArgs << "--no-sound";
689
690             if (KdenliveSettings::rmd_fullshots()) m_captureArgs << "--full-shots";
691             m_captureArgs << "--v_bitrate" << QString::number(KdenliveSettings::rmd_bitrate());
692             m_captureArgs << "--v_quality" << QString::number(KdenliveSettings::rmd_quality());
693             m_captureArgs << "--workdir" << KdenliveSettings::currenttmpfolder();
694             m_captureArgs << "--fps" << QString::number(KdenliveSettings::rmd_fps()) << "-o" << m_captureFile.path();
695             m_captureProcess->start(KdenliveSettings::rmd_path(), m_captureArgs);
696             kDebug() << "// RecordMyDesktop params: " << m_captureArgs;
697             break;
698         default:
699             break;
700         }
701
702
703         if (device_selector->currentIndex() == FIREWIRE) {
704             m_isCapturing = true;
705             kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
706             m_displayProcess->start("ffplay", m_displayArgs);
707             video_frame->setText(i18n("Initialising..."));
708         }
709     } else {
710         // stop capture
711         m_displayProcess->kill();
712         //captureProcess->kill();
713         QTimer::singleShot(1000, this, SLOT(slotRecord()));
714     }
715 }
716
717 /*
718 void RecMonitor::slotStartGrab(const QRect &rect) {
719     rgnGrab->deleteLater();
720     QApplication::restoreOverrideCursor();
721     show();
722     if (rect.isNull()) return;
723     int width = rect.width();
724     int height = rect.height();
725     if (width % 2 != 0) width--;
726     if (height % 2 != 0) height--;
727     QString args = KdenliveSettings::screengrabcapture().replace("%size", QString::number(width) + "x" + QString::number(height)).replace("%offset", "+" + QString::number(rect.x()) + "," + QString::number(rect.y()));
728     if (KdenliveSettings::screengrabenableaudio()) {
729         // also capture audio
730         if (KdenliveSettings::useosscapture()) m_captureArgs << KdenliveSettings::screengrabosscapture().simplified().split(' ');
731         else m_captureArgs << KdenliveSettings::screengrabalsacapture2().simplified().split(' ');
732     }
733     m_captureArgs << args.simplified().split(' ') << KdenliveSettings::screengrabencoding().simplified().split(' ') << m_captureFile.path();
734     m_isCapturing = true;
735     video_frame->setText(i18n("Capturing..."));
736     if (KdenliveSettings::screengrabenableaudio() && !KdenliveSettings::useosscapture()) {
737         QStringList alsaArgs = KdenliveSettings::screengrabalsacapture().simplified().split(' ');
738         alsaProcess->setStandardOutputProcess(captureProcess);
739         kDebug() << "Capture: Running arecord " << alsaArgs.join(" ");
740         alsaProcess->start("arecord", alsaArgs);
741     }
742     kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
743     captureProcess->start("ffmpeg", m_captureArgs);
744 }*/
745
746 void RecMonitor::slotProcessStatus(QProcess::ProcessState status)
747 {
748     if (status == QProcess::NotRunning) {
749         m_displayProcess->kill();
750         if (m_isCapturing && device_selector->currentIndex() != FIREWIRE)
751             if (autoaddbox->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
752                 emit addProjectClip(m_captureFile);
753                 m_captureFile.clear();
754             }
755         if (device_selector->currentIndex() == FIREWIRE) {
756             m_discAction->setIcon(KIcon("network-connect"));
757             m_discAction->setText(i18n("Connect"));
758             m_playAction->setEnabled(false);
759             m_rewAction->setEnabled(false);
760             m_fwdAction->setEnabled(false);
761             m_recAction->setEnabled(false);
762         }
763         m_isPlaying = false;
764         m_playAction->setIcon(m_playIcon);
765         m_recAction->setChecked(false);
766         m_stopAction->setEnabled(false);
767         device_selector->setEnabled(true);
768         if (m_captureProcess && m_captureProcess->exitStatus() == QProcess::CrashExit) {
769             video_frame->setText(i18n("Capture crashed, please check your parameters"));
770         } else {
771             if (device_selector->currentIndex() != SCREENGRAB) {
772                 video_frame->setText(i18n("Not connected"));
773             } else {
774                 if (m_captureProcess->exitCode() != 0) {
775                     video_frame->setText(i18n("Capture crashed, please check your parameters\nRecordMyDesktop exit code: %1", QString::number(m_captureProcess->exitCode())));
776                 } else {
777                     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)));
778                 }
779             }
780         }
781         m_isCapturing = false;
782
783         m_spaceTimer.stop();
784         // update free space info
785         slotUpdateFreeSpace();
786     } else {
787         if (device_selector->currentIndex() != SCREENGRAB) m_stopAction->setEnabled(true);
788         device_selector->setEnabled(false);
789     }
790 }
791
792 void RecMonitor::manageCapturedFiles()
793 {
794     QString extension;
795     switch (KdenliveSettings::firewireformat()) {
796     case 0:
797         extension = ".dv";
798         break;
799     case 1:
800     case 2:
801         extension = ".avi";
802         break;
803     case 3:
804         extension = ".m2t";
805         break;
806     }
807     QDir dir(m_capturePath);
808     QStringList filters;
809     QString capturename = KdenliveSettings::dvgrabfilename();
810     if (capturename.isEmpty()) capturename = "capture";
811     filters << capturename + "*" + extension;
812     const QStringList result = dir.entryList(filters, QDir::Files, QDir::Time);
813     KUrl::List capturedFiles;
814     foreach(const QString & name, result) {
815         KUrl url = KUrl(dir.filePath(name));
816         if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, this)) {
817             KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url, true);
818             if (file.time(KFileItem::ModificationTime) > m_captureTime) {
819                 // The file was captured in the last batch
820                 if (url.fileName().contains(':')) {
821                     // Several dvgrab options (--timecode,...) use : in the file name, which is
822                     // not supported by MLT, so rename them
823                     QString newUrl = url.directory(KUrl::AppendTrailingSlash) + url.fileName().replace(':', '_');
824                     if (QFile::rename(url.path(), newUrl)) {
825                         url = KUrl(newUrl);
826                     }
827                     
828                 }
829                 capturedFiles.append(url);
830             }
831         }
832     }
833     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
834     kDebug() << capturedFiles;
835
836     if (capturedFiles.count() > 0) {
837         ManageCapturesDialog *d = new ManageCapturesDialog(capturedFiles, this);
838         if (d->exec() == QDialog::Accepted) {
839             emit addProjectClipList(d->importFiles());
840         }
841         delete d;
842     }
843 }
844
845 // virtual
846 void RecMonitor::mousePressEvent(QMouseEvent * /*event*/)
847 {
848     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
849 }
850
851 void RecMonitor::slotUpdateFreeSpace()
852 {
853     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
854     if (info.isValid() && info.size() > 0) {
855         m_freeSpace->setValue(100 * info.used() / info.size());
856         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
857         m_freeSpace->update();
858     }
859 }
860
861 void RecMonitor::refreshRecMonitor(bool visible)
862 {
863     if (visible) {
864         //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
865
866     }
867 }
868
869 void RecMonitor::slotPlay()
870 {
871
872     //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
873
874 }
875
876 void RecMonitor::slotReadDvgrabInfo()
877 {
878     QString data = m_captureProcess->readAllStandardError().simplified();
879     data = data.section('"', 2, 2).simplified();
880     m_dvinfo.setText(data.left(11));
881     m_dvinfo.updateGeometry();
882 }
883
884 AbstractRender *RecMonitor::abstractRender()
885 {
886     return m_captureDevice;
887 }
888
889
890 void RecMonitor::analyseFrames(bool analyse)
891 {
892     m_analyse = analyse;
893     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
894 }
895
896 void RecMonitor::slotDroppedFrames(int dropped)
897 {
898     slotSetInfoMessage(i18n("%1 dropped frames", dropped));
899 }
900
901 void RecMonitor::buildMltDevice(const QString &path)
902 {
903     if (m_captureDevice == NULL) {
904         m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
905         connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
906         m_captureDevice->sendFrameForAnalysis = m_analyse;
907         m_manager->updateScopeSource();
908     }
909 }
910
911 void RecMonitor::slotChangeRecordingPreview(int ix)
912 {
913     KdenliveSettings::setRecording_preview(ix);
914 }
915
916 #include "recmonitor.moc"
917