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