]> git.sesse.net Git - kdenlive/blob - src/stopmotion/stopmotion.cpp
6235ac91485874d904866f5c2f2298f3028645e0
[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 #ifdef USE_V4L
20 #include "v4l/v4lcapture.h"
21 #endif
22 #include "slideshowclip.h"
23 #include "profilesdialog.h"
24 #include "mltdevicecapture.h"
25 #include "recmonitor.h"
26 #include "monitormanager.h"
27 #include "ui_smconfig_ui.h"
28 #include "kdenlivesettings.h"
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(const QImage& img)
54 {
55     m_img = img;
56 }
57
58 //virtual
59 void MyLabel::wheelEvent(QWheelEvent* event)
60 {
61     if (event->delta() > 0)
62         emit seek(true);
63     else
64         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(MonitorManager *manager, QWidget *parent) :
96     AbstractMonitor(Kdenlive::stopmotionMonitor, manager, parent),
97     m_captureDevice(NULL)
98 {
99     createVideoSurface();
100 }
101
102 StopmotionMonitor::~StopmotionMonitor()
103 {
104 }
105
106 void StopmotionMonitor::slotSwitchFullScreen()
107 {
108 }
109
110 void StopmotionMonitor::setRender(MltDeviceCapture *render)
111 {
112     m_captureDevice = render;
113 }
114
115 AbstractRender *StopmotionMonitor::abstractRender()
116 {
117     return m_captureDevice;
118 }
119
120 Kdenlive::MONITORID StopmotionMonitor::id() const
121 {
122     return Kdenlive::stopmotionMonitor;
123 }
124
125
126 void StopmotionMonitor::stop()
127 {
128     if (m_captureDevice) m_captureDevice->stop();
129     emit stopCapture();
130 }
131
132 void StopmotionMonitor::start()
133 {
134 }
135
136 void StopmotionMonitor::slotPlay()
137 {
138 }
139
140 void StopmotionMonitor::slotMouseSeek(int /*eventDelta*/, bool /*fast*/)
141 {
142 }
143
144 StopmotionWidget::StopmotionWidget(MonitorManager *manager, const KUrl &projectFolder, const QList<QAction *> &actions, QWidget* parent) :
145     QDialog(parent)
146   , Ui::Stopmotion_UI()
147   , m_projectFolder(projectFolder)
148   , m_captureDevice(NULL)
149   , m_sequenceFrame(0)
150   , m_animatedIndex(-1)
151   , m_animate(false)
152   , m_manager(manager)
153   , m_monitor(new StopmotionMonitor(manager, this))
154 {
155     //setAttribute(Qt::WA_DeleteOnClose);
156     //HACK: the monitor widget is hidden, it is just used to control the capturedevice from monitormanager
157     m_monitor->setHidden(true);
158     connect(m_monitor, SIGNAL(stopCapture()), this, SLOT(slotStopCapture()));
159     m_manager->appendMonitor(m_monitor);
160     QAction* analyse = new QAction(i18n("Send frames to color scopes"), this);
161     analyse->setCheckable(true);
162     analyse->setChecked(KdenliveSettings::analyse_stopmotion());
163     connect(analyse, SIGNAL(triggered(bool)), this, SLOT(slotSwitchAnalyse(bool)));
164
165     QAction* mirror = new QAction(i18n("Mirror display"), this);
166     mirror->setCheckable(true);
167     //mirror->setChecked(KdenliveSettings::analyse_stopmotion());
168     connect(mirror, SIGNAL(triggered(bool)), this, SLOT(slotSwitchMirror(bool)));
169
170     addActions(actions);
171     setupUi(this);
172     setWindowTitle(i18n("Stop Motion Capture"));
173     setFont(KGlobalSettings::toolBarFont());
174
175     live_button->setIcon(KIcon("camera-photo"));
176
177     m_captureAction = actions.at(0);
178     connect(m_captureAction, SIGNAL(triggered()), this, SLOT(slotCaptureFrame()));
179     m_captureAction->setCheckable(true);
180     m_captureAction->setChecked(false);
181     capture_button->setDefaultAction(m_captureAction);
182
183     connect(actions.at(1), SIGNAL(triggered()), this, SLOT(slotSwitchLive()));
184
185     QAction *intervalCapture = new QAction(i18n("Interval capture"), this);
186     intervalCapture->setIcon(KIcon("chronometer"));
187     intervalCapture->setCheckable(true);
188     intervalCapture->setChecked(false);
189     capture_interval->setDefaultAction(intervalCapture);
190
191     preview_button->setIcon(KIcon("media-playback-start"));
192     capture_button->setEnabled(false);
193
194
195     // Build config menu
196     QMenu* confMenu = new QMenu;
197     m_showOverlay = actions.at(2);
198     connect(m_showOverlay, SIGNAL(triggered(bool)), this, SLOT(slotShowOverlay(bool)));
199     overlay_button->setDefaultAction(m_showOverlay);
200     //confMenu->addAction(m_showOverlay);
201
202     m_effectIndex = KdenliveSettings::stopmotioneffect();
203     QMenu* effectsMenu = new QMenu(i18n("Overlay effect"));
204     QActionGroup* effectGroup = new QActionGroup(this);
205     QAction* noEffect = new QAction(i18n("No Effect"), effectGroup);
206     noEffect->setData(0);
207     QAction* contrastEffect = new QAction(i18n("Contrast"), effectGroup);
208     contrastEffect->setData(1);
209     QAction* edgeEffect = new QAction(i18n("Edge detect"), effectGroup);
210     edgeEffect->setData(2);
211     QAction* brightEffect = new QAction(i18n("Brighten"), effectGroup);
212     brightEffect->setData(3);
213     QAction* invertEffect = new QAction(i18n("Invert"), effectGroup);
214     invertEffect->setData(4);
215     QAction* thresEffect = new QAction(i18n("Threshold"), effectGroup);
216     thresEffect->setData(5);
217
218     effectsMenu->addAction(noEffect);
219     effectsMenu->addAction(contrastEffect);
220     effectsMenu->addAction(edgeEffect);
221     effectsMenu->addAction(brightEffect);
222     effectsMenu->addAction(invertEffect);
223     effectsMenu->addAction(thresEffect);
224     QList <QAction*> list = effectsMenu->actions();
225     for (int i = 0; i < list.count(); ++i) {
226         list.at(i)->setCheckable(true);
227         if (list.at(i)->data().toInt() == m_effectIndex) {
228             list.at(i)->setChecked(true);
229         }
230     }
231     connect(effectsMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotUpdateOverlayEffect(QAction*)));
232     confMenu->addMenu(effectsMenu);
233
234     QAction* showThumbs = new QAction(KIcon("image-x-generic"), i18n("Show sequence thumbnails"), this);
235     showThumbs->setCheckable(true);
236     showThumbs->setChecked(KdenliveSettings::showstopmotionthumbs());
237     connect(showThumbs, SIGNAL(triggered(bool)), this, SLOT(slotShowThumbs(bool)));
238
239     QAction* removeCurrent = new QAction(KIcon("edit-delete"), i18n("Delete current frame"), this);
240     removeCurrent->setShortcut(Qt::Key_Delete);
241     connect(removeCurrent, SIGNAL(triggered()), this, SLOT(slotRemoveFrame()));
242
243     QAction* conf = new QAction(KIcon("configure"), i18n("Configure"), this);
244     connect(conf, SIGNAL(triggered()), this, SLOT(slotConfigure()));
245
246     confMenu->addAction(showThumbs);
247     confMenu->addAction(removeCurrent);
248     confMenu->addAction(analyse);
249     confMenu->addAction(mirror);
250     confMenu->addAction(conf);
251     config_button->setIcon(KIcon("configure"));
252     config_button->setMenu(confMenu);
253
254     connect(sequence_name, SIGNAL(textChanged(QString)), this, SLOT(sequenceNameChanged(QString)));
255     connect(sequence_name, SIGNAL(currentIndexChanged(int)), live_button, SLOT(setFocus()));
256
257     // Video widget holder
258     QVBoxLayout *layout = new QVBoxLayout;
259     layout->setContentsMargins(0, 0, 0, 0);
260     layout->setSpacing(0);
261     m_monitor->videoBox->setLineWidth(4);
262     layout->addWidget(m_monitor->videoBox);
263
264     if (KdenliveSettings::decklink_device_found()) {
265         // Found a BlackMagic device
266     }
267
268     if (QFile::exists(KdenliveSettings::video4vdevice())) {
269 #ifdef USE_V4L
270         // Video 4 Linux device detection
271         for (int i = 0; i < 10; ++i) {
272             QString path = "/dev/video" + QString::number(i);
273             if (QFile::exists(path)) {
274                 QStringList deviceInfo = V4lCaptureHandler::getDeviceName(path);
275                 if (!deviceInfo.isEmpty()) {
276                     capture_device->addItem(deviceInfo.at(0), "v4l");
277                     capture_device->setItemData(capture_device->count() - 1, path, Qt::UserRole + 1);
278                     capture_device->setItemData(capture_device->count() - 1, deviceInfo.at(1), Qt::UserRole + 2);
279                     if (path == KdenliveSettings::video4vdevice()) capture_device->setCurrentIndex(capture_device->count() - 1);
280                 }
281             }
282         }
283 #endif /* USE_V4L */
284     }
285
286     connect(capture_device, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateDeviceHandler()));
287     /*if (m_bmCapture) {
288         connect(m_bmCapture, SIGNAL(frameSaved(QString)), this, SLOT(slotNewThumb(QString)));
289         connect(m_bmCapture, SIGNAL(gotFrame(QImage)), this, SIGNAL(gotFrame(QImage)));
290     } else live_button->setEnabled(false);*/
291
292     m_frame_preview = new MyLabel(this);
293     connect(m_frame_preview, SIGNAL(seek(bool)), this, SLOT(slotSeekFrame(bool)));
294     connect(m_frame_preview, SIGNAL(switchToLive()), this, SLOT(slotSwitchLive()));
295     layout->addWidget(m_frame_preview);
296     m_frame_preview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
297     video_preview->setLayout(layout);
298
299     //kDebug()<<video_preview->winId();
300
301     QString profilePath;
302     // Create MLT producer data
303     if (capture_device->itemData(capture_device->currentIndex()) == "v4l") {
304         // Capture using a video4linux device
305         profilePath = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
306     }
307     else {
308         // Decklink capture
309         profilePath = KdenliveSettings::current_profile();
310     }
311
312     m_captureDevice = new MltDeviceCapture(profilePath, m_monitor->videoSurface, this);
313     m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
314     m_monitor->setRender(m_captureDevice);
315     connect(m_captureDevice, SIGNAL(frameSaved(QString)), this, SLOT(slotNewThumb(QString)));
316
317     live_button->setChecked(false);
318     button_addsequence->setEnabled(false);
319     connect(live_button, SIGNAL(toggled(bool)), this, SLOT(slotLive(bool)));
320     connect(button_addsequence, SIGNAL(clicked(bool)), this, SLOT(slotAddSequence()));
321     connect(preview_button, SIGNAL(clicked(bool)), this, SLOT(slotPlayPreview(bool)));
322     connect(frame_list, SIGNAL(currentRowChanged(int)), this, SLOT(slotShowSelectedFrame()));
323     connect(frame_list, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotShowSelectedFrame()));
324     connect(this, SIGNAL(doCreateThumbs(QImage,int)), this, SLOT(slotCreateThumbs(QImage,int)));
325
326     frame_list->addAction(removeCurrent);
327     frame_list->setContextMenuPolicy(Qt::ActionsContextMenu);
328     frame_list->setHidden(!KdenliveSettings::showstopmotionthumbs());
329     parseExistingSequences();
330     QTimer::singleShot(500, this, SLOT(slotLive()));
331     connect(&m_intervalTimer, SIGNAL(timeout()), this, SLOT(slotCaptureFrame()));
332     m_intervalTimer.setSingleShot(true);
333     m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
334 }
335
336 StopmotionWidget::~StopmotionWidget()
337 {
338     m_manager->removeMonitor(m_monitor);
339     if (m_captureDevice) {
340         m_captureDevice->stop();
341         delete m_captureDevice;
342         m_captureDevice = NULL;
343     }
344
345     delete m_monitor;
346 }
347
348 void StopmotionWidget::slotUpdateOverlayEffect(QAction* act)
349 {
350     if (act) m_effectIndex = act->data().toInt();
351     KdenliveSettings::setStopmotioneffect(m_effectIndex);
352     slotUpdateOverlay();
353 }
354
355 void StopmotionWidget::closeEvent(QCloseEvent* e)
356 {
357     slotLive(false);
358     QDialog::closeEvent(e);
359 }
360
361 void StopmotionWidget::slotConfigure()
362 {
363     QDialog d;
364     Ui::SmConfig_UI ui;
365     ui.setupUi(&d);
366     d.setWindowTitle(i18n("Configure Stop Motion"));
367     ui.sm_interval->setValue(KdenliveSettings::captureinterval());
368     ui.sm_interval->setSuffix(ki18np(" second", " seconds"));
369     ui.sm_notifytime->setSuffix(ki18np(" second", " seconds"));
370     ui.sm_notifytime->setValue(KdenliveSettings::sm_notifytime());
371     connect(ui.sm_prenotify, SIGNAL(toggled(bool)), ui.sm_notifytime, SLOT(setEnabled(bool)));
372     ui.sm_prenotify->setChecked(KdenliveSettings::sm_prenotify());
373     ui.sm_loop->setChecked(KdenliveSettings::sm_loop());
374     ui.sm_framesplayback->setValue(KdenliveSettings::sm_framesplayback());
375
376     if (d.exec() == QDialog::Accepted) {
377         KdenliveSettings::setSm_loop(ui.sm_loop->isChecked());
378         KdenliveSettings::setCaptureinterval(ui.sm_interval->value());
379         KdenliveSettings::setSm_framesplayback(ui.sm_framesplayback->value());
380         KdenliveSettings::setSm_notifytime(ui.sm_notifytime->value());
381         KdenliveSettings::setSm_prenotify(ui.sm_prenotify->isChecked());
382         m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
383     }
384 }
385
386 void StopmotionWidget::slotShowThumbs(bool show)
387 {
388     KdenliveSettings::setShowstopmotionthumbs(show);
389     if (show) {
390         frame_list->clear();
391         sequenceNameChanged(sequence_name->currentText());
392     } else {
393         m_filesList.clear();
394         frame_list->clear();
395     }
396     frame_list->setHidden(!show);
397 }
398
399
400 void StopmotionWidget::slotUpdateDeviceHandler()
401 {
402     slotLive(false);
403     delete m_captureDevice;
404     m_captureDevice = NULL;
405     /*QString data = capture_device->itemData(capture_device->currentIndex()).toString();
406     slotLive(false);
407     if (m_bmCapture) {
408         delete m_bmCapture;
409     }
410     m_layout->removeWidget(m_frame_preview);
411     if (data == "v4l") {
412 #ifdef USE_V4L
413         m_bmCapture = new V4lCaptureHandler(m_layout);
414         m_bmCapture->setDevice(capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString(), capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 2).toString());
415 #endif
416     } else {
417         m_bmCapture = new BmdCaptureHandler(m_layout);
418         if (m_bmCapture) connect(m_bmCapture, SIGNAL(gotMessage(QString)), this, SLOT(slotGotHDMIMessage(QString)));
419     }
420     live_button->setEnabled(m_bmCapture != NULL);
421     m_layout->addWidget(m_frame_preview);*/
422 }
423
424 void StopmotionWidget::slotGotHDMIMessage(const QString& message)
425 {
426     log_box->insertItem(0, message);
427 }
428
429 void StopmotionWidget::parseExistingSequences()
430 {
431     sequence_name->clear();
432     sequence_name->addItem(QString());
433     QDir dir(m_projectFolder.path());
434     QStringList filters;
435     filters << "*_0000.png";
436     //dir.setNameFilters(filters);
437     QStringList sequences = dir.entryList(filters, QDir::Files, QDir::Name);
438     //kDebug()<<"PF: "<<<<", sm: "<<sequences;
439     foreach(const QString &sequencename, sequences) {
440         sequence_name->addItem(sequencename.section('_', 0, -2));
441     }
442 }
443
444 void StopmotionWidget::slotSwitchLive()
445 {
446     setUpdatesEnabled(false);
447     slotLive(!live_button->isChecked());
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_monitor->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_monitor->videoSurface, this);
488             m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
489             m_monitor->setRender(m_captureDevice);
490             connect(m_captureDevice, SIGNAL(frameSaved(QString)), this, SLOT(slotNewThumb(QString)));
491         }
492
493         m_manager->activateMonitor(Kdenlive::stopmotionMonitor);
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_monitor->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(const 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())
713         seqName = m_sequenceName;
714     return m_projectFolder.path(KUrl::AddTrailingSlash) + seqName + QLatin1Char('_') + QString::number(ix).rightJustified(4, '0', false) + QLatin1String(".png");
715 }
716
717 void StopmotionWidget::slotShowFrame(const QString& path)
718 {
719     //slotLive(false);
720     QImage img(path);
721     capture_button->setEnabled(false);
722     slotLive(false);
723     if (!img.isNull()) {
724         m_frame_preview->setImage(img);
725         m_frame_preview->setHidden(false);
726         m_frame_preview->update();
727     }
728 }
729
730 void StopmotionWidget::slotShowSelectedFrame()
731 {
732     QListWidgetItem* item = frame_list->currentItem();
733     if (item) {
734         //int ix = item->data(Qt::UserRole).toInt();;
735         slotShowFrame(item->toolTip());
736     }
737 }
738
739 void StopmotionWidget::slotAddSequence()
740 {
741     emit addOrUpdateSequence(getPathForFrame(0));
742 }
743
744 void StopmotionWidget::slotPlayPreview(bool animate)
745 {
746     m_animate = animate;
747     if (!animate) {
748         // stop animation
749         m_animationList.clear();
750         return;
751     }
752     if (KdenliveSettings::showstopmotionthumbs()) {
753         if (KdenliveSettings::sm_framesplayback() == 0) frame_list->setCurrentRow(0);
754         else frame_list->setCurrentRow(frame_list->count() - KdenliveSettings::sm_framesplayback());
755         QTimer::singleShot(200, this, SLOT(slotAnimate()));
756     } else {
757         SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_animationList);
758         if (KdenliveSettings::sm_framesplayback() > 0) {
759             // only play the last x frames
760             while (m_animationList.count() > KdenliveSettings::sm_framesplayback() + 1) {
761                 m_animationList.removeFirst();
762             }
763         }
764         m_animatedIndex = 0;
765         slotAnimate();
766     }
767 }
768
769 void StopmotionWidget::slotAnimate()
770 {
771     if (m_animate) {
772         if (KdenliveSettings::showstopmotionthumbs()) {
773             int newRow = frame_list->currentRow() + 1;
774             if (KdenliveSettings::sm_loop() || newRow < frame_list->count()) {
775                 if (newRow >= frame_list->count()) {
776                     if (KdenliveSettings::sm_framesplayback() == 0) newRow = 0;
777                     else {
778                         // seek to correct frame
779                         newRow = frame_list->count() - KdenliveSettings::sm_framesplayback();
780                     }
781                 }
782                 frame_list->setCurrentRow(newRow);
783                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
784                 return;
785             }
786         } else {
787             if (m_animatedIndex >= m_animationList.count()) {
788                 if (KdenliveSettings::sm_loop()) m_animatedIndex = 0;
789                 else m_animatedIndex = -1;
790             }
791             if (m_animatedIndex > -1) {
792                 slotShowFrame(m_animationList.at(m_animatedIndex));
793                 m_animatedIndex++;
794                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
795                 return;
796             }
797         }
798     }
799     m_animate = false;
800     preview_button->setChecked(false);
801
802 }
803
804 QListWidgetItem* StopmotionWidget::getFrameFromIndex(int ix)
805 {
806     QListWidgetItem* item = NULL;
807     int pos = ix;
808     if (ix >= frame_list->count()) {
809         pos = frame_list->count() - 1;
810     }
811     if (ix < 0) pos = 0;
812     item = frame_list->item(pos);
813
814     int value = item->data(Qt::UserRole).toInt();
815     if (value == ix) return item;
816     else if (value < ix) {
817         pos++;
818         while (pos < frame_list->count()) {
819             item = frame_list->item(pos);
820             value = item->data(Qt::UserRole).toInt();
821             if (value == ix) return item;
822             pos++;
823         }
824     } else {
825         pos --;
826         while (pos >= 0) {
827             item = frame_list->item(pos);
828             value = item->data(Qt::UserRole).toInt();
829             if (value == ix) return item;
830             pos --;
831         }
832     }
833     return NULL;
834 }
835
836
837 void StopmotionWidget::selectFrame(int ix)
838 {
839     frame_list->blockSignals(true);
840     QListWidgetItem* item = getFrameFromIndex(ix);
841     if (!item)
842         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)
860         return;
861
862     QFile f(path);
863     if (f.remove()) {
864         QListWidgetItem* item = frame_list->takeItem(frame_list->currentRow());
865         int ix = item->data(Qt::UserRole).toInt();
866         if (ix == m_sequenceFrame - 1) {
867             // We are removing the last frame, update counter
868             QListWidgetItem* item2 = frame_list->item(frame_list->count() - 1);
869             if (item2) m_sequenceFrame = item2->data(Qt::UserRole).toInt() + 1;
870         }
871         delete item;
872     }
873 }
874
875 void StopmotionWidget::slotSwitchAnalyse(bool isOn)
876 {
877     KdenliveSettings::setAnalyse_stopmotion(isOn);
878     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = isOn;
879 }
880
881 void StopmotionWidget::slotSwitchMirror(bool isOn)
882 {
883     //KdenliveSettings::setAnalyse_stopmotion(isOn);
884     if (m_captureDevice)
885         m_captureDevice->mirror(isOn);
886 }
887
888
889 const QString StopmotionWidget::createProducer(const MltVideoProfile &profile, const QString &service, const QString &resource)
890 {
891     Q_UNUSED(profile)
892
893     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>";
894
895     // overlay track
896     playlist.append("<playlist id=\"playlist0\"></playlist>");
897
898     // video4linux track
899     playlist.append("<playlist id=\"playlist1\"><entry producer=\"producer0\" in=\"0\" out=\"99999\"/></playlist>");
900
901     playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
902     playlist.append("<track producer=\"playlist0\"/>");
903     playlist.append("<track producer=\"playlist1\"/>");
904     playlist.append("</tractor></mlt>");
905
906
907     return playlist;
908 }
909
910
911
912
913 #include "stopmotion.moc"