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