]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Fix clip effect stack not updated when dropping effect in a group, nicer timeline...
[kdenlive] / src / clipitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "clipitem.h"
22 #include "customtrackview.h"
23 #include "customtrackscene.h"
24 #include "renderer.h"
25 #include "docclipbase.h"
26 #include "transition.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "profilesdialog.h"
30 #ifdef USE_QJSON
31 #include "rotoscoping/rotowidget.h"
32 #endif
33
34 #include <KDebug>
35 #include <KIcon>
36
37 #include <QPainter>
38 #include <QTimer>
39 #include <QStyleOptionGraphicsItem>
40 #include <QGraphicsScene>
41 #include <QMimeData>
42
43 static int FRAME_SIZE;
44
45 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, double speed, int strobe, int frame_width, bool generateThumbs) :
46         AbstractClipItem(info, QRectF(), fps),
47         m_clip(clip),
48         m_startFade(0),
49         m_endFade(0),
50         m_audioOnly(false),
51         m_videoOnly(false),
52         m_startPix(QPixmap()),
53         m_endPix(QPixmap()),
54         m_hasThumbs(false),
55         m_selectedEffect(-1),
56         m_timeLine(0),
57         m_startThumbRequested(false),
58         m_endThumbRequested(false),
59         //m_hover(false),
60         m_speed(speed),
61         m_strobe(strobe),
62         m_framePixelWidth(0),
63         m_limitedKeyFrames(false),
64         m_isMainSelectedClip(false)
65 {
66     setZValue(2);
67     m_effectList = EffectsList(true);
68     FRAME_SIZE = frame_width;
69     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (double) itemHeight());
70     setPos(info.startPos.frames(fps), (double)(info.track * KdenliveSettings::trackheight()) + 1 + itemOffset());
71
72     // set speed independant info
73     if (m_speed <= 0 && m_speed > -1)
74         m_speed = -1.0;
75     m_speedIndependantInfo = m_info;
76     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
77     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
78
79     m_videoPix = KIcon("kdenlive-show-video").pixmap(QSize(16, 16));
80     m_audioPix = KIcon("kdenlive-show-audio").pixmap(QSize(16, 16));
81
82     if (m_speed == 1.0)
83         m_clipName = m_clip->name();
84     else
85         m_clipName = m_clip->name() + " - " + QString::number(m_speed * 100, 'f', 0) + '%';
86
87     m_producer = m_clip->getId();
88     m_clipType = m_clip->clipType();
89     //m_cropStart = info.cropStart;
90     m_maxDuration = m_clip->maxDuration();
91     setAcceptDrops(true);
92     m_audioThumbReady = m_clip->audioThumbCreated();
93     //setAcceptsHoverEvents(true);
94     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
95
96     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
97         m_baseColor = QColor(141, 166, 215);
98         if (!m_clip->isPlaceHolder()) {
99             m_hasThumbs = true;
100             m_startThumbTimer.setSingleShot(true);
101             connect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
102             m_endThumbTimer.setSingleShot(true);
103             connect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
104             connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
105             connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
106             if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
107         }
108
109     } else if (m_clipType == COLOR) {
110         QString colour = m_clip->getProperty("colour");
111         colour = colour.replace(0, 2, "#");
112         m_baseColor = QColor(colour.left(7));
113     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
114         m_baseColor = QColor(141, 166, 215);
115         if (m_clipType == TEXT) {
116             connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
117         }
118         //m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
119     } else if (m_clipType == AUDIO) {
120         m_baseColor = QColor(141, 215, 166);
121         connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
122     }
123 }
124
125
126 ClipItem::~ClipItem()
127 {
128     blockSignals(true);
129     m_endThumbTimer.stop();
130     m_startThumbTimer.stop();
131     if (scene()) scene()->removeItem(this);
132     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
133         //disconnect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
134         //disconnect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
135     }
136     delete m_timeLine;
137 }
138
139 ClipItem *ClipItem::clone(ItemInfo info) const
140 {
141     ClipItem *duplicate = new ClipItem(m_clip, info, m_fps, m_speed, m_strobe, FRAME_SIZE);
142     if (m_clipType == IMAGE || m_clipType == TEXT) duplicate->slotSetStartThumb(m_startPix);
143     else if (m_clipType != COLOR) {
144         if (info.cropStart == m_info.cropStart) duplicate->slotSetStartThumb(m_startPix);
145         if (info.cropStart + (info.endPos - info.startPos) == m_info.cropStart + m_info.cropDuration) {
146             duplicate->slotSetEndThumb(m_endPix);
147         }
148     }
149     //kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
150     duplicate->setEffectList(m_effectList);
151     duplicate->setVideoOnly(m_videoOnly);
152     duplicate->setAudioOnly(m_audioOnly);
153     duplicate->setFades(fadeIn(), fadeOut());
154     //duplicate->setSpeed(m_speed);
155     return duplicate;
156 }
157
158 void ClipItem::setEffectList(const EffectsList effectList)
159 {
160     m_effectList.clone(effectList);
161     m_effectNames = m_effectList.effectNames().join(" / ");
162     if (!m_effectList.isEmpty()) {
163         for (int i = 0; i < m_effectList.count(); i++) {
164             QDomElement effect = m_effectList.at(i);
165             QString effectId = effect.attribute("id");
166             // check if it is a fade effect
167             QDomNodeList params = effect.elementsByTagName("parameter");
168             int fade = 0;
169             for (int j = 0; j < params.count(); j++) {
170                 QDomElement e = params.item(j).toElement();
171                 if (!e.isNull()) {
172                     if (effectId == "fadein") {
173                         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
174                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
175                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
176                         } else {
177                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
178                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
179                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
180                         }
181                     } else if (effectId == "fade_from_black") {
182                         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
183                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
184                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
185                         } else {
186                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
187                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
188                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
189                         }
190                     } else if (effectId == "fadeout") {
191                         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
192                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
193                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
194                         } else {
195                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
196                             if (fadeout.attribute("name") == "out") fade += fadeout.attribute("value").toInt();
197                             else if (fadeout.attribute("name") == "in") fade -= fadeout.attribute("value").toInt();
198                         }
199                     } else if (effectId == "fade_to_black") {
200                         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
201                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
202                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
203                         } else {
204                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
205                             if (fadeout.attribute("name") == "out") fade += fadeout.attribute("value").toInt();
206                             else if (fadeout.attribute("name") == "in") fade -= fadeout.attribute("value").toInt();
207                         }
208                     }
209                 }
210             }
211             if (fade > 0)
212                 m_startFade = fade;
213             else if (fade < 0)
214                 m_endFade = -fade;
215         }
216         setSelectedEffect(0);
217     }
218 }
219
220 const EffectsList ClipItem::effectList() const
221 {
222     return m_effectList;
223 }
224
225 int ClipItem::selectedEffectIndex() const
226 {
227     return m_selectedEffect;
228 }
229
230 void ClipItem::initEffect(QDomElement effect, int diff, int offset)
231 {
232     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
233     // not be changed
234
235     if (effect.attribute("id") == "freeze" && diff > 0) {
236         EffectsList::setParameter(effect, "frame", QString::number(diff));
237     }
238
239     // Init parameter value & keyframes if required
240     QDomNodeList params = effect.elementsByTagName("parameter");
241     for (int i = 0; i < params.count(); i++) {
242         QDomElement e = params.item(i).toElement();
243
244         if (e.isNull())
245             continue;
246
247         // Check if this effect has a variable parameter
248         if (e.attribute("default").contains('%')) {
249             double evaluatedValue = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("default"));
250             e.setAttribute("default", evaluatedValue);
251             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
252                 e.setAttribute("value", evaluatedValue);
253             }
254         }
255
256         if (effect.attribute("id") == "crop") {
257             // default use_profile to 1 for clips with proxies to avoid problems when rendering
258             if (e.attribute("name") == "use_profile" && !(m_clip->getProperty("proxy").isEmpty() || m_clip->getProperty("proxy") == "-"))
259                 e.setAttribute("value", "1");
260         }
261
262         if (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") {
263             if (e.attribute("keyframes").isEmpty()) {
264                 // Effect has a keyframe type parameter, we need to set the values
265                 e.setAttribute("keyframes", QString::number(cropStart().frames(m_fps)) + ':' + e.attribute("default"));
266             }
267             else if (offset != 0) {
268                 // adjust keyframes to this clip
269                 QString adjusted = adjustKeyframes(e.attribute("keyframes"), offset - cropStart().frames(m_fps));
270                 e.setAttribute("keyframes", adjusted);
271             }
272         }
273
274         if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
275             // Effects with a geometry parameter need to sync in / out with parent clip
276             effect.setAttribute("in", QString::number(cropStart().frames(m_fps)));
277             effect.setAttribute("out", QString::number((cropStart() + cropDuration()).frames(m_fps) - 1));
278             effect.setAttribute("_sync_in_out", "1");
279         }
280     }
281     if (effect.attribute("tag") == "volume" || effect.attribute("tag") == "brightness") {
282         if (effect.attribute("id") == "fadeout" || effect.attribute("id") == "fade_to_black") {
283             int end = (cropDuration() + cropStart()).frames(m_fps) - 1;
284             int start = end;
285             if (effect.attribute("id") == "fadeout") {
286                 if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
287                     int effectDuration = EffectsList::parameter(effect, "out").toInt() - EffectsList::parameter(effect, "in").toInt();
288                     if (effectDuration > cropDuration().frames(m_fps)) {
289                         effectDuration = cropDuration().frames(m_fps) / 2;
290                     }
291                     start -= effectDuration;
292                 } else {
293                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
294                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
295                 }
296             } else if (effect.attribute("id") == "fade_to_black") {
297                 if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
298                     int effectDuration = EffectsList::parameter(effect, "out").toInt() - EffectsList::parameter(effect, "in").toInt();
299                     if (effectDuration > cropDuration().frames(m_fps)) {
300                         effectDuration = cropDuration().frames(m_fps) / 2;
301                     }
302                     start -= effectDuration;
303                 } else {
304                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
305                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
306                 }
307             }
308             EffectsList::setParameter(effect, "in", QString::number(start));
309             EffectsList::setParameter(effect, "out", QString::number(end));
310         } else if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fade_from_black") {
311             int start = cropStart().frames(m_fps);
312             int end = start;
313             if (effect.attribute("id") == "fadein") {
314                 if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
315                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
316                     if (offset != 0) effectDuration -= offset;
317                     if (effectDuration > cropDuration().frames(m_fps)) {
318                         effectDuration = cropDuration().frames(m_fps) / 2;
319                     }
320                     end += effectDuration;
321                 } else
322                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fade_from_black"), "out").toInt() - offset;
323             } else if (effect.attribute("id") == "fade_from_black") {
324                 if (m_effectList.hasEffect(QString(), "fadein") == -1) {
325                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
326                     if (offset != 0) effectDuration -= offset;
327                     if (effectDuration > cropDuration().frames(m_fps)) {
328                         effectDuration = cropDuration().frames(m_fps) / 2;
329                     }
330                     end += effectDuration;
331                 } else
332                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fadein"), "out").toInt() - offset;
333             }
334             EffectsList::setParameter(effect, "in", QString::number(start));
335             EffectsList::setParameter(effect, "out", QString::number(end));
336         }
337     }
338 }
339
340 const QString ClipItem::adjustKeyframes(QString keyframes, int offset)
341 {
342     QStringList result;
343     // Simple keyframes
344     const QStringList list = keyframes.split(';', QString::SkipEmptyParts);
345     foreach(const QString &keyframe, list) {
346         int pos = keyframe.section(':', 0, 0).toInt() - offset;
347         QString newKey = QString::number(pos) + ":" + keyframe.section(':', 1);
348         result.append(newKey);
349     }
350     return result.join(";");
351 }
352
353 bool ClipItem::checkKeyFrames()
354 {
355     bool clipEffectsModified = false;
356     QLocale locale;
357     // go through all effects this clip has
358     for (int ix = 0; ix < m_effectList.count(); ++ix) {
359         QStringList keyframeParams = keyframes(ix);
360         QStringList newKeyFrameParams;
361         bool effModified = false;
362
363         // go through all params which have keyframes
364         foreach(const QString &kfr, keyframeParams) {
365             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
366             QStringList newKeyFrames;
367             bool cutKeyFrame = false;
368             bool modified = false;
369             int lastPos = -1;
370             double lastValue = -1;
371             int start = cropStart().frames(m_fps);
372             int end = (cropStart() + cropDuration()).frames(m_fps);
373
374             // go through all keyframes for one param
375             foreach(const QString &str, keyframes) {
376                 int pos = str.section(':', 0, 0).toInt();
377                 double val = locale.toDouble(str.section(':', 1, 1));
378                 if (pos - start < 0) {
379                     // a keyframe is defined before the start of the clip
380                     cutKeyFrame = true;
381                 } else if (cutKeyFrame) {
382                     // create new keyframe at clip start, calculate interpolated value
383                     if (pos > start) {
384                         int diff = pos - lastPos;
385                         double ratio = (double)(start - lastPos) / diff;
386                         double newValue = lastValue + (val - lastValue) * ratio;
387                         newKeyFrames.append(QString::number(start) + ':' + locale.toString(newValue));
388                         modified = true;
389                     }
390                     cutKeyFrame = false;
391                 }
392                 if (!cutKeyFrame) {
393                     if (pos > end) {
394                         // create new keyframe at clip end, calculate interpolated value
395                         int diff = pos - lastPos;
396                         if (diff != 0) {
397                             double ratio = (double)(end - lastPos) / diff;
398                             double newValue = lastValue + (val - lastValue) * ratio;
399                             newKeyFrames.append(QString::number(end) + ':' + locale.toString(newValue));
400                             modified = true;
401                         }
402                         break;
403                     } else {
404                         newKeyFrames.append(QString::number(pos) + ':' + locale.toString(val));
405                     }
406                 }
407                 lastPos = pos;
408                 lastValue = val;
409             }
410
411             newKeyFrameParams.append(newKeyFrames.join(";"));
412             if (modified)
413                 effModified = true;
414         }
415
416         if (effModified) {
417             // update KeyFrames
418             setKeyframes(ix, newKeyFrameParams);
419             clipEffectsModified = true;
420         }
421     }
422     return clipEffectsModified;
423 }
424
425 void ClipItem::setKeyframes(const int ix, const QStringList keyframes)
426 {
427     QDomElement effect = m_effectList.at(ix);
428     if (effect.attribute("disable") == "1") return;
429     QLocale locale;
430     QDomNodeList params = effect.elementsByTagName("parameter");
431     int keyframeParams = 0;
432     for (int i = 0; i < params.count(); i++) {
433         QDomElement e = params.item(i).toElement();
434         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && e.attribute("intimeline") == "1") {
435             e.setAttribute("keyframes", keyframes.at(keyframeParams));
436             if (ix == m_selectedEffect && keyframeParams == 0) {
437                 m_keyframes.clear();
438                 m_visibleParam = i;
439                 double max = locale.toDouble(e.attribute("max"));
440                 double min = locale.toDouble(e.attribute("min"));
441                 m_keyframeFactor = 100.0 / (max - min);
442                 m_keyframeOffset = min;
443                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
444                 m_selectedKeyframe = 0;
445                 // parse keyframes
446                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
447                 foreach(const QString &str, keyframes) {
448                     int pos = str.section(':', 0, 0).toInt();
449                     double val = locale.toDouble(str.section(':', 1, 1));
450                     m_keyframes[pos] = val;
451                 }
452                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
453                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
454                 update();
455             }
456             ++keyframeParams;
457         }
458     }
459 }
460
461
462 void ClipItem::setSelectedEffect(const int ix)
463 {
464     m_selectedEffect = ix;
465     QLocale locale;
466     QDomElement effect = effectAtIndex(m_selectedEffect);
467     if (!effect.isNull() && effect.attribute("disable") != "1") {
468         QDomNodeList params = effect.elementsByTagName("parameter");
469         for (int i = 0; i < params.count(); i++) {
470             QDomElement e = params.item(i).toElement();
471             if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && e.attribute("intimeline") == "1") {
472                 m_keyframes.clear();
473                 m_limitedKeyFrames = e.attribute("type") == "keyframe";
474                 m_visibleParam = i;
475                 double max = locale.toDouble(e.attribute("max"));
476                 double min = locale.toDouble(e.attribute("min"));
477                 m_keyframeFactor = 100.0 / (max - min);
478                 m_keyframeOffset = min;
479                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
480                 m_selectedKeyframe = 0;
481
482                 // parse keyframes
483                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
484                 foreach(const QString &str, keyframes) {
485                     int pos = str.section(':', 0, 0).toInt();
486                     double val = locale.toDouble(str.section(':', 1, 1));
487                     m_keyframes[pos] = val;
488                 }
489                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end())
490                     m_editedKeyframe = -1;
491                 update();
492                 return;
493             }
494         }
495     }
496
497     if (!m_keyframes.isEmpty()) {
498         m_keyframes.clear();
499         update();
500     }
501 }
502
503 QStringList ClipItem::keyframes(const int index)
504 {
505     QStringList result;
506     QDomElement effect = m_effectList.at(index);
507     QDomNodeList params = effect.elementsByTagName("parameter");
508
509     for (int i = 0; i < params.count(); i++) {
510         QDomElement e = params.item(i).toElement();
511         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe"))
512             result.append(e.attribute("keyframes"));
513     }
514     return result;
515 }
516
517 void ClipItem::updateKeyframeEffect()
518 {
519     // regenerate xml parameter from the clip keyframes
520     QDomElement effect = getEffectAtIndex(m_selectedEffect);
521     if (effect.attribute("disable") == "1") return;
522     QDomNodeList params = effect.elementsByTagName("parameter");
523     QDomElement e = params.item(m_visibleParam).toElement();
524
525     if (!e.isNull()) {
526         QString keyframes;
527         if (m_keyframes.count() > 0) {
528             QMap<int, int>::const_iterator i = m_keyframes.constBegin();
529             while (i != m_keyframes.constEnd()) {
530                 keyframes.append(QString::number(i.key()) + ':' + QString::number(i.value()) + ';');
531                 ++i;
532             }
533         }
534         // Effect has a keyframe type parameter, we need to set the values
535         e.setAttribute("keyframes", keyframes);
536     }
537 }
538
539 QDomElement ClipItem::selectedEffect()
540 {
541     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
542     return effectAtIndex(m_selectedEffect);
543 }
544
545 void ClipItem::resetThumbs(bool clearExistingThumbs)
546 {
547     if (clearExistingThumbs) {
548         m_startPix = QPixmap();
549         m_endPix = QPixmap();
550         m_audioThumbCachePic.clear();
551     }
552     slotFetchThumbs();
553 }
554
555
556 void ClipItem::refreshClip(bool checkDuration, bool forceResetThumbs)
557 {
558     if (checkDuration && (m_maxDuration != m_clip->maxDuration())) {
559         m_maxDuration = m_clip->maxDuration();
560         if (m_clipType != IMAGE && m_clipType != TEXT && m_clipType != COLOR) {
561             if (m_maxDuration != GenTime() && m_info.cropStart + m_info.cropDuration > m_maxDuration) {
562                 // Clip duration changed, make sure to stay in correct range
563                 if (m_info.cropStart > m_maxDuration) {
564                     m_info.cropStart = GenTime();
565                     m_info.cropDuration = qMin(m_info.cropDuration, m_maxDuration);
566                 } else {
567                     m_info.cropDuration = m_maxDuration;
568                 }
569                 updateRectGeometry();
570             }
571         }
572     }
573     if (m_clipType == COLOR) {
574         QString colour = m_clip->getProperty("colour");
575         colour = colour.replace(0, 2, "#");
576         m_baseColor = QColor(colour.left(7));
577         update();
578     } else resetThumbs(forceResetThumbs);
579 }
580
581 void ClipItem::slotFetchThumbs()
582 {
583     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
584     if (m_clipType == IMAGE) {
585         if (m_startPix.isNull()) {
586             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
587             update();
588         }
589         return;
590     }
591
592     if (m_clipType == TEXT) {
593         if (m_startPix.isNull()) slotGetStartThumb();
594         return;
595     }
596
597     QList <int> frames;
598     if (m_startPix.isNull()) {
599         m_startThumbRequested = true;
600         frames.append((int)m_speedIndependantInfo.cropStart.frames(m_fps));
601     }
602
603     if (m_endPix.isNull()) {
604         m_endThumbRequested = true;
605         frames.append((int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
606     }
607
608     if (!frames.isEmpty()) m_clip->slotExtractImage(frames);
609 }
610
611 void ClipItem::stopThumbs()
612 {
613     // Clip is about to be deleted, make sure we don't request thumbnails
614     disconnect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
615     disconnect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
616 }
617
618 void ClipItem::slotGetStartThumb()
619 {
620     m_startThumbRequested = true;
621     m_clip->slotExtractImage(QList<int>() << (int)m_speedIndependantInfo.cropStart.frames(m_fps));
622 }
623
624 void ClipItem::slotGetEndThumb()
625 {
626     m_endThumbRequested = true;
627     m_clip->slotExtractImage(QList<int>() << (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
628 }
629
630
631 void ClipItem::slotSetStartThumb(QImage img)
632 {
633     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
634         QPixmap pix = QPixmap::fromImage(img);
635         m_startPix = pix;
636         QRectF r = sceneBoundingRect();
637         r.setRight(pix.width() + 2);
638         update(r);
639     }
640 }
641
642 void ClipItem::slotSetEndThumb(QImage img)
643 {
644     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
645         QPixmap pix = QPixmap::fromImage(img);
646         m_endPix = pix;
647         QRectF r = sceneBoundingRect();
648         r.setLeft(r.right() - pix.width() - 2);
649         update(r);
650     }
651 }
652
653 void ClipItem::slotThumbReady(int frame, QImage img)
654 {
655     if (scene() == NULL) return;
656     QRectF r = boundingRect();
657     QPixmap pix = QPixmap::fromImage(img);
658     double width = pix.width() / projectScene()->scale().x();
659     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
660         m_startPix = pix;
661         m_startThumbRequested = false;
662         update(r.left(), r.top(), width, pix.height());
663         if (m_clipType == IMAGE || m_clipType == TEXT) {
664             update(r.right() - width, r.top(), width, pix.height());
665         }
666     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
667         m_endPix = pix;
668         m_endThumbRequested = false;
669         update(r.right() - width, r.top(), width, pix.height());
670     }
671 }
672
673 void ClipItem::slotSetStartThumb(const QPixmap pix)
674 {
675     m_startPix = pix;
676 }
677
678 void ClipItem::slotSetEndThumb(const QPixmap pix)
679 {
680     m_endPix = pix;
681 }
682
683 QPixmap ClipItem::startThumb() const
684 {
685     return m_startPix;
686 }
687
688 QPixmap ClipItem::endThumb() const
689 {
690     return m_endPix;
691 }
692
693 void ClipItem::slotGotAudioData()
694 {
695     m_audioThumbReady = true;
696     if (m_clipType == AV && !isAudioOnly()) {
697         QRectF r = boundingRect();
698         r.setTop(r.top() + r.height() / 2 - 1);
699         update(r);
700     } else update();
701 }
702
703 int ClipItem::type() const
704 {
705     return AVWIDGET;
706 }
707
708 DocClipBase *ClipItem::baseClip() const
709 {
710     return m_clip;
711 }
712
713 QDomElement ClipItem::xml() const
714 {
715     return itemXml();
716 }
717
718 QDomElement ClipItem::itemXml() const
719 {
720     QDomElement xml = m_clip->toXML();
721     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
722     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
723     if (m_audioOnly) xml.setAttribute("audio_only", 1);
724     else if (m_videoOnly) xml.setAttribute("video_only", 1);
725     return xml;
726 }
727
728 int ClipItem::clipType() const
729 {
730     return m_clipType;
731 }
732
733 QString ClipItem::clipName() const
734 {
735     return m_clipName;
736 }
737
738 void ClipItem::setClipName(const QString &name)
739 {
740     m_clipName = name;
741 }
742
743 const QString ClipItem::clipProducer() const
744 {
745     return m_producer;
746 }
747
748 void ClipItem::flashClip()
749 {
750     if (m_timeLine == 0) {
751         m_timeLine = new QTimeLine(750, this);
752         m_timeLine->setUpdateInterval(80);
753         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
754         m_timeLine->setFrameRange(0, 100);
755         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
756     }
757     //m_timeLine->start();
758 }
759
760 void ClipItem::animate(qreal /*value*/)
761 {
762     QRectF r = boundingRect();
763     r.setHeight(20);
764     update(r);
765 }
766
767 // virtual
768 void ClipItem::paint(QPainter *painter,
769                      const QStyleOptionGraphicsItem *option,
770                      QWidget *)
771 {
772     QPalette palette = scene()->palette();
773     QColor paintColor;
774     QColor textColor;
775     QColor textBgColor;
776     QPen framePen;
777     if (parentItem()) paintColor = QColor(255, 248, 149);
778     else paintColor = m_baseColor;
779     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
780         textColor = palette.highlightedText().color();
781         textBgColor = palette.highlight().color();
782         paintColor = paintColor.darker();
783         framePen.setColor(textBgColor);
784     }
785     else {
786         textColor = palette.text().color();
787         textBgColor = palette.window().color();
788         textBgColor.setAlpha(200);
789         framePen.setColor(paintColor.darker());
790     }
791     const QRectF exposed = option->exposedRect;
792     const QRectF mappedExposed = painter->worldTransform().mapRect(exposed);
793     const QRectF mapped = painter->worldTransform().mapRect(rect());
794     painter->setWorldMatrixEnabled(false);
795     QPainterPath p;
796     p.addRect(mappedExposed);
797     QPainterPath q;
798     q.addRoundedRect(mapped.adjusted(0, 0, -0.5, 0), 3, 3);
799     painter->setClipPath(p.intersected(q));
800     painter->setPen(Qt::NoPen);
801     painter->fillRect(mappedExposed, paintColor);
802     painter->setPen(paintColor.darker());
803     // draw thumbnails
804     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
805         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
806             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
807             painter->drawPixmap(top, m_startPix);
808             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
809             painter->drawLine(l2);
810         } else if (!m_endPix.isNull()) {
811             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
812             painter->drawPixmap(top, m_endPix);
813             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
814             painter->drawLine(l2);
815         }
816         if (!m_startPix.isNull()) {
817             painter->drawPixmap(mapped.topLeft(), m_startPix);
818             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
819             painter->drawLine(l2);
820         }
821
822         // if we are in full zoom, paint thumbnail for every frame
823         if (m_clip->thumbProducer() && clipType() != COLOR && clipType() != AUDIO && !m_audioOnly && painter->worldTransform().m11() == FRAME_SIZE) {
824             int offset = (m_info.startPos - m_info.cropStart).frames(m_fps);
825             int left = qMax((int) m_info.cropStart.frames(m_fps) + 1, (int) mapToScene(exposed.left(), 0).x() - offset);
826             int right = qMin((int)(m_info.cropStart + m_info.cropDuration).frames(m_fps) - 1, (int) mapToScene(exposed.right(), 0).x() - offset);
827             QPointF startPos = mapped.topLeft();
828             int startOffset = m_info.cropStart.frames(m_fps);
829             if (clipType() == IMAGE || clipType() == TEXT) {
830                 for (int i = left; i <= right; i++) {
831                     painter->drawPixmap(startPos + QPointF(FRAME_SIZE *(i - startOffset), 0), m_startPix);
832                 }
833             }
834             else {
835 #if KDE_IS_VERSION(4,5,0)
836                 if (m_clip && m_clip->thumbProducer()) {
837                     QString path = m_clip->fileURL().path() + '_';
838                     QImage img;
839                     QPen pen(Qt::white);
840                     pen.setStyle(Qt::DotLine);
841                     QList <int> missing;
842                     for (int i = left; i <= right; i++) {
843                         img = m_clip->thumbProducer()->findCachedThumb(path + QString::number(i));
844                         QPointF xpos = startPos + QPointF(FRAME_SIZE *(i - startOffset), 0);
845                         if (img.isNull()) missing << i;
846                         else painter->drawImage(xpos, img);
847                         painter->drawLine(xpos, xpos + QPointF(0, mapped.height()));
848                     }
849                     if (!missing.isEmpty()) {
850                         m_clip->thumbProducer()->queryIntraThumbs(missing);
851                         connect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
852                     }
853                 }
854 #endif
855             }
856         }
857     }
858
859     // draw audio thumbnails
860     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
861
862         double startpixel = exposed.left();
863         if (startpixel < 0)
864             startpixel = 0;
865         double endpixel = exposed.right();
866         if (endpixel < 0)
867             endpixel = 0;
868         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
869
870         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
871         QRectF mappedRect;
872         if (m_clipType == AV && !isAudioOnly()) {
873             mappedRect = mapped;
874             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
875         } else mappedRect = mapped;
876
877         double scale = painter->worldTransform().m11();
878         int channels = 0;
879         if (isEnabled() && m_clip) channels = m_clip->getProperty("channels").toInt();
880         if (scale != m_framePixelWidth)
881             m_audioThumbCachePic.clear();
882         double cropLeft = m_info.cropStart.frames(m_fps);
883         const int clipStart = mappedRect.x();
884         const int mappedStartPixel =  painter->worldTransform().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
885         const int mappedEndPixel =  painter->worldTransform().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
886         cropLeft = cropLeft * scale;
887
888         if (channels >= 1) {
889             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
890         }
891
892         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
893             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
894                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
895         }
896     }
897
898     // only paint details if clip is big enough
899     if (mapped.width() > 20) {
900
901         // Draw effects names
902         if (!m_effectNames.isEmpty() && mapped.width() > 40) {
903             QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
904             QColor bColor = palette.window().color();
905             QColor tColor = palette.text().color();
906             tColor.setAlpha(220);
907             if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
908                 qreal value = m_timeLine->currentValue();
909                 txtBounding.setWidth(txtBounding.width() * value);
910                 bColor.setAlpha(100 + 50 * value);
911             };
912
913             painter->setBrush(bColor);
914             painter->setPen(Qt::NoPen);
915             painter->drawRoundedRect(txtBounding.adjusted(-1, -2, 4, -1), 3, 3);
916             painter->setPen(tColor);
917             painter->drawText(txtBounding.adjusted(2, 0, 1, -1), Qt::AlignCenter, m_effectNames);
918         }
919
920         // Draw clip name
921         const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignRight | Qt::AlignTop, m_clipName + ' ').adjusted(0, -1, 0, -1);
922         painter->setPen(Qt::NoPen);
923         if (m_isMainSelectedClip) {
924             framePen.setColor(Qt::red);
925             textBgColor = Qt::red;
926         }
927         painter->fillRect(txtBounding2.adjusted(-3, 0, 0, 0), textBgColor);
928         painter->setBrush(QBrush(Qt::NoBrush));
929         painter->setPen(textColor);
930         if (m_videoOnly) {
931             painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
932         } else if (m_audioOnly) {
933             painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
934         }
935         painter->drawText(txtBounding2, Qt::AlignLeft, m_clipName);
936
937
938         // draw markers
939         if (isEnabled() && m_clip) {
940             QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
941             QList < CommentedTime >::Iterator it = markers.begin();
942             GenTime pos;
943             double framepos;
944             QBrush markerBrush(QColor(120, 120, 0, 140));
945             QPen pen = painter->pen();
946             pen.setColor(QColor(255, 255, 255, 200));
947             pen.setStyle(Qt::DotLine);
948
949             for (; it != markers.end(); ++it) {
950                 pos = GenTime((int)((*it).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
951                 if (pos > GenTime()) {
952                     if (pos > cropDuration()) break;
953                     QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
954                     QLineF l2 = painter->worldTransform().map(l);
955                     painter->setPen(pen);
956                     painter->drawLine(l2);
957                     if (KdenliveSettings::showmarkers()) {
958                         framepos = rect().x() + pos.frames(m_fps);
959                         const QRectF r1(framepos + 0.04, rect().height()/3, rect().width() - framepos - 2, rect().height() / 2);
960                         const QRectF r2 = painter->worldTransform().mapRect(r1);
961                         const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
962                         painter->setBrush(markerBrush);
963                         painter->setPen(Qt::NoPen);
964                         painter->drawRoundedRect(txtBounding3, 3, 3);
965                         painter->setBrush(QBrush(Qt::NoBrush));
966                         painter->setPen(Qt::white);
967                         painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
968                     }
969                     //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
970                 }
971             }
972         }
973
974         // draw start / end fades
975         QBrush fades;
976         if (isSelected()) {
977             fades = QBrush(QColor(200, 50, 50, 150));
978         } else fades = QBrush(QColor(200, 200, 200, 200));
979
980         if (m_startFade != 0) {
981             QPainterPath fadeInPath;
982             fadeInPath.moveTo(0, 0);
983             fadeInPath.lineTo(0, rect().height());
984             fadeInPath.lineTo(m_startFade, 0);
985             fadeInPath.closeSubpath();
986             QPainterPath f1 = painter->worldTransform().map(fadeInPath);
987             painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
988             /*if (isSelected()) {
989                 QLineF l(m_startFade * scale, 0, 0, itemHeight);
990                 painter->drawLine(l);
991             }*/
992         }
993         if (m_endFade != 0) {
994             QPainterPath fadeOutPath;
995             fadeOutPath.moveTo(rect().width(), 0);
996             fadeOutPath.lineTo(rect().width(), rect().height());
997             fadeOutPath.lineTo(rect().width() - m_endFade, 0);
998             fadeOutPath.closeSubpath();
999             QPainterPath f1 = painter->worldTransform().map(fadeOutPath);
1000             painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
1001             /*if (isSelected()) {
1002                 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
1003                 painter->drawLine(l);
1004             }*/
1005         }
1006
1007
1008         painter->setPen(QPen(Qt::lightGray));
1009         // draw effect or transition keyframes
1010         drawKeyFrames(painter, m_limitedKeyFrames);
1011     }
1012     
1013     // draw clip border
1014     // expand clip rect to allow correct painting of clip border
1015     painter->setClipping(false);
1016     painter->setRenderHint(QPainter::Antialiasing, true);
1017     framePen.setWidthF(1.5);
1018     painter->setPen(framePen);
1019     painter->drawRoundedRect(mapped.adjusted(0, 0, -0.5, -0.5), 3, 3);
1020 }
1021
1022
1023 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
1024 {
1025     if (isItemLocked()) return NONE;
1026     const double scale = projectScene()->scale().x();
1027     double maximumOffset = 6 / scale;
1028     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
1029         int kf = mouseOverKeyFrames(pos, maximumOffset);
1030         if (kf != -1) {
1031             m_editedKeyframe = kf;
1032             return KEYFRAME;
1033         }
1034     }
1035     QRectF rect = sceneBoundingRect();
1036     int addtransitionOffset = 10;
1037     // Don't allow add transition if track height is very small. No transitions for audio only clips
1038     if (rect.height() < 30 || isAudioOnly() || m_clipType == AUDIO) addtransitionOffset = 0;
1039
1040     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
1041         return FADEIN;
1042     } else if ((pos.x() <= rect.x() + rect.width() / 2) && pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
1043         return RESIZESTART;
1044     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
1045         return FADEOUT;
1046     } else if ((pos.x() >= rect.x() + rect.width() / 2) && (rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
1047         return RESIZEEND;
1048     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
1049         return TRANSITIONSTART;
1050     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
1051         return TRANSITIONEND;
1052     }
1053
1054     return MOVE;
1055 }
1056
1057 int ClipItem::itemHeight()
1058 {
1059     return KdenliveSettings::trackheight() - 2;
1060 }
1061
1062 void ClipItem::resetFrameWidth(int width)
1063 {
1064     FRAME_SIZE = width;
1065     update();
1066 }
1067
1068 QList <GenTime> ClipItem::snapMarkers() const
1069 {
1070     QList < GenTime > snaps;
1071     if (!m_clip) return snaps;
1072     QList < GenTime > markers = m_clip->snapMarkers();
1073     GenTime pos;
1074
1075     for (int i = 0; i < markers.size(); i++) {
1076         pos = GenTime((int)(markers.at(i).frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1077         if (pos > GenTime()) {
1078             if (pos > cropDuration()) break;
1079             else snaps.append(pos + startPos());
1080         }
1081     }
1082     return snaps;
1083 }
1084
1085 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
1086 {
1087     QList < CommentedTime > snaps;
1088     if (!m_clip) return snaps;
1089     QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
1090     GenTime pos;
1091
1092     for (int i = 0; i < markers.size(); i++) {
1093         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1094         if (pos > GenTime()) {
1095             if (pos > cropDuration()) break;
1096             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
1097         }
1098     }
1099     return snaps;
1100 }
1101
1102 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
1103 {
1104     QRectF re =  sceneBoundingRect();
1105     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
1106
1107     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
1108     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
1109
1110     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
1111         //kDebug() << "creating " << startCache;
1112         //if (framePixelWidth!=pixelForOneFrame  ||
1113         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
1114             continue;
1115         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
1116             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
1117             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
1118         }
1119         bool fullAreaDraw = pixelForOneFrame < 10;
1120         QMap<int, QPainterPath > positiveChannelPaths;
1121         QMap<int, QPainterPath > negativeChannelPaths;
1122         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
1123         QPen audiopen;
1124         audiopen.setWidth(0);
1125         pixpainter.setPen(audiopen);
1126         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
1127         //pixpainter.drawLine(0,0,100,re.height());
1128         // Bail out, if caller provided invalid data
1129         if (channels <= 0) {
1130             kWarning() << "Unable to draw image with " << channels << "number of channels";
1131             return;
1132         }
1133
1134         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
1135
1136         for (int i = 0; i < channels; i++) {
1137
1138             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1139             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1140         }
1141
1142         for (int samples = 0; samples <= 100; samples++) {
1143             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
1144             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
1145             if (frame < 0 || sample < 0 || sample > 19)
1146                 continue;
1147             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
1148
1149             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
1150
1151                 int y = channelHeight * channel + channelHeight / 2;
1152                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
1153                 if (fullAreaDraw) {
1154                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
1155                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
1156                 } else {
1157                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
1158                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
1159                 }
1160             }
1161             for (int channel = 0; channel < channels ; channel++)
1162                 if (fullAreaDraw && samples == 100) {
1163                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1164                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1165                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1166                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1167                 }
1168
1169         }
1170         pixpainter.setPen(QPen(QColor(0, 0, 0)));
1171         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
1172
1173         for (int i = 0; i < channels; i++) {
1174             if (fullAreaDraw) {
1175                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
1176                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
1177             } else
1178                 pixpainter.drawPath(positiveChannelPaths[i]);
1179         }
1180     }
1181     //audioThumbWasDrawn=true;
1182     m_framePixelWidth = pixelForOneFrame;
1183
1184     //}
1185 }
1186
1187 int ClipItem::fadeIn() const
1188 {
1189     return m_startFade;
1190 }
1191
1192 int ClipItem::fadeOut() const
1193 {
1194     return m_endFade;
1195 }
1196
1197
1198 void ClipItem::setFadeIn(int pos)
1199 {
1200     if (pos == m_startFade) return;
1201     int oldIn = m_startFade;
1202     m_startFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1203     QRectF rect = boundingRect();
1204     update(rect.x(), rect.y(), qMax(oldIn, m_startFade), rect.height());
1205 }
1206
1207 void ClipItem::setFadeOut(int pos)
1208 {
1209     if (pos == m_endFade) return;
1210     int oldOut = m_endFade;
1211     m_endFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1212     QRectF rect = boundingRect();
1213     update(rect.x() + rect.width() - qMax(oldOut, m_endFade), rect.y(), qMax(oldOut, m_endFade), rect.height());
1214
1215 }
1216
1217 void ClipItem::setFades(int in, int out)
1218 {
1219     m_startFade = in;
1220     m_endFade = out;
1221 }
1222
1223 /*
1224 //virtual
1225 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1226 {
1227     //if (e->pos().x() < 20) m_hover = true;
1228     return;
1229     if (isItemLocked()) return;
1230     m_hover = true;
1231     QRectF r = boundingRect();
1232     double width = 35 / projectScene()->scale().x();
1233     double height = r.height() / 2;
1234     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1235     update(r.x(), r.y() + height, width, height);
1236     update(r.right() - width, r.y() + height, width, height);
1237 }
1238
1239 //virtual
1240 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1241 {
1242     if (isItemLocked()) return;
1243     m_hover = false;
1244     QRectF r = boundingRect();
1245     double width = 35 / projectScene()->scale().x();
1246     double height = r.height() / 2;
1247     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1248     update(r.x(), r.y() + height, width, height);
1249     update(r.right() - width, r.y() + height, width, height);
1250 }
1251 */
1252
1253 void ClipItem::resizeStart(int posx, bool /*size*/)
1254 {
1255     bool sizeLimit = false;
1256     if (clipType() != IMAGE && clipType() != COLOR && clipType() != TEXT) {
1257         const int min = (startPos() - cropStart()).frames(m_fps);
1258         if (posx < min) posx = min;
1259         sizeLimit = true;
1260     }
1261
1262     if (posx == startPos().frames(m_fps)) return;
1263     const int previous = cropStart().frames(m_fps);
1264     AbstractClipItem::resizeStart(posx, sizeLimit);
1265
1266     // set speed independant info
1267     m_speedIndependantInfo = m_info;
1268     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1269     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1270
1271     if ((int) cropStart().frames(m_fps) != previous) {
1272         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1273             m_startThumbTimer.start(150);
1274         }
1275     }
1276 }
1277
1278 void ClipItem::resizeEnd(int posx)
1279 {
1280     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1281     if (posx > max && maxDuration() != GenTime()) posx = max;
1282     if (posx == endPos().frames(m_fps)) return;
1283     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1284     const int previous = cropDuration().frames(m_fps);
1285     AbstractClipItem::resizeEnd(posx);
1286
1287     // set speed independant info
1288     m_speedIndependantInfo = m_info;
1289     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1290     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1291
1292     if ((int) cropDuration().frames(m_fps) != previous) {
1293         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1294             m_endThumbTimer.start(150);
1295         }
1296     }
1297 }
1298
1299 //virtual
1300 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1301 {
1302     if (change == QGraphicsItem::ItemSelectedChange) {
1303         if (value.toBool()) setZValue(10);
1304         else setZValue(2);
1305     }
1306     if (change == ItemPositionChange && scene()) {
1307         // calculate new position.
1308         //if (parentItem()) return pos();
1309         QPointF newPos = value.toPointF();
1310         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1311         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1312         xpos = qMax(xpos, 0);
1313         newPos.setX(xpos);
1314         // Warning: newPos gives a position relative to the click event, so hack to get absolute pos
1315         int yOffset = property("y_absolute").toInt() + newPos.y();
1316         int newTrack = yOffset / KdenliveSettings::trackheight();
1317         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1318         newTrack = qMax(newTrack, 0);
1319         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1320         // Only one clip is moving
1321         QRectF sceneShape = rect();
1322         sceneShape.translate(newPos);
1323         QList<QGraphicsItem*> items;
1324         if (projectScene()->editMode() == NORMALEDIT)
1325             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1326         items.removeAll(this);
1327         bool forwardMove = newPos.x() > pos().x();
1328         int offset = 0;
1329         if (!items.isEmpty()) {
1330             for (int i = 0; i < items.count(); i++) {
1331                 if (!items.at(i)->isEnabled()) continue;
1332                 if (items.at(i)->type() == type()) {
1333                     // Collision!
1334                     QPointF otherPos = items.at(i)->pos();
1335                     if ((int) otherPos.y() != (int) pos().y()) {
1336                         return pos();
1337                     }
1338                     if (forwardMove) {
1339                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1340                     } else {
1341                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1342                     }
1343
1344                     if (offset > 0) {
1345                         if (forwardMove) {
1346                             sceneShape.translate(QPointF(-offset, 0));
1347                             newPos.setX(newPos.x() - offset);
1348                         } else {
1349                             sceneShape.translate(QPointF(offset, 0));
1350                             newPos.setX(newPos.x() + offset);
1351                         }
1352                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1353                         subitems.removeAll(this);
1354                         for (int j = 0; j < subitems.count(); j++) {
1355                             if (!subitems.at(j)->isEnabled()) continue;
1356                             if (subitems.at(j)->type() == type()) {
1357                                 // move was not successful, revert to previous pos
1358                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1359                                 return pos();
1360                             }
1361                         }
1362                     }
1363
1364                     m_info.track = newTrack;
1365                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1366
1367                     return newPos;
1368                 }
1369             }
1370         }
1371         m_info.track = newTrack;
1372         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1373         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1374         return newPos;
1375     }
1376     return QGraphicsItem::itemChange(change, value);
1377 }
1378
1379 // virtual
1380 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1381 }*/
1382
1383 int ClipItem::effectsCounter()
1384 {
1385     return effectsCount() + 1;
1386 }
1387
1388 int ClipItem::effectsCount()
1389 {
1390     return m_effectList.count();
1391 }
1392
1393 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1394 {
1395     return m_effectList.hasEffect(tag, id);
1396 }
1397
1398 QStringList ClipItem::effectNames()
1399 {
1400     return m_effectList.effectNames();
1401 }
1402
1403 QDomElement ClipItem::effect(int ix) const
1404 {
1405     if (ix >= m_effectList.count() || ix < 0) return QDomElement();
1406     return m_effectList.at(ix).cloneNode().toElement();
1407 }
1408
1409 QDomElement ClipItem::effectAtIndex(int ix) const
1410 {
1411     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1412     return m_effectList.itemFromIndex(ix).cloneNode().toElement();
1413 }
1414
1415 QDomElement ClipItem::getEffectAtIndex(int ix) const
1416 {
1417     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1418     return m_effectList.itemFromIndex(ix);
1419 }
1420
1421 void ClipItem::updateEffect(QDomElement effect)
1422 {
1423     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1424     m_effectList.updateEffect(effect);
1425     m_effectNames = m_effectList.effectNames().join(" / ");
1426     QString id = effect.attribute("id");
1427     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1428         update();
1429     else {
1430         QRectF r = boundingRect();
1431         r.setHeight(20);
1432         update(r);
1433     }
1434 }
1435
1436 void ClipItem::enableEffects(QList <int> indexes, bool disable)
1437 {
1438     m_effectList.enableEffects(indexes, disable);
1439 }
1440
1441 bool ClipItem::moveEffect(QDomElement effect, int ix)
1442 {
1443     if (ix <= 0 || ix > (m_effectList.count()) || effect.isNull()) {
1444         kDebug() << "Invalid effect index: " << ix;
1445         return false;
1446     }
1447     m_effectList.removeAt(effect.attribute("kdenlive_ix").toInt());
1448     effect.setAttribute("kdenlive_ix", ix);
1449     m_effectList.insert(effect);
1450     m_effectNames = m_effectList.effectNames().join(" / ");
1451     QString id = effect.attribute("id");
1452     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1453         update();
1454     else {
1455         QRectF r = boundingRect();
1456         r.setHeight(20);
1457         update(r);
1458     }
1459     return true;
1460 }
1461
1462 EffectsParameterList ClipItem::addEffect(QDomElement effect, bool /*animate*/)
1463 {
1464     bool needRepaint = false;
1465     QLocale locale;
1466     int ix;
1467     QDomElement insertedEffect;
1468     if (!effect.hasAttribute("kdenlive_ix")) {
1469         // effect dropped from effect list
1470         ix = effectsCounter();
1471     } else ix = effect.attribute("kdenlive_ix").toInt();
1472     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1473         needRepaint = true;
1474         insertedEffect = m_effectList.insert(effect);
1475     } else insertedEffect = m_effectList.append(effect);
1476     
1477     // Update index to the real one
1478     effect.setAttribute("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1479     int effectIn;
1480     int effectOut;
1481
1482     if (effect.attribute("tag") == "affine") {
1483         // special case: the affine effect needs in / out points
1484         effectIn = effect.attribute("in").toInt();
1485         effectOut = effect.attribute("out").toInt();
1486     }
1487     else {
1488         effectIn = EffectsList::parameter(effect, "in").toInt();
1489         effectOut = EffectsList::parameter(effect, "out").toInt();
1490     }
1491     
1492     EffectsParameterList parameters;
1493     parameters.addParam("tag", insertedEffect.attribute("tag"));
1494     parameters.addParam("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1495     if (insertedEffect.hasAttribute("src")) parameters.addParam("src", insertedEffect.attribute("src"));
1496     if (insertedEffect.hasAttribute("disable")) parameters.addParam("disable", insertedEffect.attribute("disable"));
1497
1498     QString effectId = insertedEffect.attribute("id");
1499     if (effectId.isEmpty()) effectId = insertedEffect.attribute("tag");
1500     parameters.addParam("id", effectId);
1501
1502     QDomNodeList params = insertedEffect.elementsByTagName("parameter");
1503     int fade = 0;
1504     bool needInOutSync = false;
1505
1506     // check if it is a fade effect
1507     if (effectId == "fadein") {
1508         needRepaint = true;
1509         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1510             fade = effectOut - effectIn;
1511         }/* else {
1512             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1513             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1514             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1515         }*/
1516     } else if (effectId == "fade_from_black") {
1517         kDebug()<<"// FOUND FTB:"<<effectOut<<" - "<<effectIn;
1518         needRepaint = true;
1519         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1520             fade = effectOut - effectIn;
1521         }/* else {
1522             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1523             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1524             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1525         }*/
1526      } else if (effectId == "fadeout") {
1527         needRepaint = true;
1528         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1529             fade = effectIn - effectOut;
1530         } /*else {
1531             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1532             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1533             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1534         }*/
1535     } else if (effectId == "fade_to_black") {
1536         needRepaint = true;
1537         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1538             fade = effectIn - effectOut;
1539         }/* else {
1540             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1541             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1542             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1543         }*/
1544     }
1545
1546     for (int i = 0; i < params.count(); i++) {
1547         QDomElement e = params.item(i).toElement();
1548         if (!e.isNull()) {
1549             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1550                 // Effects with a geometry parameter need to sync in / out with parent clip
1551                 needInOutSync = true;
1552             }
1553             if (e.attribute("type") == "simplekeyframe") {
1554                 QStringList values = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1555                 double factor = locale.toDouble(e.attribute("factor", "1"));
1556                 double offset = e.attribute("offset", "0").toDouble();
1557                 if (factor != 1 || offset != 0) {
1558                     for (int j = 0; j < values.count(); j++) {
1559                         QString pos = values.at(j).section(':', 0, 0);
1560                         double val = (locale.toDouble(values.at(j).section(':', 1, 1)) - offset) / factor;
1561                         values[j] = pos + '=' + locale.toString(val);
1562                     }
1563                 }
1564                 parameters.addParam(e.attribute("name"), values.join(";"));
1565                 /*parameters.addParam("max", e.attribute("max"));
1566                 parameters.addParam("min", e.attribute("min"));
1567                 parameters.addParam("factor", );*/
1568             } else if (e.attribute("type") == "keyframe") {
1569                 parameters.addParam("keyframes", e.attribute("keyframes"));
1570                 parameters.addParam("max", e.attribute("max"));
1571                 parameters.addParam("min", e.attribute("min"));
1572                 parameters.addParam("factor", e.attribute("factor", "1"));
1573                 parameters.addParam("offset", e.attribute("offset", "0"));
1574                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1575                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1576             } else if (e.attribute("factor", "1") == "1" && e.attribute("offset", "0") == "0") {
1577                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1578
1579             } else {
1580                 double fact;
1581                 if (e.attribute("factor").contains('%')) {
1582                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1583                 } else {
1584                     fact = locale.toDouble(e.attribute("factor", "1"));
1585                 }
1586                 double offset = e.attribute("offset", "0").toDouble();
1587                 parameters.addParam(e.attribute("name"), locale.toString((locale.toDouble(e.attribute("value")) - offset) / fact));
1588             }
1589         }
1590     }
1591     if (needInOutSync) {
1592         parameters.addParam("in", QString::number(cropStart().frames(m_fps)));
1593         parameters.addParam("out", QString::number((cropStart() + cropDuration()).frames(m_fps) - 1));
1594         parameters.addParam("_sync_in_out", "1");
1595     }
1596     m_effectNames = m_effectList.effectNames().join(" / ");
1597     if (fade > 0) m_startFade = fade;
1598     else if (fade < 0) m_endFade = -fade;
1599
1600     if (m_selectedEffect == -1) {
1601         setSelectedEffect(0);
1602     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1603     if (needRepaint) update(boundingRect());
1604     /*if (animate) {
1605         flashClip();
1606     } */
1607     else { /*if (!needRepaint) */
1608         QRectF r = boundingRect();
1609         r.setHeight(20);
1610         update(r);
1611     }
1612     return parameters;
1613 }
1614
1615 void ClipItem::deleteEffect(QString index)
1616 {
1617     bool needRepaint = false;
1618     int ix = index.toInt();
1619
1620     QDomElement effect = m_effectList.itemFromIndex(ix);
1621     QString effectId = effect.attribute("id");
1622     if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1623         (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1624         m_startFade = 0;
1625         needRepaint = true;
1626     } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1627         (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1628         m_endFade = 0;
1629         needRepaint = true;
1630     } else if (EffectsList::hasKeyFrames(effect)) needRepaint = true;
1631     m_effectList.removeAt(ix);
1632     m_effectNames = m_effectList.effectNames().join(" / ");
1633
1634     if (m_effectList.isEmpty() || m_selectedEffect == ix) {
1635         // Current effect was removed
1636         if (ix > m_effectList.count()) {
1637             setSelectedEffect(m_effectList.count());
1638         } else setSelectedEffect(ix);
1639     }
1640     if (needRepaint) update(boundingRect());
1641     else {
1642         QRectF r = boundingRect();
1643         r.setHeight(20);
1644         update(r);
1645     }
1646     //if (!m_effectList.isEmpty()) flashClip();
1647 }
1648
1649 double ClipItem::speed() const
1650 {
1651     return m_speed;
1652 }
1653
1654 int ClipItem::strobe() const
1655 {
1656     return m_strobe;
1657 }
1658
1659 void ClipItem::setSpeed(const double speed, const int strobe)
1660 {
1661     m_speed = speed;
1662     if (m_speed <= 0 && m_speed > -1)
1663         m_speed = -1.0;
1664     m_strobe = strobe;
1665     if (m_speed == 1.0) m_clipName = m_clip->name();
1666     else m_clipName = m_clip->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1667     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1668     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1669     //update();
1670 }
1671
1672 GenTime ClipItem::maxDuration() const
1673 {
1674     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1675 }
1676
1677 GenTime ClipItem::speedIndependantCropStart() const
1678 {
1679     return m_speedIndependantInfo.cropStart;
1680 }
1681
1682 GenTime ClipItem::speedIndependantCropDuration() const
1683 {
1684     return m_speedIndependantInfo.cropDuration;
1685 }
1686
1687
1688 const ItemInfo ClipItem::speedIndependantInfo() const
1689 {
1690     return m_speedIndependantInfo;
1691 }
1692
1693 int ClipItem::nextFreeEffectGroupIndex() const
1694 {
1695     int freeGroupIndex = 0;
1696     for (int i = 0; i < m_effectList.count(); i++) {
1697         QDomElement effect = m_effectList.at(i);
1698         EffectInfo effectInfo;
1699         effectInfo.fromString(effect.attribute("kdenlive_info"));
1700         if (effectInfo.groupIndex >= freeGroupIndex) {
1701             freeGroupIndex = effectInfo.groupIndex + 1;
1702         }
1703     }
1704     return freeGroupIndex;
1705 }
1706
1707 //virtual
1708 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1709 {
1710     if (event->proposedAction() == Qt::CopyAction && scene() && !scene()->views().isEmpty()) {
1711         const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
1712         event->acceptProposedAction();
1713         QDomDocument doc;
1714         doc.setContent(effects, true);
1715         QDomElement e = doc.documentElement();
1716         if (e.tagName() == "effectgroup") {
1717             // dropped an effect group
1718             QDomNodeList effectlist = e.elementsByTagName("effect");
1719             int freeGroupIndex = nextFreeEffectGroupIndex();
1720             EffectInfo effectInfo;
1721             for (int i = 0; i < effectlist.count(); i++) {
1722                 QDomElement effect = effectlist.at(i).toElement();
1723                 effectInfo.fromString(effect.attribute("kdenlive_info"));
1724                 effectInfo.groupIndex = freeGroupIndex;
1725                 effect.setAttribute("kdenlive_info", effectInfo.toString());
1726                 effect.removeAttribute("kdenlive_ix");
1727             }
1728         } else {
1729             // single effect dropped
1730             e.removeAttribute("kdenlive_ix");
1731         }
1732         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1733         if (view) view->slotAddEffect(e, m_info.startPos, track());
1734     }
1735     else return;
1736 }
1737
1738 //virtual
1739 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1740 {
1741     if (isItemLocked()) event->setAccepted(false);
1742     else if (event->mimeData()->hasFormat("kdenlive/effectslist")) {
1743         event->acceptProposedAction();
1744     } else event->setAccepted(false);
1745 }
1746
1747 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1748 {
1749     Q_UNUSED(event)
1750 }
1751
1752 void ClipItem::addTransition(Transition* t)
1753 {
1754     m_transitionsList.append(t);
1755     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1756     QDomDocument doc;
1757     QDomElement e = doc.documentElement();
1758     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1759 }
1760
1761 void ClipItem::setVideoOnly(bool force)
1762 {
1763     m_videoOnly = force;
1764 }
1765
1766 void ClipItem::setAudioOnly(bool force)
1767 {
1768     m_audioOnly = force;
1769     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1770     else {
1771         if (m_clipType == COLOR) {
1772             QString colour = m_clip->getProperty("colour");
1773             colour = colour.replace(0, 2, "#");
1774             m_baseColor = QColor(colour.left(7));
1775         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1776         else m_baseColor = QColor(141, 166, 215);
1777     }
1778     m_audioThumbCachePic.clear();
1779 }
1780
1781 bool ClipItem::isAudioOnly() const
1782 {
1783     return m_audioOnly;
1784 }
1785
1786 bool ClipItem::isVideoOnly() const
1787 {
1788     return m_videoOnly;
1789 }
1790
1791 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1792 {
1793     if (effect.attribute("disable") == "1") return;
1794     QLocale locale;
1795     effect.setAttribute("active_keyframe", pos);
1796     m_editedKeyframe = pos;
1797     QDomNodeList params = effect.elementsByTagName("parameter");
1798     for (int i = 0; i < params.count(); i++) {
1799         QDomElement e = params.item(i).toElement();
1800         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1801             QString kfr = e.attribute("keyframes");
1802             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1803             QStringList newkfr;
1804             bool added = false;
1805             foreach(const QString &str, keyframes) {
1806                 int kpos = str.section(':', 0, 0).toInt();
1807                 double newval = locale.toDouble(str.section(':', 1, 1));
1808                 if (kpos < pos) {
1809                     newkfr.append(str);
1810                 } else if (!added) {
1811                     if (i == m_visibleParam)
1812                         newkfr.append(QString::number(pos) + ':' + QString::number(val));
1813                     else
1814                         newkfr.append(QString::number(pos) + ':' + locale.toString(newval));
1815                     if (kpos > pos) newkfr.append(str);
1816                     added = true;
1817                 } else newkfr.append(str);
1818             }
1819             if (!added) {
1820                 if (i == m_visibleParam)
1821                     newkfr.append(QString::number(pos) + ':' + QString::number(val));
1822                 else
1823                     newkfr.append(QString::number(pos) + ':' + e.attribute("default"));
1824             }
1825             e.setAttribute("keyframes", newkfr.join(";"));
1826         }
1827     }
1828 }
1829
1830 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1831 {
1832     if (effect.attribute("disable") == "1") return;
1833     QLocale locale;
1834     effect.setAttribute("active_keyframe", newpos);
1835     QDomNodeList params = effect.elementsByTagName("parameter");
1836     int start = cropStart().frames(m_fps);
1837     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1838     for (int i = 0; i < params.count(); i++) {
1839         QDomElement e = params.item(i).toElement();
1840         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1841             QString kfr = e.attribute("keyframes");
1842             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1843             QStringList newkfr;
1844             foreach(const QString &str, keyframes) {
1845                 if (str.section(':', 0, 0).toInt() != oldpos) {
1846                     newkfr.append(str);
1847                 } else if (newpos != -1) {
1848                     newpos = qMax(newpos, start);
1849                     newpos = qMin(newpos, end);
1850                     if (i == m_visibleParam)
1851                         newkfr.append(QString::number(newpos) + ':' + locale.toString(value));
1852                     else
1853                         newkfr.append(QString::number(newpos) + ':' + str.section(':', 1, 1));
1854                 }
1855             }
1856             e.setAttribute("keyframes", newkfr.join(";"));
1857         }
1858     }
1859
1860     updateKeyframes(effect);
1861     update();
1862 }
1863
1864 void ClipItem::updateKeyframes(QDomElement effect)
1865 {
1866     m_keyframes.clear();
1867     QLocale locale;
1868     // parse keyframes
1869     QDomNodeList params = effect.elementsByTagName("parameter");
1870     QDomElement e = params.item(m_visibleParam).toElement();
1871     if (e.attribute("intimeline") != "1") {
1872         setSelectedEffect(m_selectedEffect);
1873         return;
1874     }
1875     m_limitedKeyFrames = e.attribute("type") == "keyframe";
1876     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1877     foreach(const QString &str, keyframes) {
1878         int pos = str.section(':', 0, 0).toInt();
1879         double val = locale.toDouble(str.section(':', 1, 1));
1880         m_keyframes[pos] = val;
1881     }
1882     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1883 }
1884
1885 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1886 {
1887     if (isAudioOnly())
1888         return m_clip->audioProducer(track);
1889     else if (isVideoOnly())
1890         return m_clip->videoProducer(track);
1891     else
1892         return m_clip->getProducer(trackSpecific ? track : -1);
1893 }
1894
1895 QMap<int, QDomElement> ClipItem::adjustEffectsToDuration(int width, int height, ItemInfo oldInfo)
1896 {
1897     QMap<int, QDomElement> effects;
1898     for (int i = 0; i < m_effectList.count(); i++) {
1899         QDomElement effect = m_effectList.at(i);
1900
1901         if (effect.attribute("id").startsWith("fade")) {
1902             QString id = effect.attribute("id");
1903             int in = EffectsList::parameter(effect, "in").toInt();
1904             int out = EffectsList::parameter(effect, "out").toInt();
1905             int clipEnd = (cropStart() + cropDuration()).frames(m_fps) - 1;
1906             if (id == "fade_from_black" || id == "fadein") {
1907                 if (in != cropStart().frames(m_fps)) {
1908                     effects[i] = effect.cloneNode().toElement();
1909                     int duration = out - in;
1910                     in = cropStart().frames(m_fps);
1911                     out = in + duration;
1912                     EffectsList::setParameter(effect, "in", QString::number(in));
1913                     EffectsList::setParameter(effect, "out", QString::number(out));
1914                 }
1915                 if (out > clipEnd) {
1916                     if (!effects.contains(i))
1917                         effects[i] = effect.cloneNode().toElement();
1918                     EffectsList::setParameter(effect, "out", QString::number(clipEnd));
1919                 }
1920                 if (effects.contains(i))
1921                     setFadeIn(out - in);
1922             } else {
1923                 if (out != clipEnd) {
1924                     effects[i] = effect.cloneNode().toElement();
1925                     int diff = out - clipEnd;
1926                     in = qMax(in - diff, (int) cropStart().frames(m_fps));
1927                     out -= diff;
1928                     EffectsList::setParameter(effect, "in", QString::number(in));
1929                     EffectsList::setParameter(effect, "out", QString::number(out));
1930                 }
1931                 if (in < cropStart().frames(m_fps)) {
1932                     if (!effects.contains(i))
1933                         effects[i] = effect.cloneNode().toElement();
1934                     EffectsList::setParameter(effect, "in", QString::number(cropStart().frames(m_fps)));
1935                 }
1936                 if (effects.contains(i))
1937                     setFadeOut(out - in);
1938             }
1939             continue;
1940         } else if (effect.attribute("id") == "freeze" && cropStart() != oldInfo.cropStart) {
1941             effects[i] = effect.cloneNode().toElement();
1942             int diff = (oldInfo.cropStart - cropStart()).frames(m_fps);
1943             int frame = EffectsList::parameter(effect, "frame").toInt();
1944             EffectsList::setParameter(effect, "frame", QString::number(frame - diff));
1945             continue;
1946         } else if (effect.attribute("id") == "pan_zoom") {
1947             effect.setAttribute("in", cropStart().frames(m_fps));
1948             effect.setAttribute("out", (cropStart() + cropDuration()).frames(m_fps) - 1);
1949         }
1950
1951         QDomNodeList params = effect.elementsByTagName("parameter");
1952         for (int j = 0; j < params.count(); j++) {
1953             QDomElement param = params.item(j).toElement();
1954
1955             QString type = param.attribute("type");
1956             if (type == "geometry" && !param.hasAttribute("fixed")) {
1957                 if (!effects.contains(i))
1958                     effects[i] = effect.cloneNode().toElement();
1959                 updateGeometryKeyframes(effect, j, width, height, oldInfo);
1960             } else if (type == "simplekeyframe" || type == "keyframe") {
1961                 if (!effects.contains(i))
1962                     effects[i] = effect.cloneNode().toElement();
1963                 updateNormalKeyframes(param, oldInfo);
1964 #ifdef USE_QJSON
1965             } else if (type == "roto-spline") {
1966                 if (!effects.contains(i))
1967                     effects[i] = effect.cloneNode().toElement();
1968                 QString value = param.attribute("value");
1969                 if (adjustRotoDuration(&value, cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1))
1970                     param.setAttribute("value", value);
1971 #endif    
1972             }
1973         }
1974     }
1975     return effects;
1976 }
1977
1978 bool ClipItem::updateNormalKeyframes(QDomElement parameter, ItemInfo oldInfo)
1979 {
1980     int in = cropStart().frames(m_fps);
1981     int out = (cropStart() + cropDuration()).frames(m_fps) - 1;
1982     int oldin = oldInfo.cropStart.frames(m_fps);
1983     QLocale locale;
1984     bool keyFrameUpdated = false;
1985
1986     const QStringList data = parameter.attribute("keyframes").split(';', QString::SkipEmptyParts);
1987     QMap <int, double> keyframes;
1988     foreach (QString keyframe, data) {
1989         int keyframepos = keyframe.section(':', 0, 0).toInt();
1990         // if keyframe was at clip start, update it
1991         if (keyframepos == oldin) {
1992             keyframepos = in;
1993             keyFrameUpdated = true;
1994         }
1995         keyframes[keyframepos] = locale.toDouble(keyframe.section(':', 1, 1));
1996     }
1997
1998
1999     QMap<int, double>::iterator i = keyframes.end();
2000     int lastPos = -1;
2001     double lastValue = 0;
2002     qreal relPos;
2003
2004     /*
2005      * Take care of resize from start
2006      */
2007     bool startFound = false;
2008     while (i-- != keyframes.begin()) {
2009         if (i.key() < in && !startFound) {
2010             startFound = true;
2011             if (lastPos < 0) {
2012                 keyframes[in] = i.value();
2013             } else {
2014                 relPos = (in - i.key()) / (qreal)(lastPos - i.key() + 1);
2015                 keyframes[in] = i.value() + (lastValue - i.value()) * relPos;
2016             }
2017         }
2018         lastPos = i.key();
2019         lastValue = i.value();
2020         if (startFound)
2021             i = keyframes.erase(i);
2022     }
2023
2024     /*
2025      * Take care of resize from end
2026      */
2027     i = keyframes.begin();
2028     lastPos = -1;
2029     bool endFound = false;
2030     while (i != keyframes.end()) {
2031         if (i.key() > out && !endFound) {
2032             endFound = true;
2033             if (lastPos < 0) {
2034                 keyframes[out] = i.value();
2035             } else {
2036                 relPos = (out - lastPos) / (qreal)(i.key() - lastPos + 1);
2037                 keyframes[out] = lastValue + (i.value() - lastValue) * relPos;
2038             }
2039          }
2040         lastPos = i.key();
2041         lastValue = i.value();
2042         if (endFound)
2043             i = keyframes.erase(i);
2044         else
2045             ++i;
2046     }
2047
2048     if (startFound || endFound || keyFrameUpdated) {
2049         QString newkfr;
2050         QMap<int, double>::const_iterator k = keyframes.constBegin();
2051         while (k != keyframes.constEnd()) {
2052             newkfr.append(QString::number(k.key()) + ':' + QString::number(qRound(k.value())) + ';');
2053             ++k;
2054         }
2055         parameter.setAttribute("keyframes", newkfr);
2056         return true;
2057     }
2058
2059     return false;
2060 }
2061
2062 void ClipItem::updateGeometryKeyframes(QDomElement effect, int paramIndex, int width, int height, ItemInfo oldInfo)
2063 {
2064     QDomElement param = effect.elementsByTagName("parameter").item(paramIndex).toElement();
2065     int offset = oldInfo.cropStart.frames(m_fps);
2066     QString data = param.attribute("value");
2067     if (offset > 0) {
2068         QStringList kfrs = data.split(';');
2069         data.clear();
2070         foreach (const QString &keyframe, kfrs) {
2071             if (keyframe.contains('=')) {
2072                 int pos = keyframe.section('=', 0, 0).toInt();
2073                 pos += offset;
2074                 data.append(QString::number(pos) + '=' + keyframe.section('=', 1) + ";");
2075             }
2076             else data.append(keyframe + ';');
2077         }
2078     }
2079     Mlt::Geometry geometry(data.toUtf8().data(), oldInfo.cropDuration.frames(m_fps), width, height);
2080     param.setAttribute("value", geometry.serialise(cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1));
2081 }
2082
2083 void ClipItem::slotGotThumbsCache()
2084 {
2085     disconnect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
2086     update();
2087 }
2088
2089 void ClipItem::setMainSelectedClip(bool selected)
2090 {
2091     if (selected == m_isMainSelectedClip) return;
2092     m_isMainSelectedClip = selected;
2093     update();
2094 }
2095
2096 bool ClipItem::isMainSelectedClip()
2097 {
2098     return m_isMainSelectedClip;
2099 }
2100
2101 #include "clipitem.moc"
2102