]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Integrate with the required MLT hooks for getting Movit to work.
[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 #include "widgets/videosurface.h"
30
31 #include <KDebug>
32 #include <KLocalizedString>
33 #include <KStandardDirs>
34 #include <KComboBox>
35 #include <KIO/NetAccess>
36 #include <KFileItem>
37 #include <KMessageBox>
38 #include <KApplication>
39 #include <KDiskFreeSpaceInfo>
40
41 #include <QMouseEvent>
42 #include <QMenu>
43 #include <QToolButton>
44 #include <QFile>
45 #include <QDir>
46 #include <QDesktopWidget>
47 #include <QPainter>
48
49
50 RecMonitor::RecMonitor(Kdenlive::MonitorId name, MonitorManager *manager, QWidget *parent) :
51     AbstractMonitor(name, manager, parent),
52     m_isCapturing(false),
53     m_didCapture(false),
54     m_isPlaying(false),
55     m_captureDevice(NULL),
56     m_analyse(false)
57 {
58     setupUi(this);
59
60     //video_frame->setAttribute(Qt::WA_PaintOnScreen);
61     device_selector->setCurrentIndex(KdenliveSettings::defaultcapture());
62     connect(device_selector, SIGNAL(currentIndexChanged(int)), this, SLOT(slotVideoDeviceChanged(int)));
63     // Video widget holder
64     QVBoxLayout *l = new QVBoxLayout;
65     l->setContentsMargins(0, 0, 0, 0);
66     l->setSpacing(0);
67     l->addWidget(videoBox, 10);
68     video_frame->setLayout(l);
69     createVideoSurface();
70
71     QToolBar *toolbar = new QToolBar(this);
72     QHBoxLayout *hlayout = new QHBoxLayout;
73     hlayout->setContentsMargins(0, 0, 0, 0);
74     m_playIcon = KIcon("media-playback-start");
75     m_pauseIcon = KIcon("media-playback-pause");
76
77     m_discAction = toolbar->addAction(KIcon("network-connect"), i18n("Connect"));
78     connect(m_discAction, SIGNAL(triggered()), this, SLOT(slotDisconnect()));
79
80     m_rewAction = toolbar->addAction(KIcon("media-seek-backward"), i18n("Rewind"));
81     connect(m_rewAction, SIGNAL(triggered()), this, SLOT(slotRewind()));
82
83     m_playAction = toolbar->addAction(m_playIcon, i18n("Play"));
84     connect(m_playAction, SIGNAL(triggered()), this, SLOT(slotStartPreview()));
85
86     m_stopAction = toolbar->addAction(KIcon("media-playback-stop"), i18n("Stop"));
87     connect(m_stopAction, SIGNAL(triggered()), this, SLOT(slotStopCapture()));
88     m_stopAction->setEnabled(false);
89     m_fwdAction = toolbar->addAction(KIcon("media-seek-forward"), i18n("Forward"));
90     connect(m_fwdAction, SIGNAL(triggered()), this, SLOT(slotForward()));
91
92     m_recAction = toolbar->addAction(KIcon("media-record"), i18n("Record"));
93     connect(m_recAction, SIGNAL(triggered()), this, SLOT(slotRecord()));
94     m_recAction->setCheckable(true);
95
96     rec_options->setIcon(KIcon("system-run"));
97     QMenu *menu = new QMenu(this);
98     m_addCapturedClip = new QAction(i18n("Add Captured File to Project"), this);
99     m_addCapturedClip->setCheckable(true);
100     m_addCapturedClip->setChecked(true);
101     menu->addAction(m_addCapturedClip);
102
103     rec_audio->setChecked(KdenliveSettings::v4l_captureaudio());
104     rec_video->setChecked(KdenliveSettings::v4l_capturevideo());
105
106     m_previewSettings = new QAction(i18n("Recording Preview"), this);
107     m_previewSettings->setCheckable(true);
108
109     rec_options->setMenu(menu);
110     menu->addAction(m_previewSettings);
111
112     toolbar->addSeparator();
113
114     QAction *configAction = toolbar->addAction(KIcon("configure"), i18n("Configure"));
115     connect(configAction, SIGNAL(triggered()), this, SLOT(slotConfigure()));
116     configAction->setCheckable(false);
117
118     hlayout->addWidget(toolbar);
119     hlayout->addWidget(&m_logger);
120     hlayout->addWidget(&m_dvinfo);
121     m_logger.setMaxCount(10);
122     m_logger.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
123     m_logger.setFrame(false);
124     //m_logger.setInsertPolicy(QComboBox::InsertAtTop);
125     
126     m_freeSpace = new KCapacityBar(KCapacityBar::DrawTextInline, this);
127     m_freeSpace->setMaximumWidth(150);
128     QFontMetricsF fontMetrics(font());
129     m_freeSpace->setMaximumHeight(fontMetrics.height() * 1.2);
130     slotUpdateFreeSpace();
131     hlayout->addWidget(m_freeSpace);
132     connect(&m_spaceTimer, SIGNAL(timeout()), this, SLOT(slotUpdateFreeSpace()));
133     m_spaceTimer.setInterval(30000);
134     m_spaceTimer.setSingleShot(false);
135
136     control_frame_firewire->setLayout(hlayout);
137     m_displayProcess = new QProcess;
138     m_captureProcess = new QProcess;
139
140     connect(m_captureProcess, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(slotProcessStatus(QProcess::ProcessState)));
141     connect(m_captureProcess, SIGNAL(readyReadStandardError()), this, SLOT(slotReadProcessInfo()));
142     
143     QString videoDriver = KdenliveSettings::videodrivername();
144 #if QT_VERSION >= 0x040600
145     QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
146     env.insert("SDL_WINDOWID", QString::number(videoSurface->winId()));
147     if (!videoDriver.isEmpty()) {
148         if (videoDriver == "x11_noaccel") {
149             env.insert("SDL_VIDEO_YUV_HWACCEL", "0");
150             env.insert("SDL_VIDEODRIVER", "x11");
151         } else env.insert("SDL_VIDEODRIVER", videoDriver);
152     }
153     m_displayProcess->setProcessEnvironment(env);
154 #else
155     QStringList env = QProcess::systemEnvironment();
156     env << "SDL_WINDOWID=" + QString::number(videoSurface->winId());
157     if (!videoDriver.isEmpty()) {
158         if (videoDriver == "x11_noaccel") {
159             env << "SDL_VIDEO_YUV_HWACCEL=0";
160             env << "SDL_VIDEODRIVER=x11";
161         } else env << "SDL_VIDEODRIVER=" + videoDriver;
162     }
163     m_displayProcess->setEnvironment(env);
164 #endif
165
166     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
167
168     kDebug() << "/////// BUILDING MONITOR, ID: " << videoSurface->winId();
169 #if KDE_IS_VERSION(4,7,0)
170     m_infoMessage = new KMessageWidget;
171     QVBoxLayout *s =  static_cast <QVBoxLayout *> (layout());
172     s->insertWidget(1, m_infoMessage);
173     m_infoMessage->hide();
174 #endif
175     
176     slotVideoDeviceChanged(device_selector->currentIndex());
177     m_previewSettings->setChecked(KdenliveSettings::enable_recording_preview());
178     connect(m_previewSettings, SIGNAL(triggered(bool)), this, SLOT(slotChangeRecordingPreview(bool)));
179 }
180
181 RecMonitor::~RecMonitor()
182 {
183     m_spaceTimer.stop();
184     delete m_captureProcess;
185     delete m_displayProcess;
186     delete m_captureDevice;
187 }
188
189 void RecMonitor::slotSwitchFullScreen()
190 {
191     videoBox->switchFullScreen();
192 }
193
194 void RecMonitor::stop()
195 {
196     // Special case: when recording audio only, do not stop so that we can do voiceover.
197     if (device_selector->currentIndex() == ScreenBag || (device_selector->currentIndex() == Video4Linux && !rec_video->isChecked())) return;
198     slotStopCapture();
199 }
200
201 void RecMonitor::start()
202 {
203     //slotStartPreview(true);
204 }
205
206 void RecMonitor::slotConfigure()
207 {
208     emit showConfigDialog(4, device_selector->currentIndex());
209 }
210
211 void RecMonitor::slotUpdateCaptureFolder(const QString &currentProjectFolder)
212 {
213     if (KdenliveSettings::capturetoprojectfolder()) m_capturePath = currentProjectFolder;
214     else m_capturePath = KdenliveSettings::capturefolder();
215     if (m_captureProcess) m_captureProcess->setWorkingDirectory(m_capturePath);
216     if (m_captureProcess->state() != QProcess::NotRunning) {
217         if (device_selector->currentIndex() == Firewire)
218             KMessageBox::information(this, i18n("You need to disconnect and reconnect in the capture monitor to apply your changes"), i18n("Capturing"));
219         else KMessageBox::information(this, i18n("You need to stop capture before your changes can be applied"), i18n("Capturing"));
220     } else slotVideoDeviceChanged(device_selector->currentIndex());
221
222     // update free space info
223     slotUpdateFreeSpace();
224 }
225
226 void RecMonitor::slotVideoDeviceChanged(int ix)
227 {
228     QString capturefile;
229     QString capturename;
230 #if KDE_IS_VERSION(4,7,0)
231     if (m_infoMessage->isVisible()) {
232 #if KDE_IS_VERSION(4,10,0)
233         m_infoMessage->animatedHide();
234 #else    
235         QTimer::singleShot(0, m_infoMessage, SLOT(animatedHide()));
236 #endif
237     }
238 #endif
239     m_previewSettings->setEnabled(ix == Video4Linux || ix == BlackMagic);
240     control_frame->setVisible(ix == Video4Linux);
241     m_playAction->setVisible(ix != ScreenBag);
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 ScreenBag:
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()) showWarningMessage(i18n("ffmpeg or avconv not found,\n please install it for screen grabs"));
272             else KdenliveSettings::setFfmpegpath(exepath);
273         }
274         if (!KdenliveSettings::ffmpegpath().isEmpty()) {
275             if (!Render::checkX11Grab()) {
276                 // FFmpeg does not support screen grab
277                 showWarningMessage(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                 showWarningMessage(i18n("dvgrab utility not found,\n please install it for firewire capture"));
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 ScreenBag:
423         m_captureProcess->terminate();
424         QTimer::singleShot(1500, m_captureProcess, SLOT(kill()));
425         break;
426     case Video4Linux:
427     case BlackMagic:
428         if (m_captureDevice) {
429             m_captureDevice->stop();
430         }
431         m_previewSettings->setEnabled(true);
432         m_isCapturing = false;
433         m_isPlaying = false;
434         m_playAction->setEnabled(true);
435         m_stopAction->setEnabled(false);
436         m_recAction->setEnabled(true);
437         slotSetInfoMessage(i18n("Capture stopped"));
438         m_isCapturing = false;
439         m_recAction->setChecked(false);
440         if (m_addCapturedClip->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
441             emit addProjectClip(m_captureFile);
442             m_captureFile.clear();
443         }
444         break;
445     default:
446         break;
447     }
448 }
449
450 void RecMonitor::slotStartPreview(bool play)
451 {
452     if (m_captureProcess->state() != QProcess::NotRunning) {
453         if (device_selector->currentIndex() == Firewire) {
454             videoBox->setHidden(false);
455             if (m_isPlaying) {
456                 m_captureProcess->write("k", 1);
457                 //captureProcess->write("\e", 2);
458                 m_playAction->setIcon(m_playIcon);
459                 m_isPlaying = false;
460             } else {
461                 m_captureProcess->write("p", 1);
462                 m_playAction->setIcon(m_pauseIcon);
463                 m_isPlaying = true;
464             }
465         }
466         return;
467     }
468     slotActivateMonitor();
469     if (m_isPlaying) return;
470     m_captureArgs.clear();
471     m_displayArgs.clear();
472     m_isPlaying = false;
473     QString capturename = KdenliveSettings::dvgrabfilename();
474     QString path;
475     MltVideoProfile profile;
476     QString producer;
477     QStringList dvargs = KdenliveSettings::dvgrabextra().simplified().split(' ', QString::SkipEmptyParts);
478     int ix = device_selector->currentIndex();
479     bool isXml;
480     videoBox->setHidden(ix != Video4Linux && ix != BlackMagic && ix != Firewire);
481     switch (ix) {
482     case Firewire:
483         switch (KdenliveSettings::firewireformat()) {
484         case 0:
485             // RAW DV CAPTURE
486             m_captureArgs << "--format" << "raw";
487             m_displayArgs << "-f" << "dv";
488             break;
489         case 1:
490             // DV type 1
491             m_captureArgs << "--format" << "dv1";
492             m_displayArgs << "-f" << "dv";
493             break;
494         case 2:
495             // DV type 2
496             m_captureArgs << "--format" << "dv2";
497             m_displayArgs << "-f" << "dv";
498             break;
499         case 3:
500             // HDV CAPTURE
501             m_captureArgs << "--format" << "hdv";
502             m_displayArgs << "-f" << "mpegts";
503             break;
504         }
505         if (KdenliveSettings::firewireautosplit()) m_captureArgs << "--autosplit";
506         if (KdenliveSettings::firewiretimestamp()) m_captureArgs << "--timestamp";
507         if (!dvargs.isEmpty()) {
508             m_captureArgs << dvargs;
509         }
510         m_captureArgs << "-i";
511         if (capturename.isEmpty()) capturename = "capture";
512         m_captureArgs << capturename << "-";
513
514         m_displayArgs << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-noframedrop" << "-";
515
516         m_captureProcess->setStandardOutputProcess(m_displayProcess);
517         m_captureProcess->setWorkingDirectory(m_capturePath);
518         kDebug() << "Capture: Running dvgrab " << m_captureArgs.join(" ");
519
520         m_captureProcess->start(KdenliveSettings::dvgrab_path(), m_captureArgs);
521         if (play) m_captureProcess->write(" ", 1);
522         m_discAction->setEnabled(true);
523         break;
524     case Video4Linux:
525         path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
526         buildMltDevice(path);
527         profile = ProfilesDialog::getVideoProfile(path);
528         producer = getV4lXmlPlaylist(profile, &isXml);
529
530         //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);
531         if (!m_captureDevice->slotStartPreview(producer, isXml)) {
532             // v4l capture failed to start
533             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
534             videoBox->setHidden(true);
535
536         } else {
537             m_playAction->setEnabled(false);
538             m_stopAction->setEnabled(true);
539             m_isPlaying = true;
540         }
541
542         break;
543     case BlackMagic:
544         path = KdenliveSettings::current_profile();
545         slotActivateMonitor();
546         buildMltDevice(path);
547         producer = QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice());
548         if (!m_captureDevice->slotStartPreview(producer)) {
549             // v4l capture failed to start
550             video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
551             videoBox->setHidden(true);
552
553         } else {
554             m_playAction->setEnabled(false);
555             m_stopAction->setEnabled(true);
556             m_isPlaying = true;
557         }
558         break;
559     default:
560         break;
561     }
562
563     control_frame->setEnabled(false);
564
565     if (device_selector->currentIndex() == Firewire) {
566         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
567         m_displayProcess->start(KdenliveSettings::ffplaypath(), m_displayArgs);
568         //video_frame->setText(i18n("Initialising..."));
569     } else {
570         // do something when starting screen grab
571     }
572 }
573
574 void RecMonitor::slotRecord()
575 {
576     m_error.clear();
577     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == Firewire) {
578         slotStartPreview();
579     }
580     if (m_isCapturing) {
581         // User stopped capture
582         slotStopCapture();
583         return;
584     } else if (device_selector->currentIndex() == Firewire) {
585         m_isCapturing = true;
586         m_didCapture = true;
587         m_captureProcess->write("c\n", 3);
588         m_spaceTimer.start();
589         return;
590     }
591     if (m_captureProcess->state() == QProcess::NotRunning) {
592         m_logger.clear();
593         m_recAction->setChecked(true);
594         QString extension = "mpg";
595         if (device_selector->currentIndex() == ScreenBag) {
596             extension = KdenliveSettings::grab_extension();
597         }
598         else if (device_selector->currentIndex() == Video4Linux) {
599             // TODO: when recording audio only, allow configuration?
600             if (!rec_video->isChecked()) extension = "wav";
601             else extension = KdenliveSettings::v4l_extension();
602         }
603         else if (device_selector->currentIndex() == BlackMagic) extension = KdenliveSettings::decklink_extension();
604         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
605         int i = 1;
606         while (QFile::exists(path)) {
607             QString num = QString::number(i).rightJustified(4, '0', false);
608             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
609             ++i;
610         }
611         m_captureFile = KUrl(path);
612
613         m_captureArgs.clear();
614         m_displayArgs.clear();
615         QString args;
616         QString playlist;
617         QString v4lparameters;
618         QStringList grabParameters;
619         MltVideoProfile profile;
620         bool showPreview;
621         bool isXml;
622         QString captureSize;
623         QRect screenSize = QApplication::desktop()->screenGeometry();
624         QString capturename = KdenliveSettings::dvgrabfilename();
625         if (capturename.isEmpty()) capturename = "capture";
626
627         switch (device_selector->currentIndex()) {
628         case Video4Linux:
629             if (rec_video->isChecked()) slotActivateMonitor();
630             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
631             profile = ProfilesDialog::getVideoProfile(path);
632             //m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
633             buildMltDevice(path);
634             playlist = getV4lXmlPlaylist(profile, &isXml);
635
636             v4lparameters = KdenliveSettings::v4l_parameters();
637
638             // TODO: when recording audio only, allow param configuration?
639             if (!rec_video->isChecked()) v4lparameters.clear();
640
641             // Add alsa audio capture
642             if (!rec_audio->isChecked()) {
643                 // if we do not want audio, make sure that we don't have audio encoding parameters
644                 // this is required otherwise the MLT avformat consumer will not close properly
645                 if (v4lparameters.contains("acodec")) {
646                     QString endParam = v4lparameters.section("acodec", 1);
647                     int vcodec = endParam.indexOf(" vcodec");
648                     int format = endParam.indexOf(" f=");
649                     int cutPosition = -1;
650                     if (vcodec > -1) {
651                         if (format  > -1) {
652                             cutPosition = qMin(vcodec, format);
653                         }
654                         else cutPosition = vcodec;
655                     }
656                     else if (format  > -1) {
657                         cutPosition = format;
658                     }
659                     else {
660                         // nothing interesting in end params
661                         endParam.clear();
662                     }
663                     if (cutPosition > -1) {
664                         endParam.remove(0, cutPosition);
665                     }
666                     v4lparameters = QString(v4lparameters.section("acodec", 0, 0) + "an=1 " + endParam).simplified();
667                 }
668             }
669
670             showPreview = m_previewSettings->isChecked();
671             if (!rec_video->isChecked()) showPreview = false;
672
673             if (m_captureDevice->slotStartCapture(v4lparameters, m_captureFile.path(), playlist, showPreview, isXml)) {
674                 videoBox->setHidden(false);
675                 m_isCapturing = true;
676                 m_recAction->setEnabled(false);
677                 m_stopAction->setEnabled(true);
678                 m_previewSettings->setEnabled(false);
679                 control_frame->setEnabled(false);
680             }
681             else {
682                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
683                 videoBox->setHidden(true);
684                 m_recAction->blockSignals(true);
685                 m_recAction->setChecked(false);
686                 m_recAction->blockSignals(false);
687                 m_isCapturing = false;
688             }
689             break;
690
691         case BlackMagic:
692             slotActivateMonitor();
693             path = KdenliveSettings::current_profile();
694             profile = ProfilesDialog::getVideoProfile(path);
695             //m_videoBox->setRatio((double) profile.display_aspect_num / profile.display_aspect_den);
696             buildMltDevice(path);
697
698             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());
699
700             if (m_captureDevice->slotStartCapture(KdenliveSettings::decklink_parameters(), m_captureFile.path(), QString("decklink:%1").arg(KdenliveSettings::decklink_capturedevice()), m_previewSettings->isChecked(), false)) {
701                 videoBox->setHidden(false);
702                 m_isCapturing = true;
703                 slotSetInfoMessage(i18n("Capturing to %1", m_captureFile.fileName()));
704                 m_recAction->setEnabled(false);
705                 m_stopAction->setEnabled(true);
706                 m_previewSettings->setEnabled(false);
707             }
708             else {
709                 video_frame->setText(i18n("Failed to start Decklink,\ncheck your parameters..."));
710                 slotSetInfoMessage(i18n("Failed to start capture"));
711                 videoBox->setHidden(true);
712                 m_isCapturing = false;
713             }
714             break;
715
716         case ScreenBag:
717             m_captureArgs << "-f" << "x11grab";
718             if (KdenliveSettings::grab_follow_mouse()) m_captureArgs << "-follow_mouse" << "centered";
719             if (!KdenliveSettings::grab_hide_frame()) m_captureArgs << "-show_region" << "1";
720             captureSize = ":0.0";
721             if (KdenliveSettings::grab_capture_type() == 0) {
722                 // Full screen capture
723                 m_captureArgs << "-s" << QString::number(screenSize.width()) + "x" + QString::number(screenSize.height());
724             } else {
725                 // Region capture
726                 m_captureArgs << "-s" << QString::number(KdenliveSettings::grab_width()) + "x" + QString::number(KdenliveSettings::grab_height());
727                 captureSize.append("+" + QString::number(KdenliveSettings::grab_offsetx()) + "." + QString::number(KdenliveSettings::grab_offsetx()));
728             }
729             // fps
730             m_captureArgs << "-r" << QString::number(KdenliveSettings::grab_fps());
731             if (KdenliveSettings::grab_hide_mouse()) captureSize.append("+nomouse");
732             m_captureArgs << "-i" << captureSize;
733             grabParameters = KdenliveSettings::grab_parameters().simplified().split(" ");
734             m_captureArgs << grabParameters;
735             m_captureArgs << path;
736             
737             m_isCapturing = true;
738             m_recAction->setEnabled(false);
739             /*if (KdenliveSettings::rmd_capture_audio()) {
740                 m_captureArgs << "--freq" << KdenliveSettings::rmd_freq();
741                 m_captureArgs << "--channels" << QString::number(KdenliveSettings::rmd_audio_channels());
742                 if (KdenliveSettings::rmd_use_jack()) {
743                     m_captureArgs << "--use-jack";
744                     QStringList ports = KdenliveSettings::rmd_jackports().split(' ', QString::SkipEmptyParts);
745                     for (int i = 0; i < ports.count(); ++i) {
746                         m_captureArgs << ports.at(i);
747                     }
748                     if (KdenliveSettings::rmd_jack_buffer() > 0.0)
749                         m_captureArgs << "--ring-buffer-size" << QString::number(KdenliveSettings::rmd_jack_buffer());
750                 } else {
751                     if (!KdenliveSettings::rmd_alsadevicename().isEmpty())
752                         m_captureArgs << "--device" << KdenliveSettings::rmd_alsadevicename();
753                     if (KdenliveSettings::rmd_alsa_buffer() > 0)
754                         m_captureArgs << "--buffer-size" << QString::number(KdenliveSettings::rmd_alsa_buffer());
755                 }
756             } else m_captureArgs << "--no-sound";*/
757
758             m_captureProcess->start(KdenliveSettings::ffmpegpath(), m_captureArgs);
759             if (!m_captureProcess->waitForStarted()) {
760                 // Problem launching capture app
761                 showWarningMessage(i18n("Failed to start the capture application:\n%1", KdenliveSettings::ffmpegpath()));
762             }
763             //kDebug() << "// Screen grab params: " << m_captureArgs;
764             break;
765         default:
766             break;
767         }
768
769
770         if (device_selector->currentIndex() == Firewire) {
771             m_isCapturing = true;
772             kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
773             m_displayProcess->start(KdenliveSettings::ffplaypath(), m_displayArgs);
774             video_frame->setText(i18n("Initialising..."));
775         }
776     } else {
777         // stop capture
778         m_displayProcess->kill();
779         //captureProcess->kill();
780         QTimer::singleShot(1000, this, SLOT(slotRecord()));
781     }
782 }
783
784
785 void RecMonitor::showWarningMessage(const QString &text, bool logAction)
786 {
787 #if KDE_IS_VERSION(4,7,0)
788     m_infoMessage->setText(text);
789     m_infoMessage->setMessageType(KMessageWidget::Warning);
790     if (logAction) {
791         QAction *manualAction = new QAction(i18n("Show log"), this);
792         connect(manualAction, SIGNAL(triggered()), this, SLOT(slotShowLog()));
793         m_infoMessage->addAction(manualAction);
794     }
795 #if KDE_IS_VERSION(4,10,0)
796     if (isVisible())
797        m_infoMessage->animatedShow();
798 #else
799     QTimer::singleShot(0, m_infoMessage, SLOT(animatedShow()));
800 #endif
801 #else
802     if (!logAction) {
803         video_frame->setPixmap(mergeSideBySide(KIcon("dialog-warning").pixmap(QSize(50, 50)), text));
804         
805     }
806     else {
807         video_frame->setText(QString("<qt>" + text + "<br><a href=\"http://kde.org\">" + i18n("Show log") + "</a>"));
808         connect(video_frame, SIGNAL(linkActivated(QString)), this, SLOT(slotShowLog()));
809     }
810 #endif
811 }
812
813 const QString RecMonitor::getV4lXmlPlaylist(const MltVideoProfile &profile, bool *isXml)
814 {
815     QString playlist;
816     if (rec_video->isChecked() && rec_audio->isChecked()) {
817         // We want to capture audio and video, use xml playlist
818         *isXml = true;
819         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);
820
821         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));
822     
823         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()));
824
825         playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"999999\">");
826         playlist.append("<track producer=\"playlist0\"/><track producer=\"playlist1\"/>");
827         playlist.append("</tractor></mlt>");
828     }
829     else if (rec_audio->isChecked()) {
830         // Audio only recording
831         *isXml = false;
832         playlist =QString("alsa:%1?channels=%2").arg(KdenliveSettings::v4l_alsadevicename()).arg(KdenliveSettings::alsachannels());
833     }
834     else {
835         // Video only recording
836         *isXml = false;
837         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);
838         
839     }
840     
841     return playlist;
842 }
843
844 /*
845 void RecMonitor::slotStartGrab(const QRect &rect) {
846     rgnGrab->deleteLater();
847     QApplication::restoreOverrideCursor();
848     show();
849     if (rect.isNull()) return;
850     int width = rect.width();
851     int height = rect.height();
852     if (width % 2 != 0) width--;
853     if (height % 2 != 0) height--;
854     QString args = KdenliveSettings::screengrabcapture().replace("%size", QString::number(width) + "x" + QString::number(height)).replace("%offset", "+" + QString::number(rect.x()) + "," + QString::number(rect.y()));
855     if (KdenliveSettings::screengrabenableaudio()) {
856         // also capture audio
857         if (KdenliveSettings::useosscapture()) m_captureArgs << KdenliveSettings::screengrabosscapture().simplified().split(' ');
858         else m_captureArgs << KdenliveSettings::screengrabalsacapture2().simplified().split(' ');
859     }
860     m_captureArgs << args.simplified().split(' ') << KdenliveSettings::screengrabencoding().simplified().split(' ') << m_captureFile.path();
861     m_isCapturing = true;
862     video_frame->setText(i18n("Capturing..."));
863     if (KdenliveSettings::screengrabenableaudio() && !KdenliveSettings::useosscapture()) {
864         QStringList alsaArgs = KdenliveSettings::screengrabalsacapture().simplified().split(' ');
865         alsaProcess->setStandardOutputProcess(captureProcess);
866         kDebug() << "Capture: Running arecord " << alsaArgs.join(" ");
867         alsaProcess->start("arecord", alsaArgs);
868     }
869     kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
870     captureProcess->start(KdenliveSettings::ffmpegpath(), m_captureArgs);
871 }*/
872
873 void RecMonitor::slotProcessStatus(QProcess::ProcessState status)
874 {
875     if (status == QProcess::NotRunning) {
876         m_displayProcess->kill();
877         if (m_isCapturing && device_selector->currentIndex() != Firewire)
878             if (m_addCapturedClip->isChecked() && !m_captureFile.isEmpty() && QFile::exists(m_captureFile.path())) {
879                 emit addProjectClip(m_captureFile);
880                 m_captureFile.clear();
881             }
882         if (device_selector->currentIndex() == Firewire) {
883             m_discAction->setIcon(KIcon("network-connect"));
884             m_discAction->setText(i18n("Connect"));
885             m_playAction->setEnabled(false);
886             m_rewAction->setEnabled(false);
887             m_fwdAction->setEnabled(false);
888             m_recAction->setEnabled(false);
889         }
890         else {
891             m_recAction->setEnabled(true);
892         }
893         m_isPlaying = false;
894         m_playAction->setIcon(m_playIcon);
895         m_recAction->setChecked(false);
896         m_stopAction->setEnabled(false);
897         device_selector->setEnabled(true);
898         if (m_captureProcess && m_captureProcess->exitStatus() == QProcess::CrashExit) {
899             showWarningMessage(i18n("Capture crashed, please check your parameters"), true);
900         } else {
901             if (device_selector->currentIndex() != ScreenBag) {
902                 video_frame->setText(i18n("Not connected"));
903             } else {
904                 int code = m_captureProcess->exitCode();
905                 if (code != 0 && code != 255) {
906                     showWarningMessage(i18n("Capture crashed, please check your parameters"), true);
907                 } else {
908                     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)));
909                 }
910             }
911         }
912         m_isCapturing = false;
913
914         m_spaceTimer.stop();
915         // update free space info
916         slotUpdateFreeSpace();
917     } else {
918         if (device_selector->currentIndex()) m_stopAction->setEnabled(true);
919         device_selector->setEnabled(false);
920     }
921 }
922
923 void RecMonitor::manageCapturedFiles()
924 {
925     QString extension;
926     switch (KdenliveSettings::firewireformat()) {
927     case 0:
928         extension = ".dv";
929         break;
930     case 1:
931     case 2:
932         extension = ".avi";
933         break;
934     case 3:
935         extension = ".m2t";
936         break;
937     }
938     QDir dir(m_capturePath);
939     QStringList filters;
940     QString capturename = KdenliveSettings::dvgrabfilename();
941     if (capturename.isEmpty()) capturename = "capture";
942     filters << capturename + '*' + extension;
943     const QStringList result = dir.entryList(filters, QDir::Files, QDir::Time);
944     KUrl::List capturedFiles;
945     foreach(const QString & name, result) {
946         KUrl url = KUrl(dir.filePath(name));
947         if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, this)) {
948             KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url, true);
949             if (file.time(KFileItem::ModificationTime) > m_captureTime) {
950                 // The file was captured in the last batch
951                 if (url.fileName().contains(':')) {
952                     // Several dvgrab options (--timecode,...) use : in the file name, which is
953                     // not supported by MLT, so rename them
954                     QString newUrl = url.directory(KUrl::AppendTrailingSlash) + url.fileName().replace(':', '_');
955                     if (QFile::rename(url.path(), newUrl)) {
956                         url = KUrl(newUrl);
957                     }
958
959                 }
960                 capturedFiles.append(url);
961             }
962         }
963     }
964     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
965     kDebug() << capturedFiles;
966
967     if (!capturedFiles.isEmpty()) {
968         QPointer<ManageCapturesDialog> d = new ManageCapturesDialog(capturedFiles, this);
969         if (d->exec() == QDialog::Accepted) {
970             emit addProjectClipList(d->importFiles());
971         }
972         delete d;
973     }
974 }
975
976 // virtual
977 void RecMonitor::mousePressEvent(QMouseEvent *event)
978 {
979     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
980     else QWidget::mousePressEvent(event);//m_videoBox->mousePressEvent(event);
981 }
982
983 void RecMonitor::slotUpdateFreeSpace()
984 {
985     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
986     if (info.isValid() && info.size() > 0) {
987         m_freeSpace->setValue(100 * info.used() / info.size());
988         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
989         m_freeSpace->update();
990     }
991 }
992
993 void RecMonitor::refreshRecMonitor(bool visible)
994 {
995     if (visible) {
996         //if (!m_isActive) activateMonitor();
997
998     }
999 }
1000
1001 void RecMonitor::slotPlay()
1002 {
1003     /*if (m_isPlaying) slotStopCapture();
1004     else slotStartPreview(true);*/
1005 }
1006
1007 void RecMonitor::slotReadProcessInfo()
1008 {
1009     QString data = m_captureProcess->readAllStandardError().simplified();
1010     if (device_selector->currentIndex() == ScreenBag) {
1011         m_error.append(data + "\n");
1012     }
1013     else if (device_selector->currentIndex() == Firewire) {
1014         data = data.section('"', 2, 2).simplified();
1015         m_dvinfo.setText(data.left(11));
1016         m_dvinfo.updateGeometry();
1017     }
1018 }
1019
1020 void RecMonitor::slotShowLog()
1021 {
1022     KMessageBox::information(this, m_error);
1023 }
1024
1025 AbstractRender *RecMonitor::abstractRender()
1026 {
1027     return m_captureDevice;
1028 }
1029
1030
1031 void RecMonitor::analyseFrames(bool analyse)
1032 {
1033     m_analyse = analyse;
1034     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
1035 }
1036
1037 void RecMonitor::slotDroppedFrames(int dropped)
1038 {
1039     slotSetInfoMessage(i18n("%1 dropped frames", dropped));
1040 }
1041
1042 void RecMonitor::buildMltDevice(const QString &path)
1043 {
1044     if (m_captureDevice == NULL) {
1045         m_monitorManager->updateScopeSource();
1046         m_captureDevice = new MltDeviceCapture(path, videoSurface, this);
1047         connect(m_captureDevice, SIGNAL(droppedFrames(int)), this, SLOT(slotDroppedFrames(int)));
1048         m_captureDevice->sendFrameForAnalysis = m_analyse;
1049         m_monitorManager->updateScopeSource();
1050     }
1051 }
1052
1053 void RecMonitor::slotChangeRecordingPreview(bool enable)
1054 {
1055     KdenliveSettings::setEnable_recording_preview(enable);
1056 }
1057
1058
1059 void RecMonitor::slotMouseSeek(int /*eventDelta*/, bool /*fast*/)
1060 {
1061 }
1062
1063
1064 #include "recmonitor.moc"
1065