]> git.sesse.net Git - kdenlive/blob - src/stopmotion/stopmotion.cpp
- Fix build on FreeBSD.
[kdenlive] / src / stopmotion / stopmotion.cpp
1 /***************************************************************************
2                           stopmotion.cpp  -  description
3                              -------------------
4     begin                : Feb 28 2008
5     copyright            : (C) 2010 by Jean-Baptiste Mardelle
6     email                : jb@kdenlive.org
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  ***************************************************************************/
17
18 #include "stopmotion.h"
19 #include "../blackmagic/devices.h"
20 #if !defined(Q_OS_FREEBSD)
21 #include "../v4l/v4lcapture.h"
22 #endif
23 #include "../slideshowclip.h"
24 #include "../profilesdialog.h"
25 #include "../mltdevicecapture.h"
26 #include "../recmonitor.h"
27 #include "../monitormanager.h"
28 #include "ui_smconfig_ui.h"
29 #include "kdenlivesettings.h"
30
31
32 #include <KDebug>
33 #include <KGlobalSettings>
34 #include <KFileDialog>
35 #include <KStandardDirs>
36 #include <KMessageBox>
37 #include <kdeversion.h>
38 #include <KNotification>
39
40 #include <QtConcurrentRun>
41 #include <QInputDialog>
42 #include <QComboBox>
43 #include <QVBoxLayout>
44 #include <QTimer>
45 #include <QPainter>
46 #include <QAction>
47 #include <QWheelEvent>
48 #include <QMenu>
49
50 MyLabel::MyLabel(QWidget* parent) :
51     QLabel(parent)
52 {
53 }
54
55 void MyLabel::setImage(QImage img)
56 {
57     m_img = img;
58 }
59
60 //virtual
61 void MyLabel::wheelEvent(QWheelEvent* event)
62 {
63     if (event->delta() > 0) emit seek(true);
64     else emit seek(false);
65 }
66
67 //virtual
68 void MyLabel::mousePressEvent(QMouseEvent*)
69 {
70     emit switchToLive();
71 }
72
73 //virtual
74 void MyLabel::paintEvent(QPaintEvent* event)
75 {
76     Q_UNUSED(event);
77
78     QRect r(0, 0, width(), height());
79     QPainter p(this);
80     p.fillRect(r, QColor(KdenliveSettings::window_background()));
81     double aspect_ratio = (double) m_img.width() / m_img.height();
82     int pictureHeight = height();
83     int pictureWidth = width();
84     int calculatedWidth = aspect_ratio * height();
85     if (calculatedWidth > width()) pictureHeight = width() / aspect_ratio;
86     else {
87         int calculatedHeight = width() / aspect_ratio;
88         if (calculatedHeight > height()) pictureWidth = height() * aspect_ratio;
89     }
90     p.drawImage(QRect((width() - pictureWidth) / 2, (height() - pictureHeight) / 2, pictureWidth, pictureHeight), m_img, QRect(0, 0, m_img.width(), m_img.height()));
91     p.end();
92 }
93
94
95 StopmotionMonitor::StopmotionMonitor(QWidget *parent) :
96     AbstractMonitor(parent),
97     m_captureDevice(NULL)
98 {
99 }
100
101 StopmotionMonitor::~StopmotionMonitor()
102 {
103 }
104
105 void StopmotionMonitor::setRender(MltDeviceCapture *render)
106 {
107     m_captureDevice = render;
108 }
109
110 AbstractRender *StopmotionMonitor::abstractRender()
111 {
112     return m_captureDevice;
113 }
114
115 const QString StopmotionMonitor::name() const
116 {
117     return QString("stopmotion");
118 }
119
120
121 void StopmotionMonitor::stop()
122 {
123     if (m_captureDevice) m_captureDevice->stop();
124     emit stopCapture();
125 }
126
127 void StopmotionMonitor::start()
128 {
129 }
130
131 StopmotionWidget::StopmotionWidget(MonitorManager *manager, KUrl projectFolder, QList< QAction* > actions, QWidget* parent) :
132     QDialog(parent)
133     , Ui::Stopmotion_UI()
134     , m_projectFolder(projectFolder)
135     , m_captureDevice(NULL)
136     , m_sequenceFrame(0)
137     , m_animatedIndex(-1)
138     , m_animate(false)
139     , m_manager(manager)
140     , m_monitor(new StopmotionMonitor(this))
141 {
142     //setAttribute(Qt::WA_DeleteOnClose);
143     //HACK: the monitor widget is hidden, it is just used to control the capturedevice from monitormanager
144     m_monitor->setHidden(true);
145     connect(m_monitor, SIGNAL(stopCapture()), this, SLOT(slotStopCapture()));
146     m_manager->appendMonitor(m_monitor);
147     QAction* analyse = new QAction(i18n("Send frames to color scopes"), this);
148     analyse->setCheckable(true);
149     analyse->setChecked(KdenliveSettings::analyse_stopmotion());
150     connect(analyse, SIGNAL(triggered(bool)), this, SLOT(slotSwitchAnalyse(bool)));
151
152     QAction* mirror = new QAction(i18n("Mirror display"), this);
153     mirror->setCheckable(true);
154     //mirror->setChecked(KdenliveSettings::analyse_stopmotion());
155     connect(mirror, SIGNAL(triggered(bool)), this, SLOT(slotSwitchMirror(bool)));
156
157     addActions(actions);
158     setupUi(this);
159     setWindowTitle(i18n("Stop Motion Capture"));
160     setFont(KGlobalSettings::toolBarFont());
161
162     live_button->setIcon(KIcon("camera-photo"));
163
164     m_captureAction = actions.at(0);
165     connect(m_captureAction, SIGNAL(triggered()), this, SLOT(slotCaptureFrame()));
166     m_captureAction->setCheckable(true);
167     m_captureAction->setChecked(false);
168     capture_button->setDefaultAction(m_captureAction);
169
170     connect(actions.at(1), SIGNAL(triggered()), this, SLOT(slotSwitchLive()));
171
172     QAction *intervalCapture = new QAction(i18n("Interval capture"), this);
173     intervalCapture->setIcon(KIcon("chronometer"));
174     intervalCapture->setCheckable(true);
175     intervalCapture->setChecked(false);
176     capture_interval->setDefaultAction(intervalCapture);
177
178     preview_button->setIcon(KIcon("media-playback-start"));
179     capture_button->setEnabled(false);
180
181
182     // Build config menu
183     QMenu* confMenu = new QMenu;
184     m_showOverlay = actions.at(2);
185     connect(m_showOverlay, SIGNAL(triggered(bool)), this, SLOT(slotShowOverlay(bool)));
186     overlay_button->setDefaultAction(m_showOverlay);
187     //confMenu->addAction(m_showOverlay);
188
189     m_effectIndex = KdenliveSettings::stopmotioneffect();
190     QMenu* effectsMenu = new QMenu(i18n("Overlay effect"));
191     QActionGroup* effectGroup = new QActionGroup(this);
192     QAction* noEffect = new QAction(i18n("No Effect"), effectGroup);
193     noEffect->setData(0);
194     QAction* contrastEffect = new QAction(i18n("Contrast"), effectGroup);
195     contrastEffect->setData(1);
196     QAction* edgeEffect = new QAction(i18n("Edge detect"), effectGroup);
197     edgeEffect->setData(2);
198     QAction* brightEffect = new QAction(i18n("Brighten"), effectGroup);
199     brightEffect->setData(3);
200     QAction* invertEffect = new QAction(i18n("Invert"), effectGroup);
201     invertEffect->setData(4);
202     QAction* thresEffect = new QAction(i18n("Threshold"), effectGroup);
203     thresEffect->setData(5);
204
205     effectsMenu->addAction(noEffect);
206     effectsMenu->addAction(contrastEffect);
207     effectsMenu->addAction(edgeEffect);
208     effectsMenu->addAction(brightEffect);
209     effectsMenu->addAction(invertEffect);
210     effectsMenu->addAction(thresEffect);
211     QList <QAction*> list = effectsMenu->actions();
212     for (int i = 0; i < list.count(); i++) {
213         list.at(i)->setCheckable(true);
214         if (list.at(i)->data().toInt() == m_effectIndex) {
215             list.at(i)->setChecked(true);
216         }
217     }
218     connect(effectsMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotUpdateOverlayEffect(QAction*)));
219     confMenu->addMenu(effectsMenu);
220
221     QAction* showThumbs = new QAction(KIcon("image-x-generic"), i18n("Show sequence thumbnails"), this);
222     showThumbs->setCheckable(true);
223     showThumbs->setChecked(KdenliveSettings::showstopmotionthumbs());
224     connect(showThumbs, SIGNAL(triggered(bool)), this, SLOT(slotShowThumbs(bool)));
225
226     QAction* removeCurrent = new QAction(KIcon("edit-delete"), i18n("Delete current frame"), this);
227     removeCurrent->setShortcut(Qt::Key_Delete);
228     connect(removeCurrent, SIGNAL(triggered()), this, SLOT(slotRemoveFrame()));
229
230     QAction* conf = new QAction(KIcon("configure"), i18n("Configure"), this);
231     connect(conf, SIGNAL(triggered()), this, SLOT(slotConfigure()));
232
233     confMenu->addAction(showThumbs);
234     confMenu->addAction(removeCurrent);
235     confMenu->addAction(analyse);
236     confMenu->addAction(mirror);
237     confMenu->addAction(conf);
238     config_button->setIcon(KIcon("configure"));
239     config_button->setMenu(confMenu);
240
241     connect(sequence_name, SIGNAL(textChanged(const QString&)), this, SLOT(sequenceNameChanged(const QString&)));
242     connect(sequence_name, SIGNAL(currentIndexChanged(int)), live_button, SLOT(setFocus()));
243
244     // Video widget holder
245     QVBoxLayout *layout = new QVBoxLayout;
246     layout->setContentsMargins(0, 0, 0, 0);
247     layout->setSpacing(0);
248     m_videoBox = new VideoPreviewContainer();
249     m_videoBox->setContentsMargins(0, 0, 0, 0);
250     m_videoBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
251     //m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
252     m_videoBox->setLineWidth(4);
253     layout->addWidget(m_videoBox);
254
255
256     if (BMInterface::getBlackMagicDeviceList(capture_device)) {
257         // Found a BlackMagic device
258     }
259     if (QFile::exists(KdenliveSettings::video4vdevice())) {
260 #if !defined(Q_WS_MAC) && !defined(Q_OS_FREEBSD)
261         // Video 4 Linux device detection
262         for (int i = 0; i < 10; i++) {
263             QString path = "/dev/video" + QString::number(i);
264             if (QFile::exists(path)) {
265                 QStringList deviceInfo = V4lCaptureHandler::getDeviceName(path);
266                 if (!deviceInfo.isEmpty()) {
267                     capture_device->addItem(deviceInfo.at(0), "v4l");
268                     capture_device->setItemData(capture_device->count() - 1, path, Qt::UserRole + 1);
269                     capture_device->setItemData(capture_device->count() - 1, deviceInfo.at(1), Qt::UserRole + 2);
270                     if (path == KdenliveSettings::video4vdevice()) capture_device->setCurrentIndex(capture_device->count() - 1);
271                 }
272             }
273         }
274 #endif
275     }
276
277     connect(capture_device, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateDeviceHandler()));
278     /*if (m_bmCapture) {
279         connect(m_bmCapture, SIGNAL(frameSaved(const QString)), this, SLOT(slotNewThumb(const QString)));
280         connect(m_bmCapture, SIGNAL(gotFrame(QImage)), this, SIGNAL(gotFrame(QImage)));
281     } else live_button->setEnabled(false);*/
282
283     m_frame_preview = new MyLabel(this);
284     connect(m_frame_preview, SIGNAL(seek(bool)), this, SLOT(slotSeekFrame(bool)));
285     connect(m_frame_preview, SIGNAL(switchToLive()), this, SLOT(slotSwitchLive()));
286     layout->addWidget(m_frame_preview);
287     m_frame_preview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
288     video_preview->setLayout(layout);
289
290     //kDebug()<<video_preview->winId();
291
292     QString profilePath;
293     // Create MLT producer data
294     if (capture_device->itemData(capture_device->currentIndex()) == "v4l") {
295         // Capture using a video4linux device
296         profilePath = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
297     }
298     else {
299         // Decklink capture
300         profilePath = KdenliveSettings::current_profile();
301     }
302
303     m_captureDevice = new MltDeviceCapture(profilePath, m_videoBox, this);
304     m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
305     m_monitor->setRender(m_captureDevice);
306     connect(m_captureDevice, SIGNAL(frameSaved(const QString)), this, SLOT(slotNewThumb(const QString)));
307
308     live_button->setChecked(false);
309     button_addsequence->setEnabled(false);
310     connect(live_button, SIGNAL(toggled(bool)), this, SLOT(slotLive(bool)));
311     connect(button_addsequence, SIGNAL(clicked(bool)), this, SLOT(slotAddSequence()));
312     connect(preview_button, SIGNAL(clicked(bool)), this, SLOT(slotPlayPreview(bool)));
313     connect(frame_list, SIGNAL(currentRowChanged(int)), this, SLOT(slotShowSelectedFrame()));
314     connect(frame_list, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotShowSelectedFrame()));
315     connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
316
317     frame_list->addAction(removeCurrent);
318     frame_list->setContextMenuPolicy(Qt::ActionsContextMenu);
319     frame_list->setHidden(!KdenliveSettings::showstopmotionthumbs());
320     parseExistingSequences();
321     QTimer::singleShot(500, this, SLOT(slotLive()));
322     connect(&m_intervalTimer, SIGNAL(timeout()), this, SLOT(slotCaptureFrame()));
323     m_intervalTimer.setSingleShot(true);
324     m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
325 }
326
327 StopmotionWidget::~StopmotionWidget()
328 {
329     m_manager->removeMonitor(m_monitor);
330     if (m_captureDevice) {
331         m_captureDevice->stop();
332         delete m_captureDevice;
333         m_captureDevice = NULL;
334     }
335
336     delete m_monitor;
337 }
338
339 void StopmotionWidget::slotUpdateOverlayEffect(QAction* act)
340 {
341     if (act) m_effectIndex = act->data().toInt();
342     KdenliveSettings::setStopmotioneffect(m_effectIndex);
343     slotUpdateOverlay();
344 }
345
346 void StopmotionWidget::closeEvent(QCloseEvent* e)
347 {
348     slotLive(false);
349     QDialog::closeEvent(e);
350 }
351
352 void StopmotionWidget::slotConfigure()
353 {
354     QDialog d;
355     Ui::SmConfig_UI ui;
356     ui.setupUi(&d);
357     d.setWindowTitle(i18n("Configure Stop Motion"));
358     ui.sm_interval->setValue(KdenliveSettings::captureinterval());
359     ui.sm_interval->setSuffix(ki18np(" second", " seconds"));
360     ui.sm_notifytime->setSuffix(ki18np(" second", " seconds"));
361     ui.sm_notifytime->setValue(KdenliveSettings::sm_notifytime());
362     connect(ui.sm_prenotify, SIGNAL(toggled(bool)), ui.sm_notifytime, SLOT(setEnabled(bool)));
363     ui.sm_prenotify->setChecked(KdenliveSettings::sm_prenotify());
364     ui.sm_loop->setChecked(KdenliveSettings::sm_loop());
365     ui.sm_framesplayback->setValue(KdenliveSettings::sm_framesplayback());
366
367     if (d.exec() == QDialog::Accepted) {
368         KdenliveSettings::setSm_loop(ui.sm_loop->isChecked());
369         KdenliveSettings::setCaptureinterval(ui.sm_interval->value());
370         KdenliveSettings::setSm_framesplayback(ui.sm_framesplayback->value());
371         KdenliveSettings::setSm_notifytime(ui.sm_notifytime->value());
372         KdenliveSettings::setSm_prenotify(ui.sm_prenotify->isChecked());
373         m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
374     }
375 }
376
377 void StopmotionWidget::slotShowThumbs(bool show)
378 {
379     KdenliveSettings::setShowstopmotionthumbs(show);
380     if (show) {
381         frame_list->clear();
382         sequenceNameChanged(sequence_name->currentText());
383     } else {
384         m_filesList.clear();
385         frame_list->clear();
386     }
387     frame_list->setHidden(!show);
388 }
389
390
391 void StopmotionWidget::slotUpdateDeviceHandler()
392 {
393     slotLive(false);
394     delete m_captureDevice;
395     m_captureDevice = NULL;
396     /*QString data = capture_device->itemData(capture_device->currentIndex()).toString();
397     slotLive(false);
398     if (m_bmCapture) {
399         delete m_bmCapture;
400     }
401     m_layout->removeWidget(m_frame_preview);
402     if (data == "v4l") {
403 #if !defined(Q_WS_MAC) && !defined(Q_OS_FREEBSD)
404         m_bmCapture = new V4lCaptureHandler(m_layout);
405         m_bmCapture->setDevice(capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString(), capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 2).toString());
406 #endif
407     } else {
408         m_bmCapture = new BmdCaptureHandler(m_layout);
409         if (m_bmCapture) connect(m_bmCapture, SIGNAL(gotMessage(const QString&)), this, SLOT(slotGotHDMIMessage(const QString&)));
410     }
411     live_button->setEnabled(m_bmCapture != NULL);
412     m_layout->addWidget(m_frame_preview);*/
413 }
414
415 void StopmotionWidget::slotGotHDMIMessage(const QString& message)
416 {
417     log_box->insertItem(0, message);
418 }
419
420 void StopmotionWidget::parseExistingSequences()
421 {
422     sequence_name->clear();
423     sequence_name->addItem(QString());
424     QDir dir(m_projectFolder.path());
425     QStringList filters;
426     filters << "*_0000.png";
427     //dir.setNameFilters(filters);
428     QStringList sequences = dir.entryList(filters, QDir::Files, QDir::Name);
429     //kDebug()<<"PF: "<<<<", sm: "<<sequences;
430     foreach(QString sequencename, sequences) {
431         sequence_name->addItem(sequencename.section("_", 0, -2));
432     }
433 }
434
435 void StopmotionWidget::slotSwitchLive()
436 {
437     setUpdatesEnabled(false);
438     slotLive(!live_button->isChecked());
439     /*if (m_frame_preview->isHidden()) {
440         //if (m_bmCapture) m_bmCapture->hidePreview(true);
441         m_videoBox->setHidden(true);
442         m_frame_preview->setHidden(false);
443     } else {
444         m_frame_preview->setHidden(true);
445         //if (m_bmCapture) m_bmCapture->hidePreview(false);
446         m_videoBox->setHidden(false);
447         capture_button->setEnabled(true);
448     }*/
449     setUpdatesEnabled(true);
450 }
451
452 void StopmotionWidget::slotStopCapture()
453 {
454     slotLive(false);
455 }
456
457 void StopmotionWidget::slotLive(bool isOn)
458 {
459     live_button->blockSignals(true);
460     capture_button->setEnabled(false);
461     if (isOn) {
462         m_frame_preview->setHidden(true);
463         m_videoBox->setHidden(false);
464
465         MltVideoProfile profile;
466         QString resource;
467         QString service;
468         QString profilePath;
469         // Create MLT producer data
470         if (capture_device->itemData(capture_device->currentIndex()) == "v4l") {
471             // Capture using a video4linux device
472             profilePath = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
473             profile = ProfilesDialog::getVideoProfile(profilePath);
474             service = "avformat-novalidate";
475             QString devicePath = capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString();
476             resource = QString("video4linux2:%1?width:%2&amp;height:%3&amp;frame_rate:%4").arg(devicePath).arg(profile.width).arg(profile.height).arg((double) profile.frame_rate_num / profile.frame_rate_den);
477         }
478         else {
479             // Decklink capture
480             profilePath = KdenliveSettings::current_profile();
481             profile = ProfilesDialog::getVideoProfile(profilePath);
482             service = "decklink";
483             resource = capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString();
484         }
485
486         if (m_captureDevice == NULL) {
487             m_captureDevice = new MltDeviceCapture(profilePath, m_videoBox, this);
488             m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
489             m_monitor->setRender(m_captureDevice);
490             connect(m_captureDevice, SIGNAL(frameSaved(const QString)), this, SLOT(slotNewThumb(const QString)));
491         }
492
493         m_manager->activateMonitor("stopmotion");
494         QString producer = createProducer(profile, service, resource);
495         if (m_captureDevice->slotStartPreview(producer, true)) {
496             if (m_showOverlay->isChecked()) {
497                 reloadOverlay();
498                 slotUpdateOverlay();
499             }
500             capture_button->setEnabled(true);
501             live_button->setChecked(true);
502             log_box->insertItem(-1, i18n("Playing %1x%2 (%3 fps)", profile.width, profile.height, QString::number((double)profile.frame_rate_num/profile.frame_rate_den).rightJustified(2, '0')));
503             log_box->setCurrentIndex(0);
504         }
505         else {
506             kDebug()<<"// problem starting stopmo";
507             log_box->insertItem(-1, i18n("Failed to start device"));
508             log_box->setCurrentIndex(0);
509         }
510     }
511     else {
512         m_frame_preview->setHidden(false);
513         live_button->setChecked(false);
514         if (m_captureDevice) {
515             m_captureDevice->stop();
516             m_videoBox->setHidden(true);
517             log_box->insertItem(-1, i18n("Stopped"));
518             log_box->setCurrentIndex(0);
519             //delete m_captureDevice;
520             //m_captureDevice = NULL;
521         }
522     }
523
524     /*
525     if (isOn && m_bmCapture) {
526         //m_frame_preview->setImage(QImage());
527         m_frame_preview->setHidden(true);
528         m_bmCapture->startPreview(KdenliveSettings::hdmi_capturedevice(), KdenliveSettings::hdmi_capturemode(), false);
529         capture_button->setEnabled(true);
530         live_button->setChecked(true);
531     } else {
532         if (m_bmCapture) m_bmCapture->stopPreview();
533         m_frame_preview->setHidden(false);
534         capture_button->setEnabled(false);
535         live_button->setChecked(false);
536     }*/
537     live_button->blockSignals(false);
538 }
539
540 void StopmotionWidget::slotShowOverlay(bool isOn)
541 {
542     if (isOn) {
543         // Overlay last frame of the sequence
544         reloadOverlay();
545         slotUpdateOverlay();
546     }
547     else {
548         // Remove overlay
549         m_captureDevice->setOverlay(QString());
550     }
551 }
552
553 void StopmotionWidget::reloadOverlay()
554 {
555     QString path = getPathForFrame(m_sequenceFrame - 1);
556     if (!QFile::exists(path)) {
557         log_box->insertItem(-1, i18n("No previous frame found"));
558         log_box->setCurrentIndex(0);
559         return;
560     }
561     m_captureDevice->setOverlay(path);
562 }
563
564 void StopmotionWidget::slotUpdateOverlay()
565 {
566     if (m_captureDevice == NULL) return;
567
568     QString tag;
569     QStringList params;
570
571     switch (m_effectIndex) {
572     case 1:
573         tag = "frei0r.contrast0r";
574         params << "Contrast=1.2";
575         break;
576     case 2:
577         tag = "charcoal";
578         params << "x_scatter=4" << "y_scatter=4" << "scale=1" << "mix=0";
579         break;
580     case 3:
581         tag = "frei0r.brightness";
582         params << "Brightness=0.7";
583         break;
584     case 4:
585         tag = "invert";
586         break;
587     case 5:
588         tag = "threshold";
589         params << "midpoint=125";
590         break;
591     default:
592         break;
593
594     }
595     m_captureDevice->setOverlayEffect(tag, params);
596 }
597
598 void StopmotionWidget::sequenceNameChanged(const QString& name)
599 {
600     // Get rid of frames from previous sequence
601     disconnect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
602     m_filesList.clear();
603     m_future.waitForFinished();
604     frame_list->clear();
605     if (name.isEmpty()) {
606         button_addsequence->setEnabled(false);
607     } else {
608         // Check if we are editing an existing sequence
609         QString pattern = SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_filesList);
610         m_sequenceFrame = m_filesList.isEmpty() ? 0 : SlideshowClip::getFrameNumberFromPath(m_filesList.last()) + 1;
611         if (!m_filesList.isEmpty()) {
612             m_sequenceName = sequence_name->currentText();
613             connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
614             m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
615             button_addsequence->setEnabled(true);
616         } else {
617             // new sequence
618             connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
619             button_addsequence->setEnabled(false);
620         }
621         capture_button->setEnabled(live_button->isChecked());
622     }
623 }
624
625 void StopmotionWidget::slotCaptureFrame()
626 {
627     if (m_captureDevice == NULL) return;
628     if (sequence_name->currentText().isEmpty()) {
629         QString seqName = QInputDialog::getText(this, i18n("Create New Sequence"), i18n("Enter sequence name"));
630         if (seqName.isEmpty()) {
631             m_captureAction->setChecked(false);
632             return;
633         }
634         sequence_name->blockSignals(true);
635         sequence_name->setItemText(sequence_name->currentIndex(), seqName);
636         sequence_name->blockSignals(false);
637     }
638     if (m_sequenceName != sequence_name->currentText()) {
639         m_sequenceName = sequence_name->currentText();
640         m_sequenceFrame = 0;
641     }
642     //capture_button->setEnabled(false);
643     if (m_intervalTimer.isActive()) {
644         // stop interval capture
645         m_intervalTimer.stop();
646         return;
647     }
648     QString currentPath = getPathForFrame(m_sequenceFrame);
649     m_captureDevice->captureFrame(currentPath);
650     KNotification::event("FrameCaptured", i18n("Frame Captured"), QPixmap(), this);
651     m_sequenceFrame++;
652     button_addsequence->setEnabled(true);
653     if (capture_interval->isChecked()) {
654         if (KdenliveSettings::sm_prenotify()) QTimer::singleShot((KdenliveSettings::captureinterval() - KdenliveSettings::sm_notifytime()) * 1000, this, SLOT(slotPreNotify()));
655         m_intervalTimer.start();
656     }
657     else m_captureAction->setChecked(false);
658 }
659
660 void StopmotionWidget::slotPreNotify()
661 {
662     if (m_captureAction->isChecked()) KNotification::event("ReadyToCapture", i18n("Going to Capture Frame"), QPixmap(), this);
663 }
664
665
666 void StopmotionWidget::slotNewThumb(const QString path)
667 {
668     if (!KdenliveSettings::showstopmotionthumbs()) return;
669     m_filesList.append(path);
670     if (m_showOverlay->isChecked()) reloadOverlay();
671     if (!m_future.isRunning()) m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
672
673 }
674
675 void StopmotionWidget::slotPrepareThumbs()
676 {
677     if (m_filesList.isEmpty()) return;
678     QString path = m_filesList.takeFirst();
679     emit doCreateThumbs(QImage(path), SlideshowClip::getFrameNumberFromPath(path));
680
681 }
682
683 void StopmotionWidget::slotCreateThumbs(QImage img, int ix)
684 {
685     if (img.isNull()) {
686         m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
687         return;
688     }
689     int height = 90;
690     int width = height * img.width() / img.height();
691     frame_list->setIconSize(QSize(width, height));
692     QPixmap pix = QPixmap::fromImage(img).scaled(width, height);
693     QString nb = QString::number(ix);
694     QPainter p(&pix);
695     QFontInfo finfo(font());
696     p.fillRect(0, 0, finfo.pixelSize() * nb.count() + 6, finfo.pixelSize() + 6, QColor(80, 80, 80, 150));
697     p.setPen(Qt::white);
698     p.drawText(QPoint(3, finfo.pixelSize() + 3), nb);
699     p.end();
700     QIcon icon(pix);
701     QListWidgetItem* item = new QListWidgetItem(icon, QString(), frame_list);
702     item->setToolTip(getPathForFrame(ix, sequence_name->currentText()));
703     item->setData(Qt::UserRole, ix);
704     frame_list->blockSignals(true);
705     frame_list->setCurrentItem(item);
706     frame_list->blockSignals(false);
707     m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
708 }
709
710 QString StopmotionWidget::getPathForFrame(int ix, QString seqName)
711 {
712     if (seqName.isEmpty()) seqName = m_sequenceName;
713     return m_projectFolder.path(KUrl::AddTrailingSlash) + seqName + "_" + QString::number(ix).rightJustified(4, '0', false) + ".png";
714 }
715
716 void StopmotionWidget::slotShowFrame(const QString& path)
717 {
718     //slotLive(false);
719     QImage img(path);
720     capture_button->setEnabled(false);
721     slotLive(false);
722     if (!img.isNull()) {
723         //m_videoBox->setHidden(true);
724
725         m_frame_preview->setImage(img);
726         m_frame_preview->setHidden(false);
727         m_frame_preview->update();
728     }
729 }
730
731 void StopmotionWidget::slotShowSelectedFrame()
732 {
733     QListWidgetItem* item = frame_list->currentItem();
734     if (item) {
735         //int ix = item->data(Qt::UserRole).toInt();;
736         slotShowFrame(item->toolTip());
737     }
738 }
739
740 void StopmotionWidget::slotAddSequence()
741 {
742     emit addOrUpdateSequence(getPathForFrame(0));
743 }
744
745 void StopmotionWidget::slotPlayPreview(bool animate)
746 {
747     m_animate = animate;
748     if (!animate) {
749         // stop animation
750         m_animationList.clear();
751         return;
752     }
753     if (KdenliveSettings::showstopmotionthumbs()) {
754         if (KdenliveSettings::sm_framesplayback() == 0) frame_list->setCurrentRow(0);
755         else frame_list->setCurrentRow(frame_list->count() - KdenliveSettings::sm_framesplayback());
756         QTimer::singleShot(200, this, SLOT(slotAnimate()));
757     } else {
758         SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_animationList);
759         if (KdenliveSettings::sm_framesplayback() > 0) {
760             // only play the last x frames
761             while (m_animationList.count() > KdenliveSettings::sm_framesplayback() + 1) {
762                 m_animationList.removeFirst();
763             }
764         }
765         m_animatedIndex = 0;
766         slotAnimate();
767     }
768 }
769
770 void StopmotionWidget::slotAnimate()
771 {
772     if (m_animate) {
773         if (KdenliveSettings::showstopmotionthumbs()) {
774             int newRow = frame_list->currentRow() + 1;
775             if (KdenliveSettings::sm_loop() || newRow < frame_list->count()) {
776                 if (newRow >= frame_list->count()) {
777                     if (KdenliveSettings::sm_framesplayback() == 0) newRow = 0;
778                     else {
779                         // seek to correct frame
780                         newRow = frame_list->count() - KdenliveSettings::sm_framesplayback();
781                     }
782                 }
783                 frame_list->setCurrentRow(newRow);
784                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
785                 return;
786             }
787         } else {
788             if (m_animatedIndex >= m_animationList.count()) {
789                 if (KdenliveSettings::sm_loop()) m_animatedIndex = 0;
790                 else m_animatedIndex = -1;
791             }
792             if (m_animatedIndex > -1) {
793                 slotShowFrame(m_animationList.at(m_animatedIndex));
794                 m_animatedIndex++;
795                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
796                 return;
797             }
798         }
799     }
800     m_animate = false;
801     preview_button->setChecked(false);
802
803 }
804
805 QListWidgetItem* StopmotionWidget::getFrameFromIndex(int ix)
806 {
807     QListWidgetItem* item = NULL;
808     int pos = ix;
809     if (ix >= frame_list->count()) {
810         pos = frame_list->count() - 1;
811     }
812     if (ix < 0) pos = 0;
813     item = frame_list->item(pos);
814
815     int value = item->data(Qt::UserRole).toInt();
816     if (value == ix) return item;
817     else if (value < ix) {
818         pos++;
819         while (pos < frame_list->count()) {
820             item = frame_list->item(pos);
821             value = item->data(Qt::UserRole).toInt();
822             if (value == ix) return item;
823             pos++;
824         }
825     } else {
826         pos --;
827         while (pos >= 0) {
828             item = frame_list->item(pos);
829             value = item->data(Qt::UserRole).toInt();
830             if (value == ix) return item;
831             pos --;
832         }
833     }
834     return NULL;
835 }
836
837
838 void StopmotionWidget::selectFrame(int ix)
839 {
840     frame_list->blockSignals(true);
841     QListWidgetItem* item = getFrameFromIndex(ix);
842     if (!item) return;
843     frame_list->setCurrentItem(item);
844     frame_list->blockSignals(false);
845 }
846
847 void StopmotionWidget::slotSeekFrame(bool forward)
848 {
849     int ix = frame_list->currentRow();
850     if (forward) {
851         if (ix < frame_list->count() - 1) frame_list->setCurrentRow(ix + 1);
852     } else if (ix > 0) frame_list->setCurrentRow(ix - 1);
853 }
854
855 void StopmotionWidget::slotRemoveFrame()
856 {
857     if (frame_list->currentItem() == NULL) return;
858     QString path = frame_list->currentItem()->toolTip();
859     if (KMessageBox::questionYesNo(this, i18n("Delete frame %1 from disk?", path), i18n("Delete Frame")) != KMessageBox::Yes) return;
860     QFile f(path);
861     if (f.remove()) {
862         QListWidgetItem* item = frame_list->takeItem(frame_list->currentRow());
863         int ix = item->data(Qt::UserRole).toInt();
864         if (ix == m_sequenceFrame - 1) {
865             // We are removing the last frame, update counter
866             QListWidgetItem* item2 = frame_list->item(frame_list->count() - 1);
867             if (item2) m_sequenceFrame = item2->data(Qt::UserRole).toInt() + 1;
868         }
869         delete item;
870     }
871 }
872
873 void StopmotionWidget::slotSwitchAnalyse(bool isOn)
874 {
875     KdenliveSettings::setAnalyse_stopmotion(isOn);
876     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = isOn;
877 }
878
879 void StopmotionWidget::slotSwitchMirror(bool isOn)
880 {
881     //KdenliveSettings::setAnalyse_stopmotion(isOn);
882     if (m_captureDevice) m_captureDevice->mirror(isOn);
883 }
884
885 const QString StopmotionWidget::createProducer(MltVideoProfile profile, const QString service, const QString resource)
886 {
887
888     QString playlist = "<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\">" + resource + "</property><property name=\"mlt_service\">" + service + "</property></producer>";
889
890     // overlay track
891     playlist.append("<playlist id=\"playlist0\"></playlist>");
892
893     // video4linux track
894     playlist.append("<playlist id=\"playlist1\"><entry producer=\"producer0\" in=\"0\" out=\"99999\"/></playlist>");
895
896     playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
897     playlist.append("<track producer=\"playlist0\"/>");
898     playlist.append("<track producer=\"playlist1\"/>");
899     playlist.append("</tractor></mlt>");
900
901
902     return playlist;
903 }
904
905
906