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