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