]> git.sesse.net Git - kdenlive/blob - src/recmonitor.cpp
Complete rewrite of the video4linux capture to use MLT, in progress.
[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     m_recAction->setCheckable(true);
102
103     toolbar->addSeparator();
104
105     QAction *configAction = toolbar->addAction(KIcon("configure"), i18n("Configure"));
106     connect(configAction, SIGNAL(triggered()), this, SLOT(slotConfigure()));
107     configAction->setCheckable(false);
108
109     layout->addWidget(toolbar);
110     layout->addWidget(&m_logger);
111     layout->addWidget(&m_dvinfo);
112     m_logger.setMaxCount(10);
113     m_logger.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
114     m_logger.setFrame(false);
115     //m_logger.setInsertPolicy(QComboBox::InsertAtTop);
116
117 #if KDE_IS_VERSION(4,2,0)
118     m_freeSpace = new KCapacityBar(KCapacityBar::DrawTextInline, this);
119     m_freeSpace->setMaximumWidth(150);
120     QFontMetricsF fontMetrics(font());
121     m_freeSpace->setMaximumHeight(fontMetrics.height() * 1.2);
122     slotUpdateFreeSpace();
123     layout->addWidget(m_freeSpace);
124     connect(&m_spaceTimer, SIGNAL(timeout()), this, SLOT(slotUpdateFreeSpace()));
125     m_spaceTimer.setInterval(30000);
126     m_spaceTimer.setSingleShot(false);
127 #endif
128
129     control_frame_firewire->setLayout(layout);
130
131     slotVideoDeviceChanged(device_selector->currentIndex());
132     m_displayProcess = new QProcess;
133     m_captureProcess = new QProcess;
134
135     connect(m_captureProcess, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(slotProcessStatus(QProcess::ProcessState)));
136     connect(m_captureProcess, SIGNAL(readyReadStandardError()), this, SLOT(slotReadDvgrabInfo()));
137
138     QStringList env = QProcess::systemEnvironment();
139     env << "SDL_WINDOWID=" + QString::number(video_frame->winId());
140
141     QString videoDriver = KdenliveSettings::videodrivername();
142     if (!videoDriver.isEmpty()) {
143         if (videoDriver == "x11_noaccel") {
144             env << "SDL_VIDEO_YUV_HWACCEL=0";
145             env << "SDL_VIDEODRIVER=x11";
146         } else env << "SDL_VIDEODRIVER=" + videoDriver;
147     }
148     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
149
150     m_displayProcess->setEnvironment(env);
151
152     kDebug() << "/////// BUILDING MONITOR, ID: " << video_frame->winId();
153 }
154
155 RecMonitor::~RecMonitor()
156 {
157 #if KDE_IS_VERSION(4,2,0)
158     m_spaceTimer.stop();
159 #endif
160     delete m_captureProcess;
161     delete m_displayProcess;
162     if (m_captureDevice) delete m_captureDevice;
163 }
164
165 const QString RecMonitor::name() const
166 {
167     return m_name;
168 }
169
170 void RecMonitor::stop()
171 {
172     slotStopCapture();
173 }
174
175 void RecMonitor::start()
176 {
177 }
178
179 void RecMonitor::slotConfigure()
180 {
181     emit showConfigDialog(4, device_selector->currentIndex());
182 }
183
184 void RecMonitor::slotUpdateCaptureFolder(const QString currentProjectFolder)
185 {
186     if (KdenliveSettings::capturetoprojectfolder()) m_capturePath = currentProjectFolder;
187     else m_capturePath = KdenliveSettings::capturefolder();
188     if (m_captureProcess) m_captureProcess->setWorkingDirectory(m_capturePath);
189     if (m_captureProcess->state() != QProcess::NotRunning) {
190         if (device_selector->currentIndex() == FIREWIRE)
191             KMessageBox::information(this, i18n("You need to disconnect and reconnect in the capture monitor to apply your changes"), i18n("Capturing"));
192         else KMessageBox::information(this, i18n("You need to stop capture before your changes can be applied"), i18n("Capturing"));
193     } else slotVideoDeviceChanged(device_selector->currentIndex());
194
195 #if KDE_IS_VERSION(4,2,0)
196     // update free space info
197     slotUpdateFreeSpace();
198 #endif
199 }
200
201 void RecMonitor::slotVideoDeviceChanged(int ix)
202 {
203     QString capturefile;
204     QString capturename;
205     video_capture->setHidden(true);
206     video_frame->setHidden(false);
207     m_fwdAction->setVisible(ix == FIREWIRE);
208     m_discAction->setVisible(ix == FIREWIRE);
209     m_rewAction->setVisible(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     }
217     switch (ix) {
218     case SCREENGRAB:
219         m_discAction->setEnabled(false);
220         m_rewAction->setEnabled(false);
221         m_fwdAction->setEnabled(false);
222         m_recAction->setEnabled(true);
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_discAction->setEnabled(false);
235         m_rewAction->setEnabled(false);
236         m_fwdAction->setEnabled(false);
237         m_recAction->setEnabled(true);
238         m_stopAction->setEnabled(false);
239         m_playAction->setEnabled(true);
240         checkDeviceAvailability();
241         break;
242     case BLACKMAGIC:
243         createBlackmagicDevice();
244         m_recAction->setEnabled(false);
245         m_stopAction->setEnabled(false);
246         m_playAction->setEnabled(true);
247
248         capturefile = m_capturePath;
249         if (!capturefile.endsWith("/")) capturefile.append("/");
250         capturename = KdenliveSettings::hdmifilename();
251         capturename.append("xxx.raw");
252         capturefile.append(capturename);
253         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)));
254         break;
255     default: // FIREWIRE
256         m_discAction->setEnabled(true);
257         m_recAction->setEnabled(false);
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::createBlackmagicDevice()
296 {
297     //video_capture->setVisible(true);
298     if (m_bmCapture == NULL) {
299         QVBoxLayout *lay = new QVBoxLayout;
300         m_bmCapture = new BmdCaptureHandler(lay);
301         connect(m_bmCapture, SIGNAL(gotTimeCode(ulong)), this, SLOT(slotGotBlackMagicFrameNumber(ulong)));
302         connect(m_bmCapture, SIGNAL(gotMessage(const QString &)), this, SLOT(slotGotBlackmagicMessage(const QString &)));
303         video_capture->setLayout(lay);
304     }
305 }
306
307 void RecMonitor::slotGotBlackmagicFrameNumber(ulong ix)
308 {
309     m_dvinfo.setText(QString::number(ix));
310 }
311
312 void RecMonitor::slotGotBlackmagicMessage(const QString &message)
313 {
314     m_logger.insertItem(0, message);
315 }
316
317 QPixmap RecMonitor::mergeSideBySide(const QPixmap& pix, const QString txt)
318 {
319     QPainter p;
320     QRect r = QApplication::fontMetrics().boundingRect(QRect(0, 0, video_frame->width(), video_frame->height()), Qt::AlignLeft, txt);
321     int strWidth = r.width();
322     int strHeight = r.height();
323     int pixWidth = pix.width();
324     int pixHeight = pix.height();
325     QPixmap res(strWidth + 8 + pixWidth, qMax(strHeight, pixHeight));
326     res.fill(Qt::transparent);
327     p.begin(&res);
328     p.drawPixmap(0, 0, pix);
329     p.setPen(kapp->palette().text().color());
330     p.drawText(QRect(pixWidth + 8, 0, strWidth, strHeight), 0, txt);
331     p.end();
332     return res;
333 }
334
335
336 void RecMonitor::checkDeviceAvailability()
337 {
338     if (!KIO::NetAccess::exists(KUrl(KdenliveSettings::video4vdevice()), KIO::NetAccess::SourceSide , this)) {
339         m_playAction->setEnabled(false);
340         m_recAction->setEnabled(false);
341         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())));
342         //video_frame->setText(i18n("Cannot read from device %1\nPlease check drivers and access rights.", KdenliveSettings::video4vdevice()));
343     } else //video_frame->setText(i18n("Press play or record button\nto start video capture"));
344         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)));
345 }
346
347 void RecMonitor::slotDisconnect()
348 {
349     if (m_captureProcess->state() == QProcess::NotRunning) {
350         m_captureTime = KDateTime::currentLocalDateTime();
351         kDebug() << "CURRENT TIME: " << m_captureTime.toString();
352         m_didCapture = false;
353         slotStartCapture(false);
354         m_discAction->setIcon(KIcon("network-disconnect"));
355         m_discAction->setText(i18n("Disconnect"));
356         m_recAction->setEnabled(true);
357         m_stopAction->setEnabled(true);
358         m_playAction->setEnabled(true);
359         m_rewAction->setEnabled(true);
360         m_fwdAction->setEnabled(true);
361     } else {
362         m_captureProcess->write("q", 1);
363         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
364         if (m_didCapture) manageCapturedFiles();
365         m_didCapture = false;
366     }
367 }
368
369 void RecMonitor::slotRewind()
370 {
371     m_captureProcess->write("a", 1);
372 }
373
374 void RecMonitor::slotForward()
375 {
376     m_captureProcess->write("z", 1);
377 }
378
379 void RecMonitor::slotStopCapture()
380 {
381     // stop capture
382     video_capture->setHidden(true);
383     video_frame->setHidden(false);
384     switch (device_selector->currentIndex()) {
385     case FIREWIRE:
386         m_captureProcess->write("\e", 2);
387         m_playAction->setIcon(m_playIcon);
388         m_isPlaying = false;
389         break;
390     case VIDEO4LINUX:
391         if (m_captureDevice) {
392             m_captureDevice->stop();
393         }
394         m_playAction->setEnabled(true);
395         m_stopAction->setEnabled(false);
396         break;
397     case SCREENGRAB:
398         m_captureProcess->write("q\n", 3);
399         QTimer::singleShot(1000, m_captureProcess, SLOT(kill()));
400         break;
401     case BLACKMAGIC:
402         m_bmCapture->stopPreview();
403         m_playAction->setEnabled(true);
404         m_stopAction->setEnabled(false);
405         m_recAction->setEnabled(false);
406         break;
407     default:
408         break;
409     }
410 }
411
412 void RecMonitor::slotStartCapture(bool play)
413 {
414     if (m_captureProcess->state() != QProcess::NotRunning) {
415         if (device_selector->currentIndex() == FIREWIRE) {
416             if (m_isPlaying) {
417                 m_captureProcess->write("k", 1);
418                 //captureProcess->write("\e", 2);
419                 m_playAction->setIcon(m_playIcon);
420                 m_isPlaying = false;
421             } else {
422                 m_captureProcess->write("p", 1);
423                 m_playAction->setIcon(m_pauseIcon);
424                 m_isPlaying = true;
425             }
426         }
427         return;
428     }
429     m_captureArgs.clear();
430     m_displayArgs.clear();
431     m_isPlaying = false;
432     QString capturename = KdenliveSettings::dvgrabfilename();
433     QString path;
434     MltVideoProfile profile;
435     QString producer;
436     QStringList dvargs = KdenliveSettings::dvgrabextra().simplified().split(" ", QString::SkipEmptyParts);
437     video_capture->setVisible(device_selector->currentIndex() == BLACKMAGIC);
438     video_frame->setHidden(device_selector->currentIndex() == BLACKMAGIC);
439
440     switch (device_selector->currentIndex()) {
441     case FIREWIRE:
442         switch (KdenliveSettings::firewireformat()) {
443         case 0:
444             // RAW DV CAPTURE
445             m_captureArgs << "--format" << "raw";
446             m_displayArgs << "-f" << "dv";
447             break;
448         case 1:
449             // DV type 1
450             m_captureArgs << "--format" << "dv1";
451             m_displayArgs << "-f" << "dv";
452             break;
453         case 2:
454             // DV type 2
455             m_captureArgs << "--format" << "dv2";
456             m_displayArgs << "-f" << "dv";
457             break;
458         case 3:
459             // HDV CAPTURE
460             m_captureArgs << "--format" << "hdv";
461             m_displayArgs << "-f" << "mpegts";
462             break;
463         }
464         if (KdenliveSettings::firewireautosplit()) m_captureArgs << "--autosplit";
465         if (KdenliveSettings::firewiretimestamp()) m_captureArgs << "--timestamp";
466         if (!dvargs.isEmpty()) {
467             m_captureArgs << dvargs;
468         }
469         m_captureArgs << "-i";
470         if (capturename.isEmpty()) capturename = "capture";
471         m_captureArgs << capturename << "-";
472
473         m_displayArgs << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
474
475         m_captureProcess->setStandardOutputProcess(m_displayProcess);
476         m_captureProcess->setWorkingDirectory(m_capturePath);
477         kDebug() << "Capture: Running dvgrab " << m_captureArgs.join(" ");
478
479         m_captureProcess->start(KdenliveSettings::dvgrab_path(), m_captureArgs);
480         if (play) m_captureProcess->write(" ", 1);
481         m_discAction->setEnabled(true);
482         break;
483     case VIDEO4LINUX:
484         path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
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("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);
493         kDebug()<< "PROD: "<<producer;
494         if (!m_captureDevice->slotStartPreview(producer)) {
495             // v4l capture failed to start
496             video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));
497             m_videoBox->setHidden(true);
498             
499         } else {
500             m_videoBox->setHidden(false);
501             m_playAction->setEnabled(false);
502             m_stopAction->setEnabled(true);
503         }
504         
505         /*m_captureArgs << KdenliveSettings::video4capture().simplified().split(' ') << KdenliveSettings::video4encoding().simplified().split(' ') << "-f" << KdenliveSettings::video4container() << "-";
506         m_displayArgs << "-f" << KdenliveSettings::video4container() << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
507         m_captureProcess->setStandardOutputProcess(m_displayProcess);
508         kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
509         m_captureProcess->start("ffmpeg", m_captureArgs);*/
510         break;
511     case BLACKMAGIC:
512         m_bmCapture->startPreview(KdenliveSettings::hdmi_capturedevice(), KdenliveSettings::hdmi_capturemode());
513         m_playAction->setEnabled(false);
514         m_stopAction->setEnabled(true);
515         m_recAction->setEnabled(true);
516         break;
517     default:
518         break;
519     }
520
521     if (device_selector->currentIndex() == FIREWIRE) {
522         kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
523         m_displayProcess->start("ffplay", m_displayArgs);
524         video_frame->setText(i18n("Initialising..."));
525     } else {
526         // do something when starting screen grab
527     }
528 }
529
530 void RecMonitor::slotRecord()
531 {
532     if (device_selector->currentIndex() == BLACKMAGIC) {
533         if (m_blackmagicCapturing) {
534             // We are capturing, stop it
535             m_bmCapture->stopCapture();
536             m_blackmagicCapturing = false;
537         } else {
538             // Start capture, get capture filename first
539             QString path = m_capturePath;
540             if (!path.endsWith("/")) path.append("/");
541             path.append(KdenliveSettings::hdmifilename());
542             m_bmCapture->startCapture(path);
543             m_blackmagicCapturing = true;
544         }
545         return;
546     }
547
548     if (m_captureProcess->state() == QProcess::NotRunning && device_selector->currentIndex() == FIREWIRE) {
549         slotStartCapture();
550     }
551     if (m_isCapturing) {
552         switch (device_selector->currentIndex()) {
553         case FIREWIRE:
554             m_captureProcess->write("\e", 2);
555             m_playAction->setIcon(m_playIcon);
556             m_isCapturing = false;
557             m_isPlaying = false;
558             m_recAction->setChecked(false);
559             break;
560         case VIDEO4LINUX:
561             slotStopCapture();
562             m_isCapturing = false;
563             m_recAction->setChecked(false);
564             if (autoaddbox->isChecked() && QFile::exists(m_captureFile.path())) emit addProjectClip(m_captureFile);
565             //QTimer::singleShot(1000, this, SLOT(slotStartCapture()));
566             break;
567         case SCREENGRAB:
568             //captureProcess->write("q\n", 3);
569             m_captureProcess->terminate();
570             video_frame->setText(i18n("Encoding captured video..."));
571             // in case ffmpeg doesn't exit with the 'q' command, kill it one second later
572             //QTimer::singleShot(1000, captureProcess, SLOT(kill()));
573             break;
574         }
575         return;
576     } else if (device_selector->currentIndex() == FIREWIRE) {
577         m_isCapturing = true;
578         m_didCapture = true;
579         m_captureProcess->write("c\n", 3);
580 #if KDE_IS_VERSION(4,2,0)
581         m_spaceTimer.start();
582 #endif
583         return;
584     }
585     if (m_captureProcess->state() == QProcess::NotRunning) {
586         m_recAction->setChecked(true);
587         QString extension = "mp4";
588         if (device_selector->currentIndex() == SCREENGRAB) extension = "ogv"; //KdenliveSettings::screengrabextension();
589         else if (device_selector->currentIndex() == VIDEO4LINUX) extension = KdenliveSettings::v4l_extension();
590         QString path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture0000." + extension;
591         int i = 1;
592         while (QFile::exists(path)) {
593             QString num = QString::number(i).rightJustified(4, '0', false);
594             path = KUrl(m_capturePath).path(KUrl::AddTrailingSlash) + "capture" + num + '.' + extension;
595             i++;
596         }
597         m_captureFile = KUrl(path);
598
599         m_captureArgs.clear();
600         m_displayArgs.clear();
601         QString args;
602         QString playlist;
603         MltVideoProfile profile;
604         QString capturename = KdenliveSettings::dvgrabfilename();
605         if (capturename.isEmpty()) capturename = "capture";
606
607         switch (device_selector->currentIndex()) {
608         case VIDEO4LINUX:
609             path = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
610             profile = ProfilesDialog::getVideoProfile(path);
611             if (m_captureDevice == NULL) {
612                 m_captureDevice = new MltDeviceCapture(path, m_videoBox, this);
613                 m_captureDevice->sendFrameForAnalysis = m_analyse;
614                 m_manager->updateScopeSource();
615             }
616             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);
617
618             // Add alsa audio capture
619             if (KdenliveSettings::v4l_captureaudio()) {
620                 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()));
621             }
622             
623
624             playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
625
626             playlist.append("<track producer=\"playlist0\"/>");            
627
628             // Audio mix
629             if (KdenliveSettings::v4l_captureaudio()) {
630                 playlist.append("<track producer=\"playlist1\"/>");
631                 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>");
632             }
633
634             playlist.append("</tractor></mlt>");
635
636             if (m_captureDevice->slotStartCapture(KdenliveSettings::v4l_parameters(), m_captureFile.path(), playlist)) {
637                 m_videoBox->setHidden(false);
638                 m_isCapturing = true;
639             }
640             else {
641                 video_frame->setText(i18n("Failed to start Video4Linux,\ncheck your parameters..."));                
642                 m_videoBox->setHidden(true);
643                 m_isCapturing = false;
644                 m_recAction->setChecked(false);
645             }
646
647             /*
648             m_captureArgs << KdenliveSettings::video4capture().simplified().split(' ') << KdenliveSettings::video4encoding().simplified().split(' ') << "-y" << m_captureFile.path() << "-f" << KdenliveSettings::video4container() << "-acodec" << KdenliveSettings::video4acodec() << "-vcodec" << KdenliveSettings::video4vcodec() << "-";
649             m_displayArgs << "-f" << KdenliveSettings::video4container() << "-x" << QString::number(video_frame->width()) << "-y" << QString::number(video_frame->height()) << "-";
650             m_captureProcess->setStandardOutputProcess(m_displayProcess);
651             kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
652             m_captureProcess->start("ffmpeg", m_captureArgs);*/
653             break;
654         case SCREENGRAB:
655             switch (KdenliveSettings::rmd_capture_type()) {
656             case 0:
657                 // Full screen capture, nothing special to do
658                 break;
659             default:
660                 // Region capture
661                 m_captureArgs << "--width" << QString::number(KdenliveSettings::rmd_width()) << "--height" << QString::number(KdenliveSettings::rmd_height());
662                 if (!KdenliveSettings::rmd_follow_mouse()) {
663                     m_captureArgs << "-x" << QString::number(KdenliveSettings::rmd_offsetx()) << "-y" << QString::number(KdenliveSettings::rmd_offsety());
664                 } else {
665                     m_captureArgs << "--follow-mouse";
666                     if (KdenliveSettings::rmd_hide_frame()) m_captureArgs << "--no-frame";
667                 }
668                 break;
669             }
670             if (KdenliveSettings::rmd_hide_mouse()) m_captureArgs << "--no-cursor";
671             m_isCapturing = true;
672             if (KdenliveSettings::rmd_capture_audio()) {
673                 m_captureArgs << "--freq" << KdenliveSettings::rmd_freq();
674                 m_captureArgs << "--channels" << QString::number(KdenliveSettings::rmd_audio_channels());
675                 if (KdenliveSettings::rmd_use_jack()) {
676                     m_captureArgs << "--use-jack";
677                     QStringList ports = KdenliveSettings::rmd_jackports().split(" ", QString::SkipEmptyParts);
678                     for (int i = 0; i < ports.count(); ++i) {
679                         m_captureArgs << ports.at(i);
680                     }
681                     if (KdenliveSettings::rmd_jack_buffer() > 0.0)
682                         m_captureArgs << "--ring-buffer-size" << QString::number(KdenliveSettings::rmd_jack_buffer());
683                 } else {
684                     if (!KdenliveSettings::rmd_alsadevicename().isEmpty())
685                         m_captureArgs << "--device" << KdenliveSettings::rmd_alsadevicename();
686                     if (KdenliveSettings::rmd_alsa_buffer() > 0)
687                         m_captureArgs << "--buffer-size" << QString::number(KdenliveSettings::rmd_alsa_buffer());
688                 }
689             } else m_captureArgs << "--no-sound";
690
691             if (KdenliveSettings::rmd_fullshots()) m_captureArgs << "--full-shots";
692             m_captureArgs << "--v_bitrate" << QString::number(KdenliveSettings::rmd_bitrate());
693             m_captureArgs << "--v_quality" << QString::number(KdenliveSettings::rmd_quality());
694             m_captureArgs << "--workdir" << KdenliveSettings::currenttmpfolder();
695             m_captureArgs << "--fps" << QString::number(KdenliveSettings::rmd_fps()) << "-o" << m_captureFile.path();
696             m_captureProcess->start(KdenliveSettings::rmd_path(), m_captureArgs);
697             kDebug() << "// RecordMyDesktop params: " << m_captureArgs;
698             break;
699         default:
700             break;
701         }
702
703
704         if (device_selector->currentIndex() == FIREWIRE) {
705             m_isCapturing = true;
706             kDebug() << "Capture: Running ffplay " << m_displayArgs.join(" ");
707             m_displayProcess->start("ffplay", m_displayArgs);
708             video_frame->setText(i18n("Initialising..."));
709         }
710     } else {
711         // stop capture
712         m_displayProcess->kill();
713         //captureProcess->kill();
714         QTimer::singleShot(1000, this, SLOT(slotRecord()));
715     }
716 }
717
718 /*
719 void RecMonitor::slotStartGrab(const QRect &rect) {
720     rgnGrab->deleteLater();
721     QApplication::restoreOverrideCursor();
722     show();
723     if (rect.isNull()) return;
724     int width = rect.width();
725     int height = rect.height();
726     if (width % 2 != 0) width--;
727     if (height % 2 != 0) height--;
728     QString args = KdenliveSettings::screengrabcapture().replace("%size", QString::number(width) + "x" + QString::number(height)).replace("%offset", "+" + QString::number(rect.x()) + "," + QString::number(rect.y()));
729     if (KdenliveSettings::screengrabenableaudio()) {
730         // also capture audio
731         if (KdenliveSettings::useosscapture()) m_captureArgs << KdenliveSettings::screengrabosscapture().simplified().split(' ');
732         else m_captureArgs << KdenliveSettings::screengrabalsacapture2().simplified().split(' ');
733     }
734     m_captureArgs << args.simplified().split(' ') << KdenliveSettings::screengrabencoding().simplified().split(' ') << m_captureFile.path();
735     m_isCapturing = true;
736     video_frame->setText(i18n("Capturing..."));
737     if (KdenliveSettings::screengrabenableaudio() && !KdenliveSettings::useosscapture()) {
738         QStringList alsaArgs = KdenliveSettings::screengrabalsacapture().simplified().split(' ');
739         alsaProcess->setStandardOutputProcess(captureProcess);
740         kDebug() << "Capture: Running arecord " << alsaArgs.join(" ");
741         alsaProcess->start("arecord", alsaArgs);
742     }
743     kDebug() << "Capture: Running ffmpeg " << m_captureArgs.join(" ");
744     captureProcess->start("ffmpeg", m_captureArgs);
745 }*/
746
747 void RecMonitor::slotProcessStatus(QProcess::ProcessState status)
748 {
749     if (status == QProcess::NotRunning) {
750         m_displayProcess->kill();
751         if (m_isCapturing && device_selector->currentIndex() != FIREWIRE)
752             if (autoaddbox->isChecked() && QFile::exists(m_captureFile.path())) emit addProjectClip(m_captureFile);
753         if (device_selector->currentIndex() == FIREWIRE) {
754             m_discAction->setIcon(KIcon("network-connect"));
755             m_discAction->setText(i18n("Connect"));
756             m_playAction->setEnabled(false);
757             m_rewAction->setEnabled(false);
758             m_fwdAction->setEnabled(false);
759             m_recAction->setEnabled(false);
760         }
761         m_isPlaying = false;
762         m_playAction->setIcon(m_playIcon);
763         m_recAction->setChecked(false);
764         m_stopAction->setEnabled(false);
765         device_selector->setEnabled(true);
766         if (m_captureProcess && m_captureProcess->exitStatus() == QProcess::CrashExit) {
767             video_frame->setText(i18n("Capture crashed, please check your parameters"));
768         } else {
769             if (device_selector->currentIndex() != SCREENGRAB) {
770                 video_frame->setText(i18n("Not connected"));
771             } else {
772                 if (m_captureProcess->exitCode() != 0) {
773                     video_frame->setText(i18n("Capture crashed, please check your parameters\nRecordMyDesktop exit code: %1", QString::number(m_captureProcess->exitCode())));
774                 } else {
775                     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)));
776                 }
777             }
778         }
779         m_isCapturing = false;
780
781 #if KDE_IS_VERSION(4,2,0)
782         m_spaceTimer.stop();
783         // update free space info
784         slotUpdateFreeSpace();
785 #endif
786
787     } else {
788         if (device_selector->currentIndex() != SCREENGRAB) m_stopAction->setEnabled(true);
789         device_selector->setEnabled(false);
790     }
791 }
792
793 void RecMonitor::manageCapturedFiles()
794 {
795     QString extension;
796     switch (KdenliveSettings::firewireformat()) {
797     case 0:
798         extension = ".dv";
799         break;
800     case 1:
801     case 2:
802         extension = ".avi";
803         break;
804     case 3:
805         extension = ".m2t";
806         break;
807     }
808     QDir dir(m_capturePath);
809     QStringList filters;
810     QString capturename = KdenliveSettings::dvgrabfilename();
811     if (capturename.isEmpty()) capturename = "capture";
812     filters << capturename + "*" + extension;
813     const QStringList result = dir.entryList(filters, QDir::Files, QDir::Time);
814     KUrl::List capturedFiles;
815     foreach(const QString & name, result) {
816         KUrl url = KUrl(dir.filePath(name));
817         if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, this)) {
818             KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url, true);
819             if (file.time(KFileItem::ModificationTime) > m_captureTime) capturedFiles.append(url);
820         }
821     }
822     kDebug() << "Found : " << capturedFiles.count() << " new capture files";
823     kDebug() << capturedFiles;
824
825     if (capturedFiles.count() > 0) {
826         ManageCapturesDialog *d = new ManageCapturesDialog(capturedFiles, this);
827         if (d->exec() == QDialog::Accepted) {
828             capturedFiles = d->importFiles();
829             foreach(const KUrl & url, capturedFiles) {
830                 emit addProjectClip(url);
831             }
832         }
833         delete d;
834     }
835 }
836
837 // virtual
838 void RecMonitor::mousePressEvent(QMouseEvent * /*event*/)
839 {
840 #if KDE_IS_VERSION(4,2,0)
841     if (m_freeSpace->underMouse()) slotUpdateFreeSpace();
842 #endif
843 }
844
845 void RecMonitor::slotUpdateFreeSpace()
846 {
847 #if KDE_IS_VERSION(4,2,0)
848     KDiskFreeSpaceInfo info = KDiskFreeSpaceInfo::freeSpaceInfo(m_capturePath);
849     if (info.isValid()) {
850         m_freeSpace->setValue(100 * info.used() / info.size());
851         m_freeSpace->setText(i18n("Free space: %1", KIO::convertSize(info.available())));
852         m_freeSpace->update();
853     }
854 #endif
855 }
856
857 void RecMonitor::refreshRecMonitor(bool visible)
858 {
859     if (visible) {
860         //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
861
862     }
863 }
864
865 void RecMonitor::slotPlay()
866 {
867
868     //if (!m_isActive) m_monitorManager->activateRecMonitor(m_name);
869
870 }
871
872 void RecMonitor::slotReadDvgrabInfo()
873 {
874     QString data = m_captureProcess->readAllStandardError().simplified();
875     data = data.section('"', 2, 2).simplified();
876     m_dvinfo.setText(data.left(11));
877     m_dvinfo.updateGeometry();
878 }
879
880 AbstractRender *RecMonitor::abstractRender()
881 {
882     return m_captureDevice;
883 }
884
885
886 void RecMonitor::analyseFrames(bool analyse)
887 {
888     m_analyse = analyse;
889     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = analyse;
890 }
891
892
893 #include "recmonitor.moc"
894