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