]> git.sesse.net Git - kdenlive/blob - src/stopmotion/stopmotion.cpp
ccf55383ccf6289f05e6b320e90fd04aa7d87594
[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)
351         m_effectIndex = act->data().toInt();
352     KdenliveSettings::setStopmotioneffect(m_effectIndex);
353     slotUpdateOverlay();
354 }
355
356 void StopmotionWidget::closeEvent(QCloseEvent* e)
357 {
358     slotLive(false);
359     QDialog::closeEvent(e);
360 }
361
362 void StopmotionWidget::slotConfigure()
363 {
364     QDialog d;
365     Ui::SmConfig_UI ui;
366     ui.setupUi(&d);
367     d.setWindowTitle(i18n("Configure Stop Motion"));
368     ui.sm_interval->setValue(KdenliveSettings::captureinterval());
369     ui.sm_interval->setSuffix(ki18np(" second", " seconds"));
370     ui.sm_notifytime->setSuffix(ki18np(" second", " seconds"));
371     ui.sm_notifytime->setValue(KdenliveSettings::sm_notifytime());
372     connect(ui.sm_prenotify, SIGNAL(toggled(bool)), ui.sm_notifytime, SLOT(setEnabled(bool)));
373     ui.sm_prenotify->setChecked(KdenliveSettings::sm_prenotify());
374     ui.sm_loop->setChecked(KdenliveSettings::sm_loop());
375     ui.sm_framesplayback->setValue(KdenliveSettings::sm_framesplayback());
376
377     if (d.exec() == QDialog::Accepted) {
378         KdenliveSettings::setSm_loop(ui.sm_loop->isChecked());
379         KdenliveSettings::setCaptureinterval(ui.sm_interval->value());
380         KdenliveSettings::setSm_framesplayback(ui.sm_framesplayback->value());
381         KdenliveSettings::setSm_notifytime(ui.sm_notifytime->value());
382         KdenliveSettings::setSm_prenotify(ui.sm_prenotify->isChecked());
383         m_intervalTimer.setInterval(KdenliveSettings::captureinterval() * 1000);
384     }
385 }
386
387 void StopmotionWidget::slotShowThumbs(bool show)
388 {
389     KdenliveSettings::setShowstopmotionthumbs(show);
390     if (show) {
391         frame_list->clear();
392         sequenceNameChanged(sequence_name->currentText());
393     } else {
394         m_filesList.clear();
395         frame_list->clear();
396     }
397     frame_list->setHidden(!show);
398 }
399
400
401 void StopmotionWidget::slotUpdateDeviceHandler()
402 {
403     slotLive(false);
404     delete m_captureDevice;
405     m_captureDevice = NULL;
406     /*QString data = capture_device->itemData(capture_device->currentIndex()).toString();
407     slotLive(false);
408     if (m_bmCapture) {
409         delete m_bmCapture;
410     }
411     m_layout->removeWidget(m_frame_preview);
412     if (data == "v4l") {
413 #ifdef USE_V4L
414         m_bmCapture = new V4lCaptureHandler(m_layout);
415         m_bmCapture->setDevice(capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString(), capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 2).toString());
416 #endif
417     } else {
418         m_bmCapture = new BmdCaptureHandler(m_layout);
419         if (m_bmCapture) connect(m_bmCapture, SIGNAL(gotMessage(QString)), this, SLOT(slotGotHDMIMessage(QString)));
420     }
421     live_button->setEnabled(m_bmCapture != NULL);
422     m_layout->addWidget(m_frame_preview);*/
423 }
424
425 void StopmotionWidget::slotGotHDMIMessage(const QString& message)
426 {
427     log_box->insertItem(0, message);
428 }
429
430 void StopmotionWidget::parseExistingSequences()
431 {
432     sequence_name->clear();
433     sequence_name->addItem(QString());
434     QDir dir(m_projectFolder.path());
435     QStringList filters;
436     filters << "*_0000.png";
437     //dir.setNameFilters(filters);
438     QStringList sequences = dir.entryList(filters, QDir::Files, QDir::Name);
439     //kDebug()<<"PF: "<<<<", sm: "<<sequences;
440     foreach(const QString &sequencename, sequences) {
441         sequence_name->addItem(sequencename.section('_', 0, -2));
442     }
443 }
444
445 void StopmotionWidget::slotSwitchLive()
446 {
447     setUpdatesEnabled(false);
448     slotLive(!live_button->isChecked());
449     setUpdatesEnabled(true);
450 }
451
452 void StopmotionWidget::slotStopCapture()
453 {
454     slotLive(false);
455 }
456
457 void StopmotionWidget::slotLive(bool isOn)
458 {
459     live_button->blockSignals(true);
460     capture_button->setEnabled(false);
461     if (isOn) {
462         m_frame_preview->setHidden(true);
463         m_monitor->videoBox->setHidden(false);
464         QLocale locale;
465
466         MltVideoProfile profile;
467         QString resource;
468         QString service;
469         QString profilePath;
470         // Create MLT producer data
471         if (capture_device->itemData(capture_device->currentIndex()) == "v4l") {
472             // Capture using a video4linux device
473             profilePath = KStandardDirs::locateLocal("appdata", "profiles/video4linux");
474             profile = ProfilesDialog::getVideoProfile(profilePath);
475             service = "avformat-novalidate";
476             QString devicePath = capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString();
477             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);
478         }
479         else {
480             // Decklink capture
481             profilePath = KdenliveSettings::current_profile();
482             profile = ProfilesDialog::getVideoProfile(profilePath);
483             service = "decklink";
484             resource = capture_device->itemData(capture_device->currentIndex(), Qt::UserRole + 1).toString();
485         }
486
487         if (m_captureDevice == NULL) {
488             m_captureDevice = new MltDeviceCapture(profilePath, m_monitor->videoSurface, this);
489             m_captureDevice->sendFrameForAnalysis = KdenliveSettings::analyse_stopmotion();
490             m_monitor->setRender(m_captureDevice);
491             connect(m_captureDevice, SIGNAL(frameSaved(QString)), this, SLOT(slotNewThumb(QString)));
492         }
493
494         m_manager->activateMonitor(Kdenlive::stopmotionMonitor);
495         QString producer = createProducer(profile, service, resource);
496         if (m_captureDevice->slotStartPreview(producer, true)) {
497             if (m_showOverlay->isChecked()) {
498                 reloadOverlay();
499                 slotUpdateOverlay();
500             }
501             capture_button->setEnabled(true);
502             live_button->setChecked(true);
503             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')));
504             log_box->setCurrentIndex(0);
505         }
506         else {
507             kDebug()<<"// problem starting stopmo";
508             log_box->insertItem(-1, i18n("Failed to start device"));
509             log_box->setCurrentIndex(0);
510         }
511     }
512     else {
513         m_frame_preview->setHidden(false);
514         live_button->setChecked(false);
515         if (m_captureDevice) {
516             m_captureDevice->stop();
517             m_monitor->videoBox->setHidden(true);
518             log_box->insertItem(-1, i18n("Stopped"));
519             log_box->setCurrentIndex(0);
520             //delete m_captureDevice;
521             //m_captureDevice = NULL;
522         }
523     }
524
525     /*
526     if (isOn && m_bmCapture) {
527         //m_frame_preview->setImage(QImage());
528         m_frame_preview->setHidden(true);
529         m_bmCapture->startPreview(KdenliveSettings::hdmi_capturedevice(), KdenliveSettings::hdmi_capturemode(), false);
530         capture_button->setEnabled(true);
531         live_button->setChecked(true);
532     } else {
533         if (m_bmCapture) m_bmCapture->stopPreview();
534         m_frame_preview->setHidden(false);
535         capture_button->setEnabled(false);
536         live_button->setChecked(false);
537     }*/
538     live_button->blockSignals(false);
539 }
540
541 void StopmotionWidget::slotShowOverlay(bool isOn)
542 {
543     if (isOn) {
544         // Overlay last frame of the sequence
545         reloadOverlay();
546         slotUpdateOverlay();
547     }
548     else {
549         // Remove overlay
550         m_captureDevice->setOverlay(QString());
551     }
552 }
553
554 void StopmotionWidget::reloadOverlay()
555 {
556     const QString path = getPathForFrame(m_sequenceFrame - 1);
557     if (!QFile::exists(path)) {
558         log_box->insertItem(-1, i18n("No previous frame found"));
559         log_box->setCurrentIndex(0);
560         return;
561     }
562     m_captureDevice->setOverlay(path);
563 }
564
565 void StopmotionWidget::slotUpdateOverlay()
566 {
567     if (m_captureDevice == NULL) return;
568
569     QString tag;
570     QStringList params;
571
572     switch (m_effectIndex) {
573     case 1:
574         tag = "frei0r.contrast0r";
575         params << "Contrast=1.2";
576         break;
577     case 2:
578         tag = "charcoal";
579         params << "x_scatter=4" << "y_scatter=4" << "scale=1" << "mix=0";
580         break;
581     case 3:
582         tag = "frei0r.brightness";
583         params << "Brightness=0.7";
584         break;
585     case 4:
586         tag = "invert";
587         break;
588     case 5:
589         tag = "threshold";
590         params << "midpoint=125";
591         break;
592     default:
593         break;
594
595     }
596     m_captureDevice->setOverlayEffect(tag, params);
597 }
598
599 void StopmotionWidget::sequenceNameChanged(const QString& name)
600 {
601     // Get rid of frames from previous sequence
602     disconnect(this, SIGNAL(doCreateThumbs(QImage,int)), this, SLOT(slotCreateThumbs(QImage,int)));
603     m_filesList.clear();
604     m_future.waitForFinished();
605     frame_list->clear();
606     if (name.isEmpty()) {
607         button_addsequence->setEnabled(false);
608     } else {
609         // Check if we are editing an existing sequence
610         QString pattern = SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_filesList);
611         m_sequenceFrame = m_filesList.isEmpty() ? 0 : SlideshowClip::getFrameNumberFromPath(m_filesList.last()) + 1;
612         if (!m_filesList.isEmpty()) {
613             m_sequenceName = sequence_name->currentText();
614             connect(this, SIGNAL(doCreateThumbs(QImage,int)), this, SLOT(slotCreateThumbs(QImage,int)));
615             m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
616             button_addsequence->setEnabled(true);
617         } else {
618             // new sequence
619             connect(this, SIGNAL(doCreateThumbs(QImage,int)), this, SLOT(slotCreateThumbs(QImage,int)));
620             button_addsequence->setEnabled(false);
621         }
622         capture_button->setEnabled(live_button->isChecked());
623     }
624 }
625
626 void StopmotionWidget::slotCaptureFrame()
627 {
628     if (m_captureDevice == NULL) return;
629     if (sequence_name->currentText().isEmpty()) {
630         QString seqName = QInputDialog::getText(this, i18n("Create New Sequence"), i18n("Enter sequence name"));
631         if (seqName.isEmpty()) {
632             m_captureAction->setChecked(false);
633             return;
634         }
635         sequence_name->blockSignals(true);
636         sequence_name->setItemText(sequence_name->currentIndex(), seqName);
637         sequence_name->blockSignals(false);
638     }
639     if (m_sequenceName != sequence_name->currentText()) {
640         m_sequenceName = sequence_name->currentText();
641         m_sequenceFrame = 0;
642     }
643     //capture_button->setEnabled(false);
644     if (m_intervalTimer.isActive()) {
645         // stop interval capture
646         m_intervalTimer.stop();
647         return;
648     }
649     QString currentPath = getPathForFrame(m_sequenceFrame);
650     m_captureDevice->captureFrame(currentPath);
651     KNotification::event("FrameCaptured", i18n("Frame Captured"), QPixmap(), this);
652     m_sequenceFrame++;
653     button_addsequence->setEnabled(true);
654     if (capture_interval->isChecked()) {
655         if (KdenliveSettings::sm_prenotify())
656             QTimer::singleShot((KdenliveSettings::captureinterval() - KdenliveSettings::sm_notifytime()) * 1000, this, SLOT(slotPreNotify()));
657         m_intervalTimer.start();
658     }
659     else
660         m_captureAction->setChecked(false);
661 }
662
663 void StopmotionWidget::slotPreNotify()
664 {
665     if (m_captureAction->isChecked()) KNotification::event("ReadyToCapture", i18n("Going to Capture Frame"), QPixmap(), this);
666 }
667
668
669 void StopmotionWidget::slotNewThumb(const QString &path)
670 {
671     if (!KdenliveSettings::showstopmotionthumbs()) return;
672     m_filesList.append(path);
673     if (m_showOverlay->isChecked()) reloadOverlay();
674     if (!m_future.isRunning()) m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
675
676 }
677
678 void StopmotionWidget::slotPrepareThumbs()
679 {
680     if (m_filesList.isEmpty())
681         return;
682     QString path = m_filesList.takeFirst();
683     emit doCreateThumbs(QImage(path), SlideshowClip::getFrameNumberFromPath(path));
684
685 }
686
687 void StopmotionWidget::slotCreateThumbs(const QImage &img, int ix)
688 {
689     if (img.isNull()) {
690         m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
691         return;
692     }
693     int height = 90;
694     int width = height * img.width() / img.height();
695     frame_list->setIconSize(QSize(width, height));
696     QPixmap pix = QPixmap::fromImage(img).scaled(width, height);
697     QString nb = QString::number(ix);
698     QPainter p(&pix);
699     QFontInfo finfo(font());
700     p.fillRect(0, 0, finfo.pixelSize() * nb.count() + 6, finfo.pixelSize() + 6, QColor(80, 80, 80, 150));
701     p.setPen(Qt::white);
702     p.drawText(QPoint(3, finfo.pixelSize() + 3), nb);
703     p.end();
704     QIcon icon(pix);
705     QListWidgetItem* item = new QListWidgetItem(icon, QString(), frame_list);
706     item->setToolTip(getPathForFrame(ix, sequence_name->currentText()));
707     item->setData(Qt::UserRole, ix);
708     frame_list->blockSignals(true);
709     frame_list->setCurrentItem(item);
710     frame_list->blockSignals(false);
711     m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
712 }
713
714 QString StopmotionWidget::getPathForFrame(int ix, QString seqName)
715 {
716     if (seqName.isEmpty())
717         seqName = m_sequenceName;
718     return m_projectFolder.path(KUrl::AddTrailingSlash) + seqName + QLatin1Char('_') + QString::number(ix).rightJustified(4, '0', false) + QLatin1String(".png");
719 }
720
721 void StopmotionWidget::slotShowFrame(const QString& path)
722 {
723     //slotLive(false);
724     QImage img(path);
725     capture_button->setEnabled(false);
726     slotLive(false);
727     if (!img.isNull()) {
728         m_frame_preview->setImage(img);
729         m_frame_preview->setHidden(false);
730         m_frame_preview->update();
731     }
732 }
733
734 void StopmotionWidget::slotShowSelectedFrame()
735 {
736     QListWidgetItem* item = frame_list->currentItem();
737     if (item) {
738         //int ix = item->data(Qt::UserRole).toInt();;
739         slotShowFrame(item->toolTip());
740     }
741 }
742
743 void StopmotionWidget::slotAddSequence()
744 {
745     emit addOrUpdateSequence(getPathForFrame(0));
746 }
747
748 void StopmotionWidget::slotPlayPreview(bool animate)
749 {
750     m_animate = animate;
751     if (!animate) {
752         // stop animation
753         m_animationList.clear();
754         return;
755     }
756     if (KdenliveSettings::showstopmotionthumbs()) {
757         if (KdenliveSettings::sm_framesplayback() == 0) frame_list->setCurrentRow(0);
758         else frame_list->setCurrentRow(frame_list->count() - KdenliveSettings::sm_framesplayback());
759         QTimer::singleShot(200, this, SLOT(slotAnimate()));
760     } else {
761         SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_animationList);
762         if (KdenliveSettings::sm_framesplayback() > 0) {
763             // only play the last x frames
764             while (m_animationList.count() > KdenliveSettings::sm_framesplayback() + 1) {
765                 m_animationList.removeFirst();
766             }
767         }
768         m_animatedIndex = 0;
769         slotAnimate();
770     }
771 }
772
773 void StopmotionWidget::slotAnimate()
774 {
775     if (m_animate) {
776         if (KdenliveSettings::showstopmotionthumbs()) {
777             int newRow = frame_list->currentRow() + 1;
778             if (KdenliveSettings::sm_loop() || newRow < frame_list->count()) {
779                 if (newRow >= frame_list->count()) {
780                     if (KdenliveSettings::sm_framesplayback() == 0) newRow = 0;
781                     else {
782                         // seek to correct frame
783                         newRow = frame_list->count() - KdenliveSettings::sm_framesplayback();
784                     }
785                 }
786                 frame_list->setCurrentRow(newRow);
787                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
788                 return;
789             }
790         } else {
791             if (m_animatedIndex >= m_animationList.count()) {
792                 if (KdenliveSettings::sm_loop()) m_animatedIndex = 0;
793                 else m_animatedIndex = -1;
794             }
795             if (m_animatedIndex > -1) {
796                 slotShowFrame(m_animationList.at(m_animatedIndex));
797                 m_animatedIndex++;
798                 QTimer::singleShot(100, this, SLOT(slotAnimate()));
799                 return;
800             }
801         }
802     }
803     m_animate = false;
804     preview_button->setChecked(false);
805
806 }
807
808 QListWidgetItem* StopmotionWidget::getFrameFromIndex(int ix)
809 {
810     QListWidgetItem* item = NULL;
811     int pos = ix;
812     if (ix >= frame_list->count()) {
813         pos = frame_list->count() - 1;
814     }
815     if (ix < 0) pos = 0;
816     item = frame_list->item(pos);
817
818     int value = item->data(Qt::UserRole).toInt();
819     if (value == ix) return item;
820     else if (value < ix) {
821         pos++;
822         while (pos < frame_list->count()) {
823             item = frame_list->item(pos);
824             value = item->data(Qt::UserRole).toInt();
825             if (value == ix) return item;
826             pos++;
827         }
828     } else {
829         pos --;
830         while (pos >= 0) {
831             item = frame_list->item(pos);
832             value = item->data(Qt::UserRole).toInt();
833             if (value == ix) return item;
834             pos --;
835         }
836     }
837     return NULL;
838 }
839
840
841 void StopmotionWidget::selectFrame(int ix)
842 {
843     frame_list->blockSignals(true);
844     QListWidgetItem* item = getFrameFromIndex(ix);
845     if (!item)
846         return;
847     frame_list->setCurrentItem(item);
848     frame_list->blockSignals(false);
849 }
850
851 void StopmotionWidget::slotSeekFrame(bool forward)
852 {
853     int ix = frame_list->currentRow();
854     if (forward) {
855         if (ix < frame_list->count() - 1) frame_list->setCurrentRow(ix + 1);
856     } else if (ix > 0) frame_list->setCurrentRow(ix - 1);
857 }
858
859 void StopmotionWidget::slotRemoveFrame()
860 {
861     if (frame_list->currentItem() == NULL) return;
862     QString path = frame_list->currentItem()->toolTip();
863     if (KMessageBox::questionYesNo(this, i18n("Delete frame %1 from disk?", path), i18n("Delete Frame")) != KMessageBox::Yes)
864         return;
865
866     QFile f(path);
867     if (f.remove()) {
868         QListWidgetItem* item = frame_list->takeItem(frame_list->currentRow());
869         int ix = item->data(Qt::UserRole).toInt();
870         if (ix == m_sequenceFrame - 1) {
871             // We are removing the last frame, update counter
872             QListWidgetItem* item2 = frame_list->item(frame_list->count() - 1);
873             if (item2) m_sequenceFrame = item2->data(Qt::UserRole).toInt() + 1;
874         }
875         delete item;
876     }
877 }
878
879 void StopmotionWidget::slotSwitchAnalyse(bool isOn)
880 {
881     KdenliveSettings::setAnalyse_stopmotion(isOn);
882     if (m_captureDevice) m_captureDevice->sendFrameForAnalysis = isOn;
883 }
884
885 void StopmotionWidget::slotSwitchMirror(bool isOn)
886 {
887     //KdenliveSettings::setAnalyse_stopmotion(isOn);
888     if (m_captureDevice)
889         m_captureDevice->mirror(isOn);
890 }
891
892
893 const QString StopmotionWidget::createProducer(const MltVideoProfile &profile, const QString &service, const QString &resource)
894 {
895     Q_UNUSED(profile)
896
897     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>";
898
899     // overlay track
900     playlist.append("<playlist id=\"playlist0\"></playlist>");
901
902     // video4linux track
903     playlist.append("<playlist id=\"playlist1\"><entry producer=\"producer0\" in=\"0\" out=\"99999\"/></playlist>");
904
905     playlist.append("<tractor id=\"tractor0\" title=\"video0\" global_feed=\"1\" in=\"0\" out=\"99999\">");
906     playlist.append("<track producer=\"playlist0\"/>");
907     playlist.append("<track producer=\"playlist1\"/>");
908     playlist.append("</tractor></mlt>");
909
910
911     return playlist;
912 }
913
914
915
916
917 #include "stopmotion.moc"