]> git.sesse.net Git - kdenlive/blob - src/stopmotion/stopmotion.cpp
Display webcam pixel format in wizard
[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 "kdenlivesettings.h"
23
24
25 #include <KDebug>
26 #include <KGlobalSettings>
27 #include <KFileDialog>
28 #include <KStandardDirs>
29 #include <KMessageBox>
30 #include <kdeversion.h>
31 #include <KNotification>
32
33 #ifdef QIMAGEBLITZ
34 #include <qimageblitz/qimageblitz.h>
35 #endif
36
37 #include <QtConcurrentRun>
38 #include <QInputDialog>
39 #include <QComboBox>
40 #include <QVBoxLayout>
41 #include <QTimer>
42 #include <QPainter>
43 #include <QAction>
44 #include <QWheelEvent>
45 #include <QMenu>
46
47 MyLabel::MyLabel(QWidget *parent) :
48     QLabel(parent)
49 {
50 }
51
52 void MyLabel::setImage(QImage img)
53 {
54     m_img = img;
55 }
56
57 //virtual
58 void MyLabel::wheelEvent(QWheelEvent * event)
59 {
60     if (event->delta() > 0) emit seek(true);
61     else emit seek(false);
62 }
63
64 //virtual
65 void MyLabel::mousePressEvent(QMouseEvent *)
66 {
67     emit switchToLive();
68 }
69
70 //virtual
71 void MyLabel::paintEvent(QPaintEvent * event)
72 {
73     Q_UNUSED(event);
74
75     QRect r(0, 0, width(), height());
76     QPainter p(this);
77     p.fillRect(r, QColor(KdenliveSettings::window_background()));
78     double aspect_ratio = (double) m_img.width() / m_img.height();
79     int pictureHeight = height();
80     int pictureWidth = width();
81     int calculatedWidth = aspect_ratio * height();
82     if (calculatedWidth > width()) pictureHeight = width() / aspect_ratio;
83     else {
84         int calculatedHeight = width() / aspect_ratio;
85         if (calculatedHeight > height()) pictureWidth = height() * aspect_ratio;
86     }
87     p.drawImage(QRect((width() - pictureWidth) / 2, (height() - pictureHeight) / 2, pictureWidth, pictureHeight), m_img, QRect(0, 0, m_img.width(), m_img.height()));
88     p.end();
89 }
90
91
92 StopmotionWidget::StopmotionWidget(KUrl projectFolder, const QList< QAction * > actions, QWidget *parent) :
93     QDialog(parent)
94     , Ui::Stopmotion_UI()
95     , m_projectFolder(projectFolder)
96     , m_bmCapture(NULL)
97     , m_sequenceFrame(0)
98     , m_animatedIndex(-1)
99 {
100     addActions(actions);
101     setupUi(this);
102     setWindowTitle(i18n("Stop Motion Capture"));
103     setFont(KGlobalSettings::toolBarFont());
104
105     live_button->setIcon(KIcon("camera-photo"));
106
107     m_captureAction = actions.at(0);
108     connect(m_captureAction, SIGNAL(triggered()), this, SLOT(slotCaptureFrame()));
109     capture_button->setDefaultAction(m_captureAction);
110
111     connect(actions.at(1), SIGNAL(triggered()), this, SLOT(slotSwitchLive()));
112
113     preview_button->setIcon(KIcon("media-playback-start"));
114     capture_button->setEnabled(false);
115
116     // Build config menu
117     QMenu *confMenu = new QMenu;
118     m_showOverlay = actions.at(2);
119     connect(m_showOverlay, SIGNAL(triggered(bool)), this, SLOT(slotShowOverlay(bool)));
120     confMenu->addAction(m_showOverlay);
121
122 #ifdef QIMAGEBLITZ
123     m_effectIndex = KdenliveSettings::blitzeffect();
124     QMenu *effectsMenu = new QMenu(i18n("Overlay effect"));
125     QActionGroup *effectGroup = new QActionGroup(this);
126     QAction *noEffect = new QAction(i18n("No Effect"), effectGroup);
127     noEffect->setData(1);
128     QAction *contrastEffect = new QAction(i18n("Contrast"), effectGroup);
129     contrastEffect->setData(2);
130     QAction *edgeEffect = new QAction(i18n("Edge detect"), effectGroup);
131     edgeEffect->setData(3);
132     QAction *brightEffect = new QAction(i18n("Brighten"), effectGroup);
133     brightEffect->setData(4);
134     QAction *invertEffect = new QAction(i18n("Invert"), effectGroup);
135     invertEffect->setData(5);
136     QAction *thresEffect = new QAction(i18n("Threshold"), effectGroup);
137     thresEffect->setData(6);
138
139     effectsMenu->addAction(noEffect);
140     effectsMenu->addAction(contrastEffect);
141     effectsMenu->addAction(edgeEffect);
142     effectsMenu->addAction(brightEffect);
143     effectsMenu->addAction(invertEffect);
144     effectsMenu->addAction(thresEffect);
145     QList <QAction *> list = effectsMenu->actions();
146     for (int i = 0; i < list.count(); i++) {
147         list.at(i)->setCheckable(true);
148         if (list.at(i)->data().toInt() == m_effectIndex) {
149             list.at(i)->setChecked(true);
150         }
151     }
152     connect(effectsMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotUpdateOverlayEffect(QAction*)));
153     confMenu->addMenu(effectsMenu);
154 #endif
155
156     QAction *showThumbs = new QAction(KIcon("image-x-generic"), i18n("Show sequence thumbnails"), this);
157     showThumbs->setCheckable(true);
158     showThumbs->setChecked(KdenliveSettings::showstopmotionthumbs());
159     connect(showThumbs, SIGNAL(triggered(bool)), this, SLOT(slotShowThumbs(bool)));
160
161     QAction *removeCurrent = new QAction(KIcon("edit-delete"), i18n("Delete current frame"), this);
162     removeCurrent->setShortcut(Qt::Key_Delete);
163     connect(removeCurrent, SIGNAL(triggered()), this, SLOT(slotRemoveFrame()));
164
165     QAction *capInterval = new QAction(KIcon(), i18n("Set capture interval"), this);
166     connect(capInterval, SIGNAL(triggered()), this, SLOT(slotSetCaptureInterval()));
167
168     confMenu->addAction(showThumbs);
169     confMenu->addAction(capInterval);
170     confMenu->addAction(removeCurrent);
171     config_button->setIcon(KIcon("configure"));
172     config_button->setMenu(confMenu);
173
174     // Build capture menu
175     QMenu *capMenu = new QMenu;
176     m_intervalCapture = new QAction(KIcon("edit-redo"), i18n("Interval capture"), this);
177     m_intervalCapture->setCheckable(true);
178     m_intervalCapture->setChecked(false);
179     connect(m_intervalCapture, SIGNAL(triggered(bool)), this, SLOT(slotIntervalCapture(bool)));
180     capMenu->addAction(m_intervalCapture);
181     capture_button->setMenu(capMenu);
182
183     connect(sequence_name, SIGNAL(textChanged(const QString &)), this, SLOT(sequenceNameChanged(const QString &)));
184     connect(sequence_name, SIGNAL(currentIndexChanged(int)), live_button, SLOT(setFocus()));
185
186     m_layout = new QVBoxLayout;
187     if (BMInterface::getBlackMagicDeviceList(capture_device, NULL)) {
188         // Found a BlackMagic device
189         m_bmCapture = new BmdCaptureHandler(m_layout);
190         connect(m_bmCapture, SIGNAL(gotMessage(const QString &)), this, SLOT(slotGotHDMIMessage(const QString &)));
191     }
192     if (QFile::exists(KdenliveSettings::video4vdevice())) {
193         if (m_bmCapture == NULL) m_bmCapture = new V4lCaptureHandler(m_layout);
194         capture_device->addItem(m_bmCapture->getDeviceName(KdenliveSettings::video4vdevice()).at(0), "v4l");
195     }
196
197     connect(m_bmCapture, SIGNAL(frameSaved(const QString)), this, SLOT(slotNewThumb(const QString)));
198     connect(capture_device, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateHandler()));
199     m_frame_preview = new MyLabel(this);
200     connect(m_frame_preview, SIGNAL(seek(bool)), this, SLOT(slotSeekFrame(bool)));
201     connect(m_frame_preview, SIGNAL(switchToLive()), this, SLOT(slotSwitchLive()));
202     m_layout->addWidget(m_frame_preview);
203     m_frame_preview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
204     video_preview->setLayout(m_layout);
205     live_button->setChecked(false);
206     button_addsequence->setEnabled(false);
207     connect(live_button, SIGNAL(clicked(bool)), this, SLOT(slotLive(bool)));
208     connect(button_addsequence, SIGNAL(clicked(bool)), this, SLOT(slotAddSequence()));
209     connect(preview_button, SIGNAL(clicked(bool)), this, SLOT(slotPlayPreview(bool)));
210     connect(frame_list, SIGNAL(currentRowChanged(int)), this, SLOT(slotShowSelectedFrame()));
211     connect(frame_list, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(slotShowSelectedFrame()));
212     connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
213
214     frame_list->addAction(removeCurrent);
215     frame_list->setContextMenuPolicy(Qt::ActionsContextMenu);
216     frame_list->setHidden(!KdenliveSettings::showstopmotionthumbs());
217     parseExistingSequences();
218 }
219
220 StopmotionWidget::~StopmotionWidget()
221 {
222     m_bmCapture->stopPreview();
223 }
224
225 void StopmotionWidget::slotUpdateOverlayEffect(QAction *act)
226 {
227 #ifdef QIMAGEBLITZ
228     if (act) m_effectIndex = act->data().toInt();
229     KdenliveSettings::setBlitzeffect(m_effectIndex);
230     if (m_showOverlay->isChecked()) slotUpdateOverlay();
231 #endif
232 }
233
234 void StopmotionWidget::closeEvent(QCloseEvent *e)
235 {
236     slotLive(false);
237     QDialog::closeEvent(e);
238 }
239
240 void StopmotionWidget::slotSetCaptureInterval()
241 {
242     int interval = QInputDialog::getInteger(this, i18n("Set Capture Interval"), i18n("Interval (in seconds)"), KdenliveSettings::captureinterval(), 1);
243     if (interval > 0 && interval != KdenliveSettings::captureinterval())
244         KdenliveSettings::setCaptureinterval(interval);
245 }
246
247 void StopmotionWidget::slotShowThumbs(bool show)
248 {
249     KdenliveSettings::setShowstopmotionthumbs(show);
250     if (show) {
251         frame_list->clear();
252         sequenceNameChanged(sequence_name->currentText());
253     } else {
254         m_filesList.clear();
255         frame_list->clear();
256     }
257     frame_list->setHidden(!show);
258 }
259
260 void StopmotionWidget::slotIntervalCapture(bool capture)
261 {
262     if (capture) slotCaptureFrame();
263 }
264
265
266 void StopmotionWidget::slotUpdateHandler()
267 {
268     QString data = capture_device->itemData(capture_device->currentIndex()).toString();
269     m_bmCapture->stopPreview();
270     delete m_bmCapture;
271     m_layout->removeWidget(m_frame_preview);
272     if (data == "v4l") {
273         m_bmCapture = new V4lCaptureHandler(m_layout);
274     } else {
275         m_bmCapture = new BmdCaptureHandler(m_layout);
276         connect(m_bmCapture, SIGNAL(gotMessage(const QString &)), this, SLOT(slotGotHDMIMessage(const QString &)));
277     }
278     m_layout->addWidget(m_frame_preview);
279 }
280
281 void StopmotionWidget::slotGotHDMIMessage(const QString &message)
282 {
283     log_box->insertItem(0, message);
284 }
285
286 void StopmotionWidget::parseExistingSequences()
287 {
288     sequence_name->clear();
289     sequence_name->addItem(QString());
290     QDir dir(m_projectFolder.path());
291     QStringList filters;
292     filters << "*_0000.png";
293     //dir.setNameFilters(filters);
294     QStringList sequences = dir.entryList(filters, QDir::Files, QDir::Name);
295     //kDebug()<<"PF: "<<<<", sm: "<<sequences;
296     foreach(QString sequencename, sequences) {
297         sequence_name->addItem(sequencename.section("_", 0, -2));
298     }
299 }
300
301 void StopmotionWidget::slotSwitchLive()
302 {
303     setUpdatesEnabled(false);
304     if (m_frame_preview->isHidden()) {
305         m_bmCapture->hidePreview(true);
306         m_frame_preview->setHidden(false);
307     } else {
308         m_frame_preview->setHidden(true);
309         m_bmCapture->hidePreview(false);
310     }
311     setUpdatesEnabled(true);
312 }
313
314 void StopmotionWidget::slotLive(bool isOn)
315 {
316     if (isOn) {
317         //m_frame_preview->setImage(QImage());
318         m_frame_preview->setHidden(true);
319         m_bmCapture->startPreview(KdenliveSettings::hdmi_capturedevice(), KdenliveSettings::hdmi_capturemode(), false);
320         capture_button->setEnabled(true);
321     } else {
322         m_bmCapture->stopPreview();
323         m_frame_preview->setHidden(false);
324         capture_button->setEnabled(false);
325         live_button->setChecked(false);
326     }
327 }
328
329 void StopmotionWidget::slotShowOverlay(bool isOn)
330 {
331     if (isOn) {
332         if (live_button->isChecked() && m_sequenceFrame > 0) {
333             slotUpdateOverlay();
334         }
335     } else {
336         m_bmCapture->hideOverlay();
337     }
338 }
339
340 void StopmotionWidget::slotUpdateOverlay()
341 {
342     QString path = getPathForFrame(m_sequenceFrame - 1);
343     if (!QFile::exists(path)) return;
344     QImage img(path);
345     if (img.isNull()) {
346         QTimer::singleShot(1000, this, SLOT(slotUpdateOverlay()));
347         return;
348     }
349
350 #ifdef QIMAGEBLITZ
351     //img = Blitz::convolveEdge(img, 0, Blitz::Low);
352     switch (m_effectIndex) {
353     case 2:
354         img = Blitz::contrast(img, true, 6);
355         break;
356     case 3:
357         img = Blitz::edge(img);
358         break;
359     case 4:
360         img = Blitz::intensity(img, 0.5);
361         break;
362     case 5:
363         Blitz::invert(img);
364         break;
365     case 6:
366         img = Blitz::threshold(img, 120, Blitz::Grayscale, qRgba(0, 0, 0, 0), qRgba(255, 0, 0, 255));
367         //img = Blitz::flatten(img, QColor(255, 0, 0, 255), QColor(0, 0, 0, 0));
368         break;
369     default:
370         break;
371
372     }
373 #endif
374     m_bmCapture->showOverlay(img);
375 }
376
377 void StopmotionWidget::sequenceNameChanged(const QString &name)
378 {
379     // Get rid of frames from previous sequence
380     disconnect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
381     m_filesList.clear();
382     m_future.waitForFinished();
383     frame_list->clear();
384     if (name.isEmpty()) {
385         button_addsequence->setEnabled(false);
386     } else {
387         // Check if we are editing an existing sequence
388         QString pattern = SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_filesList);
389         m_sequenceFrame = m_filesList.isEmpty() ? 0 : SlideshowClip::getFrameNumberFromPath(m_filesList.last()) + 1;
390         if (!m_filesList.isEmpty()) {
391             m_sequenceName = sequence_name->currentText();
392             connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
393             m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
394             button_addsequence->setEnabled(true);
395         } else {
396             // new sequence
397             connect(this, SIGNAL(doCreateThumbs(QImage, int)), this, SLOT(slotCreateThumbs(QImage, int)));
398             button_addsequence->setEnabled(false);
399         }
400         capture_button->setEnabled(live_button->isChecked());
401     }
402 }
403
404 void StopmotionWidget::slotCaptureFrame()
405 {
406     if (sequence_name->currentText().isEmpty()) {
407         QString seqName = QInputDialog::getText(this, i18n("Create New Sequence"), i18n("Enter sequence name"));
408         if (seqName.isEmpty()) return;
409         sequence_name->blockSignals(true);
410         sequence_name->setItemText(sequence_name->currentIndex(), seqName);
411         sequence_name->blockSignals(false);
412     }
413     if (m_sequenceName != sequence_name->currentText()) {
414         m_sequenceName = sequence_name->currentText();
415         m_sequenceFrame = 0;
416     }
417     //capture_button->setEnabled(false);
418     QString currentPath = getPathForFrame(m_sequenceFrame);
419     m_bmCapture->captureFrame(currentPath);
420     KNotification::event("FrameCaptured");
421     m_sequenceFrame++;
422     button_addsequence->setEnabled(true);
423     if (m_intervalCapture->isChecked()) QTimer::singleShot(KdenliveSettings::captureinterval() * 1000, this, SLOT(slotCaptureFrame()));
424 }
425
426
427 void StopmotionWidget::slotNewThumb(const QString path)
428 {
429     if (!KdenliveSettings::showstopmotionthumbs()) return;
430     m_filesList.append(path);
431     if (m_showOverlay->isChecked()) slotUpdateOverlay();
432     if (!m_future.isRunning()) m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
433 }
434
435 void StopmotionWidget::slotPrepareThumbs()
436 {
437     if (m_filesList.isEmpty()) return;
438     QString path = m_filesList.takeFirst();
439     emit doCreateThumbs(QImage(path), SlideshowClip::getFrameNumberFromPath(path));
440
441 }
442
443 void StopmotionWidget::slotCreateThumbs(QImage img, int ix)
444 {
445     if (img.isNull()) {
446         m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
447         return;
448     }
449     int height = 90;
450     int width = height * img.width() / img.height();
451     frame_list->setIconSize(QSize(width, height));
452     QPixmap pix = QPixmap::fromImage(img).scaled(width, height);
453     QString nb = QString::number(ix);
454     QPainter p(&pix);
455     QFontInfo finfo(font());
456     p.fillRect(0, 0, finfo.pixelSize() * nb.count() + 6, finfo.pixelSize() + 6, QColor(80, 80, 80, 150));
457     p.setPen(Qt::white);
458     p.drawText(QPoint(3, finfo.pixelSize() + 3), nb);
459     p.end();
460     QIcon icon(pix);
461     QListWidgetItem *item = new QListWidgetItem(icon, QString(), frame_list);
462     item->setToolTip(getPathForFrame(ix, sequence_name->currentText()));
463     item->setData(Qt::UserRole, ix);
464     frame_list->blockSignals(true);
465     frame_list->setCurrentItem(item);
466     frame_list->blockSignals(false);
467     m_future = QtConcurrent::run(this, &StopmotionWidget::slotPrepareThumbs);
468 }
469
470 QString StopmotionWidget::getPathForFrame(int ix, QString seqName)
471 {
472     if (seqName.isEmpty()) seqName = m_sequenceName;
473     return m_projectFolder.path(KUrl::AddTrailingSlash) + seqName + "_" + QString::number(ix).rightJustified(4, '0', false) + ".png";
474 }
475
476 void StopmotionWidget::slotShowFrame(const QString &path)
477 {
478     //slotLive(false);
479     QImage img(path);
480     capture_button->setEnabled(false);
481     if (!img.isNull()) {
482         m_bmCapture->hidePreview(true);
483         m_frame_preview->setImage(img);
484         m_frame_preview->setHidden(false);
485         m_frame_preview->update();
486     }
487 }
488
489 void StopmotionWidget::slotShowSelectedFrame()
490 {
491     QListWidgetItem *item = frame_list->currentItem();
492     if (item) {
493         //int ix = item->data(Qt::UserRole).toInt();;
494         slotShowFrame(item->toolTip());
495     }
496 }
497
498 void StopmotionWidget::slotAddSequence()
499 {
500     emit addOrUpdateSequence(getPathForFrame(0));
501 }
502
503 void StopmotionWidget::slotPlayPreview(bool animate)
504 {
505     if (!animate) {
506         // stop animation
507         m_animationList.clear();
508         return;
509     }
510     if (KdenliveSettings::showstopmotionthumbs()) {
511         frame_list->setCurrentRow(0);
512         QTimer::singleShot(200, this, SLOT(slotAnimate()));
513     } else {
514         SlideshowClip::selectedPath(getPathForFrame(0, sequence_name->currentText()), false, QString(), &m_animationList);
515         slotAnimate();
516     }
517 }
518
519 void StopmotionWidget::slotAnimate()
520 {
521     //slotShowFrame(m_animatedIndex);
522     if (KdenliveSettings::showstopmotionthumbs()) {
523         //TODO: loop
524         if (frame_list->currentRow() < (frame_list->count() - 1)) {
525             frame_list->setCurrentRow(frame_list->currentRow() + 1);
526             QTimer::singleShot(100, this, SLOT(slotAnimate()));
527         } else preview_button->setChecked(false);
528     } else if (!m_animationList.isEmpty()) {
529         slotShowFrame(m_animationList.takeFirst());
530         QTimer::singleShot(100, this, SLOT(slotAnimate()));
531     } else preview_button->setChecked(false);
532
533 }
534
535 QListWidgetItem *StopmotionWidget::getFrameFromIndex(int ix)
536 {
537     QListWidgetItem *item = NULL;
538     int pos = ix;
539     if (ix >= frame_list->count()) {
540         pos = frame_list->count() - 1;
541     }
542     if (ix < 0) pos = 0;
543     item = frame_list->item(pos);
544
545     int value = item->data(Qt::UserRole).toInt();
546     if (value == ix) return item;
547     else if (value < ix) {
548         pos++;
549         while (pos < frame_list->count()) {
550             item = frame_list->item(pos);
551             value = item->data(Qt::UserRole).toInt();
552             if (value == ix) return item;
553             pos++;
554         }
555     } else {
556         pos --;
557         while (pos >= 0) {
558             item = frame_list->item(pos);
559             value = item->data(Qt::UserRole).toInt();
560             if (value == ix) return item;
561             pos --;
562         }
563     }
564     return NULL;
565 }
566
567
568 void StopmotionWidget::selectFrame(int ix)
569 {
570     frame_list->blockSignals(true);
571     QListWidgetItem *item = getFrameFromIndex(ix);
572     if (!item) return;
573     frame_list->setCurrentItem(item);
574     frame_list->blockSignals(false);
575 }
576
577 void StopmotionWidget::slotSeekFrame(bool forward)
578 {
579     int ix = frame_list->currentRow();
580     if (forward) {
581         if (ix < frame_list->count() - 1) frame_list->setCurrentRow(ix + 1);
582     } else if (ix > 0) frame_list->setCurrentRow(ix - 1);
583 }
584
585 void StopmotionWidget::slotRemoveFrame()
586 {
587     if (frame_list->currentItem() == NULL) return;
588     QString path = frame_list->currentItem()->toolTip();
589     if (KMessageBox::questionYesNo(this, i18n("Delete frame %1 from disk?", path), i18n("Delete Frame")) != KMessageBox::Yes) return;
590     QFile f(path);
591     if (f.remove()) {
592         QListWidgetItem *item = frame_list->takeItem(frame_list->currentRow());
593         delete item;
594     }
595 }