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