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