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