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