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