]> git.sesse.net Git - kdenlive/blob - src/rotoscoping/rotowidget.cpp
Merge branch 'master' into next
[kdenlive] / src / rotoscoping / rotowidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2011 by Till Theato (root@ttill.de)                     *
3  *   This file is part of Kdenlive (www.kdenlive.org).                     *
4  *                                                                         *
5  *   Kdenlive is free software: you can redistribute it and/or modify      *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation, either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   Kdenlive is distributed in the hope that it will be useful,           *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with Kdenlive.  If not, see <http://www.gnu.org/licenses/>.     *
17  ***************************************************************************/
18
19 #include "rotowidget.h"
20 #include "monitor.h"
21 #include "renderer.h"
22 #include "monitorscene.h"
23 #include "monitoreditwidget.h"
24 #include "onmonitoritems/rotoscoping/bpointitem.h"
25 #include "onmonitoritems/rotoscoping/splineitem.h"
26 #include "simplekeyframes/simplekeyframewidget.h"
27 #include "kdenlivesettings.h"
28
29 #include <mlt++/Mlt.h>
30
31 #include <math.h>
32
33 #include <qjson/parser.h>
34 #include <qjson/serializer.h>
35
36 #include <QVBoxLayout>
37
38 /** @brief Listener for "tracking-finished" event in MLT rotoscoping filter. */
39 void tracking_finished(mlt_service *owner, RotoWidget *self, char *data)
40 {
41     Q_UNUSED(owner)
42
43     if (self)
44         self->setSpline(QString(data));
45 }
46
47 RotoWidget::RotoWidget(QString data, Monitor *monitor, ItemInfo info, Timecode t, QWidget* parent) :
48         QWidget(parent),
49         m_monitor(monitor),
50         m_showScene(true),
51         m_in(info.cropStart.frames(KdenliveSettings::project_fps())),
52         m_out((info.cropStart + info.cropDuration).frames(KdenliveSettings::project_fps()) - 1),
53         m_filter(NULL)
54 {
55     QVBoxLayout *l = new QVBoxLayout(this);
56     m_keyframeWidget = new SimpleKeyframeWidget(t, m_out - m_in, this);
57     l->addWidget(m_keyframeWidget);
58
59     MonitorEditWidget *edit = monitor->getEffectEdit();
60     edit->showVisibilityButton(true);
61     m_scene = edit->getScene();
62
63     m_item = new SplineItem(QList <BPoint>(), NULL, m_scene);
64
65     connect(m_item, SIGNAL(changed(bool)), this, SLOT(slotUpdateData(bool)));
66     connect(edit, SIGNAL(showEdit(bool)), this, SLOT(slotShowScene(bool)));
67     connect(m_monitor, SIGNAL(renderPosition(int)), this, SLOT(slotCheckMonitorPosition(int)));
68     connect(m_keyframeWidget, SIGNAL(positionChanged(int)), this, SLOT(slotPositionChanged(int)));
69     connect(m_keyframeWidget, SIGNAL(keyframeAdded(int)), this, SLOT(slotAddKeyframe(int)));
70     connect(m_keyframeWidget, SIGNAL(keyframeRemoved(int)), this, SLOT(slotRemoveKeyframe(int)));
71     connect(m_keyframeWidget, SIGNAL(keyframeMoved(int,int)), this, SLOT(slotMoveKeyframe(int,int)));
72     connect(m_scene, SIGNAL(addKeyframe()), this, SLOT(slotAddKeyframe()));
73
74     setSpline(data, false);
75     setupTrackingListen(info);
76 }
77
78 RotoWidget::~RotoWidget()
79 {
80     if (m_filter)
81         mlt_events_disconnect(m_filter->get_properties(), this);
82
83     delete m_keyframeWidget;
84
85     m_scene->removeItem(m_item);
86     delete m_item;
87
88     if (m_monitor) {
89         MonitorEditWidget *edit = m_monitor->getEffectEdit();
90         edit->showVisibilityButton(false);
91         edit->removeCustomControls();
92         m_monitor->slotEffectScene(false);
93     }
94 }
95
96 void RotoWidget::slotCheckMonitorPosition(int renderPos)
97 {
98     if (m_showScene)
99         emit checkMonitorPosition(renderPos);
100 }
101
102 void RotoWidget::slotSyncPosition(int relTimelinePos)
103 {
104     relTimelinePos = qBound(0, relTimelinePos, m_out);
105     m_keyframeWidget->slotSetPosition(relTimelinePos, false);
106     slotPositionChanged(relTimelinePos, false);
107 }
108
109 void RotoWidget::slotShowScene(bool show)
110 {
111     m_showScene = show;
112     if (!m_showScene)
113         m_monitor->slotEffectScene(false);
114     else
115         slotCheckMonitorPosition(m_monitor->render->seekFramePosition());
116 }
117
118 void RotoWidget::slotUpdateData(int pos, bool editing)
119 {
120     Q_UNUSED(editing)
121
122     int width = m_monitor->render->frameRenderWidth();
123     int height = m_monitor->render->renderHeight();
124
125     /*
126      * use the position of the on-monitor points to create a storable list
127      */
128     QList <BPoint> spline = m_item->getPoints();
129     QList <QVariant> vlist;
130     foreach (const BPoint &point, spline) {
131         QList <QVariant> pl;
132         for (int i = 0; i < 3; ++i)
133             pl << QVariant(QList <QVariant>() << QVariant(point[i].x() / width) << QVariant(point[i].y() / height));
134         vlist << QVariant(pl);
135     }
136
137     if (m_data.canConvert(QVariant::Map)) {
138         QMap <QString, QVariant> map = m_data.toMap();
139         // replace or insert at position
140         // we have to fill with 0s to maintain the correct order
141         map[QString::number((pos < 0 ? m_keyframeWidget->getPosition() : pos) + m_in).rightJustified(log10((double)m_out) + 1, '0')] = QVariant(vlist);
142         m_data = QVariant(map);
143     } else {
144         // timeline update is only required if the first keyframe did not exist yet
145         bool update = m_data.isNull();
146         m_data = QVariant(vlist);
147         if (update) {
148             keyframeTimelineFullUpdate();
149         }
150     }
151
152     emit valueChanged();
153 }
154
155 void RotoWidget::slotUpdateData(bool editing)
156 {
157     slotUpdateData(-1, editing);
158 }
159
160 QString RotoWidget::getSpline()
161 {
162     QJson::Serializer serializer;
163     return QString(serializer.serialize(m_data));
164 }
165
166 void RotoWidget::slotPositionChanged(int pos, bool seek)
167 {
168     // do not update while the spline is being edited (points are being dragged)
169     if (m_item->editing())
170         return;
171
172     m_keyframeWidget->slotSetPosition(pos, false);
173
174     pos += m_in;
175
176     QList <BPoint> p;
177
178     if (m_data.canConvert(QVariant::Map)) {
179         QMap <QString, QVariant> map = m_data.toMap();
180         QMap <QString, QVariant>::const_iterator i = map.constBegin();
181         int keyframe1, keyframe2;
182         keyframe1 = keyframe2 = i.key().toInt();
183         // find keyframes next to pos
184         while (i.key().toInt() < pos && ++i != map.constEnd()) {
185             keyframe1 = keyframe2;
186             keyframe2 = i.key().toInt();
187         }
188
189         if (keyframe1 != keyframe2 && pos < keyframe2) {
190             /*
191              * in between two keyframes
192              * -> interpolate
193              */
194             QList <BPoint> p1 = getPoints(keyframe1);
195             QList <BPoint> p2 = getPoints(keyframe2);
196             qreal relPos = (pos - keyframe1) / (qreal)(keyframe2 - keyframe1 + 1);
197
198             // additionaly points are ignored (same behavior as MLT filter)
199             int count = qMin(p1.count(), p2.count());
200             for (int i = 0; i < count; ++i) {
201                 BPoint bp;
202                 for (int j = 0; j < 3; ++j) {
203                     if (p1.at(i)[j] != p2.at(i)[j])
204                         bp[j] = QLineF(p1.at(i)[j], p2.at(i)[j]).pointAt(relPos);
205                     else
206                         bp[j] = p1.at(i)[j];
207                 }
208                 p.append(bp);
209             }
210
211             m_item->setPoints(p);
212             m_item->setEnabled(false);
213             m_scene->setEnabled(false);
214         } else {
215             p = getPoints(keyframe2);
216             // only update if necessary to preserve the current point selection
217             if (p != m_item->getPoints())
218                 m_item->setPoints(p);
219             m_item->setEnabled(pos == keyframe2);
220             m_scene->setEnabled(pos == keyframe2);
221         }
222     } else {
223         p = getPoints(-1);
224         // only update if necessary to preserve the current point selection
225         if (p != m_item->getPoints())
226             m_item->setPoints(p);
227         m_item->setEnabled(true);
228         m_scene->setEnabled(true);
229     }
230
231     if (seek)
232         emit seekToPos(pos - m_in);
233 }
234
235 QList <BPoint> RotoWidget::getPoints(int keyframe)
236 {
237     int width = m_monitor->render->frameRenderWidth();
238     int height = m_monitor->render->renderHeight();
239     QList <BPoint> points;
240     QList <QVariant> data;
241     if (keyframe >= 0)
242         data = m_data.toMap()[QString::number(keyframe).rightJustified(log10((double)m_out) + 1, '0')].toList();
243     else
244         data = m_data.toList();
245
246     // skip tracking flag
247     if (data.count() && data.at(0).canConvert(QVariant::String))
248         data.removeFirst();
249
250     foreach (const QVariant &bpoint, data) {
251         QList <QVariant> l = bpoint.toList();
252         BPoint p;
253         for (int i = 0; i < 3; ++i)
254             p[i] = QPointF(l.at(i).toList().at(0).toDouble() * width, l.at(i).toList().at(1).toDouble() * height);
255         points << p;
256     }
257     return points;
258 }
259
260 void RotoWidget::slotAddKeyframe(int pos)
261 {
262     if (!m_data.canConvert(QVariant::Map)) {
263         QVariant data = m_data;
264         QMap<QString, QVariant> map;
265         map[QString::number(m_in).rightJustified(log10((double)m_out) + 1, '0')] = data;
266         m_data = QVariant(map);
267     }
268
269     if (pos < 0)
270         m_keyframeWidget->addKeyframe();
271
272     slotUpdateData(pos);
273     m_item->setEnabled(true);
274     m_scene->setEnabled(true);
275 }
276
277 void RotoWidget::slotRemoveKeyframe(int pos)
278 {
279     if (pos < 0)
280         pos = m_keyframeWidget->getPosition();
281
282     if (!m_data.canConvert(QVariant::Map) || m_data.toMap().count() < 2)
283         return;
284
285     QMap<QString, QVariant> map = m_data.toMap();
286     map.remove(QString::number(pos + m_in).rightJustified(log10((double)m_out) + 1, '0'));
287     m_data = QVariant(map);
288
289     if (m_data.toMap().count() == 1) {
290         // only one keyframe -> switch from map to list again
291         m_data = m_data.toMap().begin().value();
292     }
293
294     slotPositionChanged(m_keyframeWidget->getPosition(), false);
295     emit valueChanged();
296 }
297
298 void RotoWidget::slotMoveKeyframe(int oldPos, int newPos)
299 {
300     if (m_data.canConvert(QVariant::Map)) {
301         QMap<QString, QVariant> map = m_data.toMap();
302         map[QString::number(newPos + m_in).rightJustified(log10((double)m_out) + 1, '0')] = map.take(QString::number(oldPos + m_in).rightJustified(log10((double)m_out) + 1, '0'));
303         m_data = QVariant(map);
304     }
305
306     slotPositionChanged(m_keyframeWidget->getPosition(), false);
307     emit valueChanged();
308 }
309
310 void RotoWidget::updateTimecodeFormat()
311 {
312     m_keyframeWidget->updateTimecodeFormat();
313 }
314
315 void RotoWidget::keyframeTimelineFullUpdate()
316 {
317     if (m_data.canConvert(QVariant::Map)) {
318         QList <int> keyframes;
319         QMap <QString, QVariant> map = m_data.toMap();
320         QMap <QString, QVariant>::const_iterator i = map.constBegin();
321         while (i != map.constEnd()) {
322             keyframes.append(i.key().toInt() - m_in);
323             ++i;
324         }
325         m_keyframeWidget->setKeyframes(keyframes);
326
327         /*for (int j = 0; j < keyframes.count(); ++j) {
328             // key might already be justified
329             if (map.contains(QString::number(keyframes.at(j) + m_in))) {
330                 QVariant value = map.take(QString::number(keyframes.at(j) + m_in));
331                 map[QString::number(keyframes.at(j) + m_in).rightJustified(log10((double)m_out) + 1, '0')] = value;
332             }
333         }
334         m_data = QVariant(map);*/
335     } else {
336         // static (only one keyframe)
337         // make sure the first keyframe was already created
338         if (m_data.isValid()) {
339             m_keyframeWidget->setKeyframes(QList <int>() << 0);
340         }
341     }
342 }
343
344 void RotoWidget::setupTrackingListen(ItemInfo info)
345 {
346     if (info.startPos < GenTime()) {
347         // TODO: track effects
348         return;
349     }
350
351     Mlt::Service service(m_monitor->render->getProducer()->parent().get_service());
352     Mlt::Tractor tractor(service);
353     Mlt::Producer trackProducer(tractor.track(tractor.count() - info.track - 1));
354     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
355
356     Mlt::Producer *clip = trackPlaylist.get_clip_at((int)info.startPos.frames(KdenliveSettings::project_fps()));
357     if (!clip) {
358         return;
359     }
360
361     int i = 0;
362     Mlt::Filter *filter = clip->filter(0);
363     while (filter) {
364         if (strcmp(filter->get("kdenlive_id"), "rotoscoping") == 0) {
365             m_filter = filter;
366             filter->listen("tracking-finished", this, (mlt_listener)tracking_finished);
367             break;
368         }
369         filter = clip->filter(++i);
370     }
371
372     delete clip;
373 }
374
375 void RotoWidget::setSpline(QString spline, bool notify)
376 {
377     QJson::Parser parser;
378     bool ok;
379     m_data = parser.parse(spline.simplified().toUtf8(), &ok);
380     if (!ok) {
381         // :(
382     }
383     keyframeTimelineFullUpdate();
384     slotPositionChanged(m_keyframeWidget->getPosition(), false);
385     if (notify)
386         emit valueChanged();
387 }
388
389
390 static QVariant interpolate(int position, int in, int out, QVariant *splineIn, QVariant *splineOut)
391 {
392     qreal relPos = (position - in) / (qreal)(out - in + 1);
393     QList<QVariant> keyframe1 = splineIn->toList();
394     QList<QVariant> keyframe2 = splineOut->toList();
395     QList<QVariant> keyframe;
396     if (keyframe1.count() && keyframe1.at(0).canConvert(QVariant::String))
397         keyframe1.removeFirst();
398     if (keyframe2.count() && keyframe2.at(0).canConvert(QVariant::String))
399         keyframe2.removeFirst();
400     int max = qMin(keyframe1.count(), keyframe2.count());
401         
402     for (int i = 0; i < max; ++i) {
403         QList<QVariant> p1 = keyframe1.at(i).toList();
404         QList<QVariant> p2 = keyframe2.at(i).toList();
405         QList<QVariant> p;
406         for (int j = 0; j < 3; ++j) {
407             QPointF middle = QLineF(QPointF(p1.at(j).toList().at(0).toDouble(), p1.at(j).toList().at(1).toDouble()),
408                                     QPointF(p2.at(j).toList().at(0).toDouble(), p2.at(j).toList().at(1).toDouble())).pointAt(relPos);
409             p.append(QVariant(QList<QVariant>() << QVariant(middle.x()) << QVariant(middle.y())));
410         }
411         keyframe.append(QVariant(p));
412     }
413     return QVariant(keyframe);
414 }
415
416 bool adjustRotoDuration(QString* data, int in, int out)
417 {
418     QJson::Parser parser;
419     bool ok;
420     QVariant splines = parser.parse(data->toUtf8(), &ok);
421     if (!ok) {
422         *data = QString();
423         return true;
424     }
425
426     if (!splines.canConvert(QVariant::Map))
427         return false;
428
429     QMap<QString, QVariant> newMap;
430     QMap<QString, QVariant> map = splines.toMap();
431     QMap<QString, QVariant>::iterator i = map.end();
432     int lastPos = -1;
433     QVariant last = QVariant();
434
435     /*
436      * Take care of resize from start
437      */
438     bool startFound = false;
439     while (i-- != map.begin()) {
440         if (!startFound && i.key().toInt() < in) {
441             startFound = true;
442             if (lastPos < 0)
443                 newMap[QString::number(in).rightJustified(log10((double)out) + 1, '0')] = i.value();
444             else
445                 newMap[QString::number(in).rightJustified(log10((double)out) + 1, '0')] = interpolate(in, i.key().toInt(), lastPos, &i.value(), &last);
446         }
447         lastPos = i.key().toInt();
448         last = i.value();
449         if (startFound)
450             i = map.erase(i);
451     }
452
453     /*
454      * Take care of resize from end
455      */
456     i = map.begin();
457     lastPos = -1;
458     bool endFound = false;
459     while (i != map.end()) {
460         if (!endFound && i.key().toInt() > out) {
461             endFound = true;
462             if (lastPos < 0)
463                 newMap[QString::number(out)] = i.value();
464             else
465                 newMap[QString::number(out)] = interpolate(out, lastPos, i.key().toInt(), &last, &i.value());
466         }
467         lastPos = i.key().toInt();
468         last = i.value();
469         if (endFound)
470             i = map.erase(i);
471         else
472             ++i;
473     }
474
475     /*
476      * Update key lengths to prevent sorting issues
477      */
478     i = map.begin();
479     while (i != map.end()) {
480         newMap[i.key().rightJustified(log10((double)out) + 1, '0', true)] = i.value();
481         ++i;
482     }
483
484     QJson::Serializer serializer;
485     *data = QString(serializer.serialize(QVariant(newMap)));
486
487     if (startFound || endFound)
488         return true;
489     return false;
490 }
491
492 #include "rotowidget.moc"