]> git.sesse.net Git - kdenlive/blob - src/stopmotion/stopmotion.cpp
Reorganize and cleanup build structure
[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) && !defined(Q_OS_KFREEBSD)
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 #include <KDebug>
32 #include <KGlobalSettings>
33 #include <KFileDialog>
34 #include <KStandardDirs>
35 #include <KMessageBox>
36 #include <kdeversion.h>
37 #include <KNotification>
38
39 #include <QtConcurrentRun>
40 #include <QInputDialog>
41 #include <QComboBox>
42 #include <QVBoxLayout>
43 #include <QTimer>
44 #include <QPainter>
45 #include <QAction>
46 #include <QWheelEvent>
47 #include <QMenu>
48
49 MyLabel::MyLabel(QWidget* parent) :
50     QLabel(parent)
51 {
52 }
53
54 void MyLabel::setImage(QImage img)
55 {
56     m_img = img;
57 }
58
59 //virtual
60 void MyLabel::wheelEvent(QWheelEvent* event)
61 {
62     if (event->delta() > 0) emit seek(true);
63     else emit seek(false);
64 }
65
66 //virtual
67 void MyLabel::mousePressEvent(QMouseEvent*)
68 {
69     emit switchToLive();
70 }
71
72 //virtual
73 void MyLabel::paintEvent(QPaintEvent* event)
74 {
75     Q_UNUSED(event);
76
77     QRect r(0, 0, width(), height());
78     QPainter p(this);
79     p.fillRect(r, QColor(KdenliveSettings::window_background()));
80     double aspect_ratio = (double) m_img.width() / m_img.height();
81     int pictureHeight = height();
82     int pictureWidth = width();
83     int calculatedWidth = aspect_ratio * height();
84     if (calculatedWidth > width()) pictureHeight = width() / aspect_ratio;
85     else {
86         int calculatedHeight = width() / aspect_ratio;
87         if (calculatedHeight > height()) pictureWidth = height() * aspect_ratio;
88     }
89     p.drawImage(QRect((width() - pictureWidth) / 2, (height() - pictureHeight) / 2, pictureWidth, pictureHeight), m_img, QRect(0, 0, m_img.width(), m_img.height()));
90     p.end();
91 }
92
93
94 StopmotionMonitor::StopmotionMonitor(QWidget *parent) :
95     AbstractMonitor(parent),
96     m_captureDevice(NULL)
97 {
98 }
99
100 StopmotionMonitor::~StopmotionMonitor()
101 {
102 }
103
104 void StopmotionMonitor::setRender(MltDeviceCapture *render)
105 {
106     m_captureDevice = render;
107 }
108
109 AbstractRender *StopmotionMonitor::abstractRender()
110 {
111     return m_captureDevice;
112 }
113
114 const QString StopmotionMonitor::name() const
115 {
116     return QString("stopmotion");
117 }
118
119
120 void StopmotionMonitor::stop()
121 {
122     if (m_captureDevice) m_captureDevice->stop();
123     emit stopCapture();
124 }
125
126 void StopmotionMonitor::start()
127 {
128 }
129
130 StopmotionWidget::StopmotionWidget(MonitorManager *manager, KUrl projectFolder, QList< QAction* > actions, QWidget* parent) :
131     QDialog(parent)
132     , Ui::Stopmotion_UI()
133     , m_projectFolder(projectFolder)
134     , m_captureDevice(NULL)
135     , m_sequenceFrame(0)
136     , m_animatedIndex(-1)
137     , m_animate(false)
138     , m_manager(manager)
139     , m_monitor(new StopmotionMonitor(this))
140 {
141     //setAttribute(Qt::WA_DeleteOnClose);
142     //HACK: the monitor widget is hidden, it is just used to control the capturedevice from monitormanager
143     m_monitor->setHidden(true);
144     connect(m_monitor, SIGNAL(stopCapture()), this, SLOT(slotStopCapture()));
145     m_manager->appendMonitor(m_monitor);
146     QAction* analyse = new QAction(i18n("Send frames to color scopes"), this);
147     analyse->setCheckable(true);
148     analyse->setChecked(KdenliveSettings::analyse_stopmotion());
149     connect(analyse, SIGNAL(triggered(bool)), this, SLOT(slotSwitchAnalyse(bool)));
150
151     QAction* mirror = new QAction(i18n("Mirror display"), this);
152     mirror->setCheckable(true);
153     //mirror->setChecked(KdenliveSettings::analyse_stopmotion());
154     connect(mirror, SIGNAL(triggered(bool)), this, SLOT(slotSwitchMirror(bool)));
155
156     addActions(actions);
157     setupUi(this);
158     setWindowTitle(i18n("Stop Motion Capture"));
159     setFont(KGlobalSettings::toolBarFont());
160
161     live_button->setIcon(KIcon("camera-photo"));
162
163     m_captureAction = actions.at(0);
164     connect(m_captureAction, SIGNAL(triggered()), this, SLOT(slotCaptureFrame()));
165     m_captureAction->setCheckable(true);
166     m_captureAction->setChecked(false);
167     capture_button->setDefaultAction(m_captureAction);
168
169     connect(actions.at(1), SIGNAL(triggered()), this, SLOT(slotSwitchLive()));
170
171     QAction *intervalCapture = new QAction(i18n("Interval capture"), this);
172     intervalCapture->setIcon(KIcon("chronometer"));
173     intervalCapture->setCheckable(true);
174     intervalCapture->setChecked(false);
175     capture_interval->setDefaultAction(intervalCapture);
176
177     preview_button->setIcon(KIcon("media-playback-start"));
178     capture_button->setEnabled(false);
179
180
181     // Build config menu
182     QMenu* confMenu = new QMenu;
183     m_showOverlay = actions.at(2);
184     connect(m_showOverlay, SIGNAL(triggered(bool)), this, SLOT(slotShowOverlay(bool)));
185     overlay_button->setDefaultAction(m_showOverlay);
186     //confMenu->addAction(m_showOverlay);
187
188     m_effectIndex = KdenliveSettings::stopmotioneffect();
189     QMenu* effectsMenu = new QMenu(i18n("Overlay effect"));
190     QActionGroup* effectGroup = new QActionGroup(this);
191     QAction* noEffect = new QAction(i18n("No Effect"), effectGroup);
192     noEffect->setData(0);
193     QAction* contrastEffect = new QAction(i18n("Contrast"), effectGroup);
194     contrastEffect->setData(1);
195     QAction* edgeEffect = new QAction(i18n("Edge detect"), effectGroup);
196     edgeEffect->setData(2);
197     QAction* brightEffect = new QAction(i18n("Brighten"), effectGroup);
198     brightEffect->setData(3);
199     QAction* invertEffect = new QAction(i18n("Invert"), effectGroup);
200     invertEffect->setData(4);
201     QAction* thresEffect = new QAction(i18n("Threshold"), effectGroup);
202     thresEffect->setData(5);
203
204     effectsMenu->addAction(noEffect);
205     effectsMenu->addAction(contrastEffect);
206     effectsMenu->addAction(edgeEffect);
207     effectsMenu->addAction(brightEffect);
208     effectsMenu->addAction(invertEffect);
209     effectsMenu->addAction(thresEffect);
210     QList <QAction*> list = effectsMenu->actions();
211     for (int i = 0; i < list.count(); i++) {
212         list.at(i)->setCheckable(true);
213         if (list.at(i)->data().toInt() == m_effectIndex) {
214             list.at(i)->setChecked(true);
215         }
216     }
217     connect(effectsMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotUpdateOverlayEffect(QAction*)));
218     confMenu->addMenu(effectsMenu);
219
220     QAction* showThumbs = new QAction(KIcon("image-x-generic"), i18n("Show sequence thumbnails"), this);
221     showThumbs->setCheckable(true);
222     showThumbs->setChecked(KdenliveSettings::showstopmotionthumbs());
223     connect(showThumbs, SIGNAL(triggered(bool)), this, SLOT(slotShowThumbs(bool)));
224
225     QAction* removeCurrent = new QAction(KIcon("edit-delete"), i18n("Delete current frame"), this);
226     removeCurrent->setShortcut(Qt::Key_Delete);
227     connect(removeCurrent, SIGNAL(triggered()), this, SLOT(slotRemoveFrame()));
228
229     QAction* conf = new QAction(KIcon("configure"), i18n("Configure"), this);
230     connect(conf, SIGNAL(triggered()), this, SLOT(slotConfigure()));
231
232     confMenu->addAction(showThumbs);
233     confMenu->addAction(removeCurrent);
234     confMenu->addAction(analyse);
235     confMenu->addAction(mirror);
236     confMenu->addAction(conf);
237     config_button->setIcon(KIcon("configure"));
238     config_button->setMenu(confMenu);
239
240     connect(sequence_name, SIGNAL(textChanged(const QString&)), this, SLOT(sequenceNameChanged(const QString&)));
241     connect(sequence_name, SIGNAL(currentIndexChanged(int)), live_button, SLOT(setFocus()));
242
243     // Video widget holder
244     QVBoxLayout *layout = new QVBoxLayout;
245     layout->setContentsMargins(0, 0, 0, 0);
246     layout->setSpacing(0);
247     m_videoBox = new VideoPreviewContainer();
248     m_videoBox->setContentsMargins(0, 0, 0, 0);
249     m_videoBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
250     //m_videoBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
251     m_videoBox->setLineWidth(4);
252     layout->addWidget(m_videoBox);
253
254
255     if (BMInterface::getBlackMagicDeviceList(capture_device)) {
256         // Found a BlackMagic device
257     }
258     if (QFile::exists(KdenliveSettings::video4vdevice())) {
259 #if !defined(Q_WS_MAC) && !defined(Q_OS_FREEBSD) && !defined(Q_OS_KFREEBSD)
260         // Video 4 Linux device detection
261         for (int i = 0; i < 10; i++) {
262             QString path = "/dev/video" + QString::number(i);
263             if (QFile::exists(path)) {
264                 QStringList deviceInfo = V4lCaptureHandler::getDeviceName(path);
265                 if (!deviceInfo.isEmpty()) {
266                     capture_device->addItem(deviceInfo.at(0), "v4l");
267                     capture_device->setItemData(capture_device->count() - 1, path, Qt::UserRole + 1);
268                     capture_device->setItemData(capture_device->count() - 1, deviceInfo.at(1), Qt::UserRole + 2);
269                     if (path == KdenliveSettings::video4vdevice()) capture_device->setCurrentIndex(capture_device->count() - 1);
270                 }
271             }
272         }
273 #endif
274     }
275
276     connect(capture_device, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateDeviceHandler()));
277     /*if (m_bmCapture) {
278         connect(m_bmCapture, SIGNAL(frameSaved(const QString &)), this, SLOT(slotNewThumb(const QString &)));
279         connect(m_bmCapture, SIGNAL(gotFrame(QImage)), this, SIGNAL(gotFrame(QImage)));
280     } else live_button->setEnabled(false);*/
281
282     m_frame_preview = new MyLabel(this);
283     connect(m_frame_preview, SIGNAL(seek(bool)), this, SLOT(slotSeekFrame(bool)));
284     connect(m_frame_preview, SIGNAL(switchToLive()), this, SLOT(slotSwitchLive()));
285     layout->addWidget(m_frame_preview);
286     m_frame_preview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
287     video_preview->setLayout(layout);
288
289     //kDebug()<<video_preview->winId();
290
291     QString profilePath;
292     // Create MLT producer data
293     if (capture_device->itemData(capture_device->currentIndex()) == "v4l") {
294         // Capture using a video4linux device
295         profilePath = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
296     }
297     else {
298         // Decklink capture
299         profilePath = KdenliveSettings::current_profile();
300     }
301
302     m_captureDevice = new MltDeviceCapture(profilePath, m_videoBox, this);
303     m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
304     m_monitor->setRender(m_captureDevice);
305     connect(m_captureDevice, SIGNAL(frameSaved(const QString &)), this, SLOT(slotNewThumb(const QString &)));
306
307     live_button->setChecked(false);
308     button_addsequence->setEnabled(false);
309     connect(live_button, SIGNAL(toggled(bool)), this, SLOT(slotLive(bool)));
310     connect(button_addsequence, SIGNAL(clicked(bool)), this, SLOT(slotAddSequence()));
311     connect(preview_button, SIGNAL(clicked(bool)), this, SLOT(slotPlayPreview(bool)));
312     connect(frame_list, SIGNAL(currentRowChanged(int)), this, SLOT(slotShowSelectedFrame()));
313     connect(frame_list, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotShowSelectedFrame()));
314     connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
315
316     frame_list->addAction(removeCurrent);
317     frame_list->setContextMenuPolicy(Qt::ActionsContextMenu);
318     frame_list->setHidden(!KdenliveSettings::showstopmotionthumbs());
319     parseExistingSequences();
320     QTimer::singleShot(500, this, SLOT(slotLive()));
321     connect(&m_intervalTimer, SIGNAL(timeout()), this, SLOT(slotCaptureFrame()));
322     m_intervalTimer.setSingleShot(true);
323     m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
324 }
325
326 StopmotionWidget::~StopmotionWidget()
327 {
328     m_manager->removeMonitor(m_monitor);
329     if (m_captureDevice) {
330         m_captureDevice->stop();
331         delete m_captureDevice;
332         m_captureDevice = NULL;
333     }
334
335     delete m_monitor;
336 }
337
338 void StopmotionWidget::slotUpdateOverlayEffect(QAction* act)
339 {
340     if (act) m_effectIndex = act->data().toInt();
341     KdenliveSettings::setStopmotioneffect(m_effectIndex);
342     slotUpdateOverlay();
343 }
344
345 void StopmotionWidget::closeEvent(QCloseEvent* e)
346 {
347     slotLive(false);
348     QDialog::closeEvent(e);
349 }
350
351 void StopmotionWidget::slotConfigure()
352 {
353     QDialog d;
354     Ui::SmConfig_UI ui;
355     ui.setupUi(&d);
356     d.setWindowTitle(i18n("Configure Stop Motion"));
357     ui.sm_interval->setValue(KdenliveSettings::captureinterval());
358     ui.sm_interval->setSuffix(ki18np(" second", " seconds"));
359     ui.sm_notifytime->setSuffix(ki18np(" second", " seconds"));
360     ui.sm_notifytime->setValue(KdenliveSettings::sm_notifytime());
361     connect(ui.sm_prenotify, SIGNAL(toggled(bool)), ui.sm_notifytime, SLOT(setEnabled(bool)));
362     ui.sm_prenotify->setChecked(KdenliveSettings::sm_prenotify());
363     ui.sm_loop->setChecked(KdenliveSettings::sm_loop());
364     ui.sm_framesplayback->setValue(KdenliveSettings::sm_framesplayback());
365
366     if (d.exec() == QDialog::Accepted) {
367         KdenliveSettings::setSm_loop(ui.sm_loop->isChecked());
368         KdenliveSettings::setCaptureinterval(ui.sm_interval->value());
369         KdenliveSettings::setSm_framesplayback(ui.sm_framesplayback->value());
370         KdenliveSettings::setSm_notifytime(ui.sm_notifytime->value());
371         KdenliveSettings::setSm_prenotify(ui.sm_prenotify->isChecked());
372         m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
373     }
374 }
375
376 void StopmotionWidget::slotShowThumbs(bool show)
377 {
378     KdenliveSettings::setShowstopmotionthumbs(show);
379     if (show) {
380         frame_list->clear();
381         sequenceNameChanged(sequence_name->currentText());
382     } else {
383         m_filesList.clear();
384         frame_list->clear();
385     }
386     frame_list->setHidden(!show);
387 }
388
389
390 void StopmotionWidget::slotUpdateDeviceHandler()
391 {
392     slotLive(false);
393     delete m_captureDevice;
394     m_captureDevice = NULL;
395     /*QString data = capture_device->itemData(capture_device->currentIndex()).toString();
396     slotLive(false);
397     if (m_bmCapture) {
398         delete m_bmCapture;
399     }
400     m_layout->removeWidget(m_frame_preview);
401     if (data == "v4l") {
402 #if !defined(Q_WS_MAC) && !defined(Q_OS_FREEBSD) && !defined(Q_OS_KFREEBSD)
403         m_bmCapture = new V4lCaptureHandler(m_layout);
404         m_bmCapture->setDevice(capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString(), capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 2).toString());
405 #endif
406     } else {
407         m_bmCapture = new BmdCaptureHandler(m_layout);
408         if (m_bmCapture) connect(m_bmCapture, SIGNAL(gotMessage(const QString&)), this, SLOT(slotGotHDMIMessage(const QString&)));
409     }
410     live_button->setEnabled(m_bmCapture != NULL);
411     m_layout->addWidget(m_frame_preview);*/
412 }
413
414 void StopmotionWidget::slotGotHDMIMessage(const QString& message)
415 {
416     log_box->insertItem(0, message);
417 }
418
419 void StopmotionWidget::parseExistingSequences()
420 {
421     sequence_name->clear();
422     sequence_name->addItem(QString());
423     QDir dir(m_projectFolder.path());
424     QStringList filters;
425     filters << "*_0000.png";
426     //dir.setNameFilters(filters);
427     QStringList sequences = dir.entryList(filters, QDir::Files, QDir::Name);
428     //kDebug()<<"PF: "<<<<", sm: "<<sequences;
429     foreach(QString sequencename, sequences) {
430         sequence_name->addItem(sequencename.section("_", 0, -2));
431     }
432 }
433
434 void StopmotionWidget::slotSwitchLive()
435 {
436     setUpdatesEnabled(false);
437     slotLive(!live_button->isChecked());
438     /*if (m_frame_preview->isHidden()) {
439         //if (m_bmCapture) m_bmCapture->hidePreview(true);
440         m_videoBox->setHidden(true);
441         m_frame_preview->setHidden(false);
442     } else {
443         m_frame_preview->setHidden(true);
444         //if (m_bmCapture) m_bmCapture->hidePreview(false);
445         m_videoBox->setHidden(false);
446         capture_button->setEnabled(true);
447     }*/
448     setUpdatesEnabled(true);
449 }
450
451 void StopmotionWidget::slotStopCapture()
452 {
453     slotLive(false);
454 }
455
456 void StopmotionWidget::slotLive(bool isOn)
457 {
458     live_button->blockSignals(true);
459     capture_button->setEnabled(false);
460     if (isOn) {
461         m_frame_preview->setHidden(true);
462         m_videoBox->setHidden(false);
463         QLocale locale;
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, locale.toString((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     Q_UNUSED(profile)
888
889     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>";
890
891     // overlay track
892     playlist.append("<playlist id=\"playlist0\"></playlist>");
893
894     // video4linux track
895     playlist.append("<playlist id=\"playlist1\"><entry producer=\"producer0\" in=\"0\" out=\"99999\"/></playlist>");
896
897     playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
898     playlist.append("<track producer=\"playlist0\"/>");
899     playlist.append("<track producer=\"playlist1\"/>");
900     playlist.append("</tractor></mlt>");
901
902
903     return playlist;
904 }
905
906
907