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