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