]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Merge branch 'master' of git://anongit.kde.org/kdenlive
[kdenlive] / src / clipitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "clipitem.h"
22 #include "customtrackview.h"
23 #include "customtrackscene.h"
24 #include "renderer.h"
25 #include "docclipbase.h"
26 #include "transition.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "profilesdialog.h"
30 #ifdef USE_QJSON
31 #include "rotoscoping/rotowidget.h"
32 #endif
33
34 #include <KDebug>
35 #include <KIcon>
36
37 #include <QPainter>
38 #include <QTimer>
39 #include <QStyleOptionGraphicsItem>
40 #include <QGraphicsScene>
41 #include <QMimeData>
42
43 static int FRAME_SIZE;
44
45 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, double speed, int strobe, int frame_width, bool generateThumbs) :
46         AbstractClipItem(info, QRectF(), fps),
47         m_clip(clip),
48         m_startFade(0),
49         m_endFade(0),
50         m_audioOnly(false),
51         m_videoOnly(false),
52         m_startPix(QPixmap()),
53         m_endPix(QPixmap()),
54         m_hasThumbs(false),
55         m_selectedEffect(-1),
56         m_timeLine(0),
57         m_startThumbRequested(false),
58         m_endThumbRequested(false),
59         //m_hover(false),
60         m_speed(speed),
61         m_strobe(strobe),
62         m_framePixelWidth(0),
63         m_limitedKeyFrames(false)
64 {
65     setZValue(2);
66     m_effectList = EffectsList(true);
67     FRAME_SIZE = frame_width;
68     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (double) itemHeight());
69     setPos(info.startPos.frames(fps), (double)(info.track * KdenliveSettings::trackheight()) + 1 + itemOffset());
70
71     // set speed independant info
72     if (m_speed <= 0 && m_speed > -1)
73         m_speed = -1.0;
74     m_speedIndependantInfo = m_info;
75     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
76     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
77
78     m_videoPix = KIcon("kdenlive-show-video").pixmap(QSize(16, 16));
79     m_audioPix = KIcon("kdenlive-show-audio").pixmap(QSize(16, 16));
80
81     if (m_speed == 1.0)
82         m_clipName = m_clip->name();
83     else
84         m_clipName = m_clip->name() + " - " + QString::number(m_speed * 100, 'f', 0) + '%';
85
86     m_producer = m_clip->getId();
87     m_clipType = m_clip->clipType();
88     //m_cropStart = info.cropStart;
89     m_maxDuration = m_clip->maxDuration();
90     setAcceptDrops(true);
91     m_audioThumbReady = m_clip->audioThumbCreated();
92     //setAcceptsHoverEvents(true);
93     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int, 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 }
123
124
125 ClipItem::~ClipItem()
126 {
127     blockSignals(true);
128     m_endThumbTimer.stop();
129     m_startThumbTimer.stop();
130     if (scene()) scene()->removeItem(this);
131     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
132         //disconnect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
133         //disconnect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
134     }
135     delete m_timeLine;
136 }
137
138 ClipItem *ClipItem::clone(ItemInfo info) const
139 {
140     ClipItem *duplicate = new ClipItem(m_clip, info, m_fps, m_speed, m_strobe, FRAME_SIZE);
141     if (m_clipType == IMAGE || m_clipType == TEXT) duplicate->slotSetStartThumb(m_startPix);
142     else if (m_clipType != COLOR) {
143         if (info.cropStart == m_info.cropStart) duplicate->slotSetStartThumb(m_startPix);
144         if (info.cropStart + (info.endPos - info.startPos) == m_info.cropStart + m_info.cropDuration) {
145             duplicate->slotSetEndThumb(m_endPix);
146         }
147     }
148     //kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
149     duplicate->setEffectList(m_effectList);
150     duplicate->setVideoOnly(m_videoOnly);
151     duplicate->setAudioOnly(m_audioOnly);
152     duplicate->setFades(fadeIn(), fadeOut());
153     //duplicate->setSpeed(m_speed);
154     return duplicate;
155 }
156
157 void ClipItem::setEffectList(const EffectsList effectList)
158 {
159     m_effectList.clone(effectList);
160     m_effectNames = m_effectList.effectNames().join(" / ");
161     if (!m_effectList.isEmpty()) {
162         for (int i = 0; i < m_effectList.count(); i++) {
163             QDomElement effect = m_effectList.at(i);
164             QString effectId = effect.attribute("id");
165             // check if it is a fade effect
166             QDomNodeList params = effect.elementsByTagName("parameter");
167             int fade = 0;
168             for (int j = 0; j < params.count(); j++) {
169                 QDomElement e = params.item(j).toElement();
170                 if (!e.isNull()) {
171                     if (effectId == "fadein") {
172                         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
173                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
174                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
175                         } else {
176                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
177                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
178                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
179                         }
180                     } else if (effectId == "fade_from_black") {
181                         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
182                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
183                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
184                         } else {
185                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
186                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
187                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
188                         }
189                     } else if (effectId == "fadeout") {
190                         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
191                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
192                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
193                         } else {
194                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
195                             if (fadeout.attribute("name") == "out") fade += fadeout.attribute("value").toInt();
196                             else if (fadeout.attribute("name") == "in") fade -= fadeout.attribute("value").toInt();
197                         }
198                     } else if (effectId == "fade_to_black") {
199                         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
200                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
201                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
202                         } else {
203                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
204                             if (fadeout.attribute("name") == "out") fade += fadeout.attribute("value").toInt();
205                             else if (fadeout.attribute("name") == "in") fade -= fadeout.attribute("value").toInt();
206                         }
207                     }
208                 }
209             }
210             if (fade > 0)
211                 m_startFade = fade;
212             else if (fade < 0)
213                 m_endFade = -fade;
214         }
215         setSelectedEffect(1);
216     }
217 }
218
219 const EffectsList ClipItem::effectList() const
220 {
221     return m_effectList;
222 }
223
224 int ClipItem::selectedEffectIndex() const
225 {
226     return m_selectedEffect;
227 }
228
229 void ClipItem::initEffect(QDomElement effect, int diff, int offset)
230 {
231     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
232     // not be changed
233
234     if (effect.attribute("id") == "freeze" && diff > 0) {
235         EffectsList::setParameter(effect, "frame", QString::number(diff));
236     }
237
238     // Init parameter value & keyframes if required
239     QDomNodeList params = effect.elementsByTagName("parameter");
240     for (int i = 0; i < params.count(); i++) {
241         QDomElement e = params.item(i).toElement();
242
243         if (e.isNull())
244             continue;
245
246         // Check if this effect has a variable parameter
247         if (e.attribute("default").contains('%')) {
248             double evaluatedValue = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("default"));
249             e.setAttribute("default", evaluatedValue);
250             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
251                 e.setAttribute("value", evaluatedValue);
252             }
253         }
254
255         if (effect.attribute("id") == "crop") {
256             // default use_profile to 1 for clips with proxies to avoid problems when rendering
257             if (e.attribute("name") == "use_profile" && !(m_clip->getProperty("proxy").isEmpty() || m_clip->getProperty("proxy") == "-"))
258                 e.setAttribute("value", "1");
259         }
260
261         if (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") {
262             if (e.attribute("keyframes").isEmpty()) {
263                 // Effect has a keyframe type parameter, we need to set the values
264                 e.setAttribute("keyframes", QString::number((int) cropStart().frames(m_fps)) + ':' + e.attribute("default"));
265             }
266             else if (offset != 0) {
267                 // adjust keyframes to this clip
268                 QString adjusted = adjustKeyframes(e.attribute("keyframes"), offset - cropStart().frames(m_fps));
269                 e.setAttribute("keyframes", adjusted);
270             }
271         }
272
273         if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
274             // Effects with a geometry parameter need to sync in / out with parent clip
275             effect.setAttribute("in", QString::number((int) cropStart().frames(m_fps)));
276             effect.setAttribute("out", QString::number((int) (cropStart() + cropDuration()).frames(m_fps) - 1));
277             effect.setAttribute("_sync_in_out", "1");
278         }
279     }
280     if (effect.attribute("tag") == "volume" || effect.attribute("tag") == "brightness") {
281         if (effect.attribute("id") == "fadeout" || effect.attribute("id") == "fade_to_black") {
282             int end = (cropDuration() + cropStart()).frames(m_fps) - 1;
283             int start = end;
284             if (effect.attribute("id") == "fadeout") {
285                 if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
286                     int effectDuration = EffectsList::parameter(effect, "out").toInt() - EffectsList::parameter(effect, "in").toInt();
287                     if (effectDuration > cropDuration().frames(m_fps)) {
288                         effectDuration = cropDuration().frames(m_fps) / 2;
289                     }
290                     start -= effectDuration;
291                 } else {
292                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
293                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
294                 }
295             } else if (effect.attribute("id") == "fade_to_black") {
296                 if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
297                     int effectDuration = EffectsList::parameter(effect, "out").toInt() - EffectsList::parameter(effect, "in").toInt();
298                     if (effectDuration > cropDuration().frames(m_fps)) {
299                         effectDuration = cropDuration().frames(m_fps) / 2;
300                     }
301                     start -= effectDuration;
302                 } else {
303                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
304                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
305                 }
306             }
307             EffectsList::setParameter(effect, "in", QString::number(start));
308             EffectsList::setParameter(effect, "out", QString::number(end));
309         } else if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fade_from_black") {
310             int start = cropStart().frames(m_fps);
311             int end = start;
312             if (effect.attribute("id") == "fadein") {
313                 if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
314                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
315                     if (offset != 0) effectDuration -= offset;
316                     if (effectDuration > cropDuration().frames(m_fps)) {
317                         effectDuration = cropDuration().frames(m_fps) / 2;
318                     }
319                     end += effectDuration;
320                 } else
321                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fade_from_black"), "out").toInt() - offset;
322             } else if (effect.attribute("id") == "fade_from_black") {
323                 if (m_effectList.hasEffect(QString(), "fadein") == -1) {
324                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
325                     if (offset != 0) effectDuration -= offset;
326                     if (effectDuration > cropDuration().frames(m_fps)) {
327                         effectDuration = cropDuration().frames(m_fps) / 2;
328                     }
329                     end += effectDuration;
330                 } else
331                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fadein"), "out").toInt() - offset;
332             }
333             EffectsList::setParameter(effect, "in", QString::number(start));
334             EffectsList::setParameter(effect, "out", QString::number(end));
335         }
336     }
337 }
338
339 const QString ClipItem::adjustKeyframes(QString keyframes, int offset)
340 {
341     QStringList result;
342     // Simple keyframes
343     const QStringList list = keyframes.split(';', QString::SkipEmptyParts);
344     foreach(const QString &keyframe, list) {
345         int pos = keyframe.section(':', 0, 0).toInt() - offset;
346         QString newKey = QString::number(pos) + ":" + keyframe.section(':', 1);
347         result.append(newKey);
348     }
349     return result.join(";");
350 }
351
352 bool ClipItem::checkKeyFrames(int width, int height, int previousDuration, int cutPos)
353 {
354     bool clipEffectsModified = false;
355     QLocale locale;
356     // go through all effects this clip has
357     for (int ix = 0; ix < m_effectList.count(); ++ix) {
358         // Check geometry params
359         resizeGeometries(ix, width, height, previousDuration, cutPos == -1 ? 0 : cutPos, cropDuration().frames(m_fps) - 1);
360
361         // Check keyframe params
362         QStringList keyframeParams = keyframes(ix);
363         QStringList newKeyFrameParams;
364         bool effModified = false;
365
366         // go through all params which have keyframes
367         foreach(const QString &kfr, keyframeParams) {
368             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
369             QStringList newKeyFrames;
370             bool cutKeyFrame = false;
371             bool modified = false;
372             int lastPos = -1;
373             double lastValue = -1;
374             int start = cropStart().frames(m_fps);
375             int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
376
377             // go through all keyframes for one param
378             foreach(const QString &str, keyframes) {
379                 int pos = str.section(':', 0, 0).toInt();
380                 double val = locale.toDouble(str.section(':', 1, 1));
381                 if (pos - start < 0) {
382                     // a keyframe is defined before the start of the clip
383                     cutKeyFrame = true;
384                 } else if (cutKeyFrame) {
385                     // create new keyframe at clip start, calculate interpolated value
386                     if (pos > start) {
387                         int diff = pos - lastPos;
388                         double ratio = (double)(start - lastPos) / diff;
389                         int newValue = lastValue + (val - lastValue) * ratio;
390                         newKeyFrames.append(QString::number(start) + ':' + QString::number(newValue));
391                         modified = true;
392                     }
393                     cutKeyFrame = false;
394                 }
395                 if (!cutKeyFrame) {
396                     if (pos > end) {
397                         // create new keyframe at clip end, calculate interpolated value
398                         int diff = pos - lastPos;
399                         if (diff != 0) {
400                             double ratio = (double)(end - lastPos) / diff;
401                             int newValue = lastValue + (val - lastValue) * ratio;
402                             newKeyFrames.append(QString::number(end) + ':' + QString::number(newValue));
403                             modified = true;
404                         }
405                         break;
406                     } else {
407                         newKeyFrames.append(QString::number(pos) + ':' + QString::number(val));
408                     }
409                 }
410                 lastPos = pos;
411                 lastValue = val;
412             }
413
414             newKeyFrameParams.append(newKeyFrames.join(";"));
415             if (modified)
416                 effModified = true;
417         }
418
419         if (effModified) {
420             // update KeyFrames
421             setKeyframes(ix, newKeyFrameParams);
422             clipEffectsModified = true;
423         }
424     }
425     return clipEffectsModified;
426 }
427
428 void ClipItem::setKeyframes(const int ix, const QStringList keyframes)
429 {
430     QDomElement effect = m_effectList.at(ix);
431     if (effect.attribute("disable") == "1") return;
432     QLocale locale;
433     QDomNodeList params = effect.elementsByTagName("parameter");
434     int keyframeParams = 0;
435     for (int i = 0; i < params.count(); i++) {
436         QDomElement e = params.item(i).toElement();
437         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && (!e.hasAttribute("intimeline") || e.attribute("intimeline") == "1")) {
438             e.setAttribute("keyframes", keyframes.at(keyframeParams));
439             if (ix + 1 == m_selectedEffect && keyframeParams == 0) {
440                 m_keyframes.clear();
441                 m_visibleParam = i;
442                 double max = locale.toDouble(e.attribute("max"));
443                 double min = locale.toDouble(e.attribute("min"));
444                 m_keyframeFactor = 100.0 / (max - min);
445                 m_keyframeOffset = min;
446                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
447                 m_selectedKeyframe = 0;
448                 // parse keyframes
449                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
450                 foreach(const QString &str, keyframes) {
451                     int pos = str.section(':', 0, 0).toInt();
452                     double val = locale.toDouble(str.section(':', 1, 1));
453                     m_keyframes[pos] = val;
454                 }
455                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
456                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
457                 update();
458             }
459             ++keyframeParams;
460         }
461     }
462 }
463
464
465 void ClipItem::setSelectedEffect(const int ix)
466 {
467     m_selectedEffect = ix;
468     QLocale locale;
469     QDomElement effect = effectAtIndex(m_selectedEffect);
470     if (!effect.isNull() && effect.attribute("disable") != "1") {
471         QDomNodeList params = effect.elementsByTagName("parameter");
472         for (int i = 0; i < params.count(); i++) {
473             QDomElement e = params.item(i).toElement();
474             if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && (!e.hasAttribute("intimeline") || e.attribute("intimeline") == "1")) {
475                 m_keyframes.clear();
476                 m_limitedKeyFrames = e.attribute("type") == "keyframe";
477                 m_visibleParam = i;
478                 double max = locale.toDouble(e.attribute("max"));
479                 double min = locale.toDouble(e.attribute("min"));
480                 m_keyframeFactor = 100.0 / (max - min);
481                 m_keyframeOffset = min;
482                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
483                 m_selectedKeyframe = 0;
484
485                 // parse keyframes
486                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
487                 foreach(const QString &str, keyframes) {
488                     int pos = str.section(':', 0, 0).toInt();
489                     double val = locale.toDouble(str.section(':', 1, 1));
490                     m_keyframes[pos] = val;
491                 }
492                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end())
493                     m_editedKeyframe = -1;
494                 update();
495                 return;
496             }
497         }
498     }
499
500     if (!m_keyframes.isEmpty()) {
501         m_keyframes.clear();
502         update();
503     }
504 }
505
506 void ClipItem::resizeGeometries(const int index, int width, int height, int previousDuration, int start, int duration)
507 {
508     QString geom;
509     QDomElement effect = m_effectList.at(index);
510     QDomNodeList params = effect.elementsByTagName("parameter");
511
512     for (int i = 0; i < params.count(); i++) {
513         QDomElement e = params.item(i).toElement();
514         if (!e.isNull() && e.attribute("type") == "geometry") {
515             geom = e.attribute("value");
516             Mlt::Geometry geometry(geom.toUtf8().data(), previousDuration, width, height);
517             e.setAttribute("value", geometry.serialise(start, start + duration));
518         }
519     }
520 }
521
522 QStringList ClipItem::keyframes(const int index)
523 {
524     QStringList result;
525     QDomElement effect = m_effectList.at(index);
526     QDomNodeList params = effect.elementsByTagName("parameter");
527
528     for (int i = 0; i < params.count(); i++) {
529         QDomElement e = params.item(i).toElement();
530         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe"))
531             result.append(e.attribute("keyframes"));
532     }
533     return result;
534 }
535
536 void ClipItem::updateKeyframeEffect()
537 {
538     // regenerate xml parameter from the clip keyframes
539     QDomElement effect = getEffectAtIndex(m_selectedEffect);
540     if (effect.attribute("disable") == "1") return;
541     QDomNodeList params = effect.elementsByTagName("parameter");
542     QDomElement e = params.item(m_visibleParam).toElement();
543
544     if (!e.isNull()) {
545         QString keyframes;
546         if (m_keyframes.count() > 0) {
547             QMap<int, int>::const_iterator i = m_keyframes.constBegin();
548             while (i != m_keyframes.constEnd()) {
549                 keyframes.append(QString::number(i.key()) + ':' + QString::number(i.value()) + ';');
550                 ++i;
551             }
552         }
553         // Effect has a keyframe type parameter, we need to set the values
554         e.setAttribute("keyframes", keyframes);
555     }
556 }
557
558 QDomElement ClipItem::selectedEffect()
559 {
560     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
561     return effectAtIndex(m_selectedEffect);
562 }
563
564 void ClipItem::resetThumbs(bool clearExistingThumbs)
565 {
566     if (clearExistingThumbs) {
567         m_startPix = QPixmap();
568         m_endPix = QPixmap();
569         m_audioThumbCachePic.clear();
570     }
571     slotFetchThumbs();
572 }
573
574
575 void ClipItem::refreshClip(bool checkDuration, bool forceResetThumbs)
576 {
577     if (checkDuration && (m_maxDuration != m_clip->maxDuration())) {
578         m_maxDuration = m_clip->maxDuration();
579         if (m_clipType != IMAGE && m_clipType != TEXT && m_clipType != COLOR) {
580             if (m_maxDuration != GenTime() && m_info.cropStart + m_info.cropDuration > m_maxDuration) {
581                 // Clip duration changed, make sure to stay in correct range
582                 if (m_info.cropStart > m_maxDuration) {
583                     m_info.cropStart = GenTime();
584                     m_info.cropDuration = qMin(m_info.cropDuration, m_maxDuration);
585                 } else {
586                     m_info.cropDuration = m_maxDuration;
587                 }
588                 updateRectGeometry();
589             }
590         }
591     }
592     if (m_clipType == COLOR) {
593         QString colour = m_clip->getProperty("colour");
594         colour = colour.replace(0, 2, "#");
595         m_baseColor = QColor(colour.left(7));
596         update();
597     } else resetThumbs(forceResetThumbs);
598 }
599
600 void ClipItem::slotFetchThumbs()
601 {
602     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
603     if (m_clipType == IMAGE) {
604         if (m_startPix.isNull()) {
605             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
606             update();
607         }
608         return;
609     }
610
611     if (m_clipType == TEXT) {
612         if (m_startPix.isNull()) slotGetStartThumb();
613         return;
614     }
615
616     QList <int> frames;
617     if (m_startPix.isNull()) {
618         m_startThumbRequested = true;
619         frames.append((int)m_speedIndependantInfo.cropStart.frames(m_fps));
620     }
621
622     if (m_endPix.isNull()) {
623         m_endThumbRequested = true;
624         frames.append((int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
625     }
626
627     if (!frames.isEmpty()) m_clip->slotExtractImage(frames);
628 }
629
630 void ClipItem::stopThumbs()
631 {
632     // Clip is about to be deleted, make sure we don't request thumbnails
633     disconnect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
634     disconnect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
635 }
636
637 void ClipItem::slotGetStartThumb()
638 {
639     m_startThumbRequested = true;
640     m_clip->slotExtractImage(QList<int>() << (int)m_speedIndependantInfo.cropStart.frames(m_fps));
641 }
642
643 void ClipItem::slotGetEndThumb()
644 {
645     m_endThumbRequested = true;
646     m_clip->slotExtractImage(QList<int>() << (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
647 }
648
649
650 void ClipItem::slotSetStartThumb(QImage img)
651 {
652     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
653         QPixmap pix = QPixmap::fromImage(img);
654         m_startPix = pix;
655         QRectF r = sceneBoundingRect();
656         r.setRight(pix.width() + 2);
657         update(r);
658     }
659 }
660
661 void ClipItem::slotSetEndThumb(QImage img)
662 {
663     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
664         QPixmap pix = QPixmap::fromImage(img);
665         m_endPix = pix;
666         QRectF r = sceneBoundingRect();
667         r.setLeft(r.right() - pix.width() - 2);
668         update(r);
669     }
670 }
671
672 void ClipItem::slotThumbReady(int frame, QImage img)
673 {
674     if (scene() == NULL) return;
675     QRectF r = boundingRect();
676     QPixmap pix = QPixmap::fromImage(img);
677     double width = pix.width() / projectScene()->scale().x();
678     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
679         m_startPix = pix;
680         m_startThumbRequested = false;
681         update(r.left(), r.top(), width, pix.height());
682         if (m_clipType == IMAGE || m_clipType == TEXT) {
683             update(r.right() - width, r.top(), width, pix.height());
684         }
685     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
686         m_endPix = pix;
687         m_endThumbRequested = false;
688         update(r.right() - width, r.top(), width, pix.height());
689     }
690 }
691
692 void ClipItem::slotSetStartThumb(const QPixmap pix)
693 {
694     m_startPix = pix;
695 }
696
697 void ClipItem::slotSetEndThumb(const QPixmap pix)
698 {
699     m_endPix = pix;
700 }
701
702 QPixmap ClipItem::startThumb() const
703 {
704     return m_startPix;
705 }
706
707 QPixmap ClipItem::endThumb() const
708 {
709     return m_endPix;
710 }
711
712 void ClipItem::slotGotAudioData()
713 {
714     m_audioThumbReady = true;
715     if (m_clipType == AV && !isAudioOnly()) {
716         QRectF r = boundingRect();
717         r.setTop(r.top() + r.height() / 2 - 1);
718         update(r);
719     } else update();
720 }
721
722 int ClipItem::type() const
723 {
724     return AVWIDGET;
725 }
726
727 DocClipBase *ClipItem::baseClip() const
728 {
729     return m_clip;
730 }
731
732 QDomElement ClipItem::xml() const
733 {
734     return itemXml();
735 }
736
737 QDomElement ClipItem::itemXml() const
738 {
739     QDomElement xml = m_clip->toXML();
740     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
741     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
742     if (m_audioOnly) xml.setAttribute("audio_only", 1);
743     else if (m_videoOnly) xml.setAttribute("video_only", 1);
744     return xml;
745 }
746
747 int ClipItem::clipType() const
748 {
749     return m_clipType;
750 }
751
752 QString ClipItem::clipName() const
753 {
754     return m_clipName;
755 }
756
757 void ClipItem::setClipName(const QString &name)
758 {
759     m_clipName = name;
760 }
761
762 const QString ClipItem::clipProducer() const
763 {
764     return m_producer;
765 }
766
767 void ClipItem::flashClip()
768 {
769     if (m_timeLine == 0) {
770         m_timeLine = new QTimeLine(750, this);
771         m_timeLine->setUpdateInterval(80);
772         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
773         m_timeLine->setFrameRange(0, 100);
774         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
775     }
776     //m_timeLine->start();
777 }
778
779 void ClipItem::animate(qreal /*value*/)
780 {
781     QRectF r = boundingRect();
782     r.setHeight(20);
783     update(r);
784 }
785
786 // virtual
787 void ClipItem::paint(QPainter *painter,
788                      const QStyleOptionGraphicsItem *option,
789                      QWidget *)
790 {
791     QPalette palette = scene()->palette();
792     QColor paintColor;
793     QColor textColor;
794     QColor textBgColor;
795     QPen framePen;
796     if (parentItem()) paintColor = QColor(255, 248, 149);
797     else paintColor = m_baseColor;
798     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
799         textColor = palette.highlightedText().color();
800         textBgColor = palette.highlight().color();
801         paintColor = paintColor.darker();
802         framePen.setColor(textBgColor);
803     }
804     else {
805         textColor = palette.text().color();
806         textBgColor = palette.window().color();
807         textBgColor.setAlpha(200);
808         framePen.setColor(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(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(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()) setZValue(10);
1390         else setZValue(2);
1391     }
1392     if (change == ItemPositionChange && scene()) {
1393         // calculate new position.
1394         //if (parentItem()) return pos();
1395         QPointF newPos = value.toPointF();
1396         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1397         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1398         xpos = qMax(xpos, 0);
1399         newPos.setX(xpos);
1400         // Warning: newPos gives a position relative to the click event, so hack to get absolute pos
1401         int yOffset = property("y_absolute").toInt() + newPos.y();
1402         int newTrack = yOffset / KdenliveSettings::trackheight();
1403         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1404         newTrack = qMax(newTrack, 0);
1405         QStringList lockedTracks = property("locked_tracks").toStringList();
1406         if (lockedTracks.contains(QString::number(newTrack))) {
1407             // Trying to move to a locked track
1408             return pos();
1409         }
1410         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1411         // Only one clip is moving
1412         QRectF sceneShape = rect();
1413         sceneShape.translate(newPos);
1414         QList<QGraphicsItem*> items;
1415         if (projectScene()->editMode() == NORMALEDIT)
1416             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1417         items.removeAll(this);
1418         bool forwardMove = newPos.x() > pos().x();
1419         int offset = 0;
1420         if (!items.isEmpty()) {
1421             for (int i = 0; i < items.count(); i++) {
1422                 if (!items.at(i)->isEnabled()) continue;
1423                 if (items.at(i)->type() == type()) {
1424                     // Collision!
1425                     QPointF otherPos = items.at(i)->pos();
1426                     if ((int) otherPos.y() != (int) pos().y()) {
1427                         return pos();
1428                     }
1429                     if (forwardMove) {
1430                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1431                     } else {
1432                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1433                     }
1434
1435                     if (offset > 0) {
1436                         if (forwardMove) {
1437                             sceneShape.translate(QPointF(-offset, 0));
1438                             newPos.setX(newPos.x() - offset);
1439                         } else {
1440                             sceneShape.translate(QPointF(offset, 0));
1441                             newPos.setX(newPos.x() + offset);
1442                         }
1443                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1444                         subitems.removeAll(this);
1445                         for (int j = 0; j < subitems.count(); j++) {
1446                             if (!subitems.at(j)->isEnabled()) continue;
1447                             if (subitems.at(j)->type() == type()) {
1448                                 // move was not successful, revert to previous pos
1449                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1450                                 return pos();
1451                             }
1452                         }
1453                     }
1454
1455                     m_info.track = newTrack;
1456                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1457
1458                     return newPos;
1459                 }
1460             }
1461         }
1462         m_info.track = newTrack;
1463         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1464         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1465         return newPos;
1466     }
1467     return QGraphicsItem::itemChange(change, value);
1468 }
1469
1470 // virtual
1471 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1472 }*/
1473
1474 int ClipItem::effectsCounter()
1475 {
1476     return effectsCount() + 1;
1477 }
1478
1479 int ClipItem::effectsCount()
1480 {
1481     return m_effectList.count();
1482 }
1483
1484 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1485 {
1486     return m_effectList.hasEffect(tag, id);
1487 }
1488
1489 QStringList ClipItem::effectNames()
1490 {
1491     return m_effectList.effectNames();
1492 }
1493
1494 QDomElement ClipItem::effect(int ix) const
1495 {
1496     if (ix >= m_effectList.count() || ix < 0) return QDomElement();
1497     return m_effectList.at(ix).cloneNode().toElement();
1498 }
1499
1500 QDomElement ClipItem::effectAtIndex(int ix) const
1501 {
1502     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1503     return m_effectList.itemFromIndex(ix).cloneNode().toElement();
1504 }
1505
1506 QDomElement ClipItem::getEffectAtIndex(int ix) const
1507 {
1508     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1509     return m_effectList.itemFromIndex(ix);
1510 }
1511
1512 void ClipItem::updateEffect(QDomElement effect)
1513 {
1514     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1515     m_effectList.updateEffect(effect);
1516     m_effectNames = m_effectList.effectNames().join(" / ");
1517     QString id = effect.attribute("id");
1518     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1519         update();
1520     else {
1521         QRectF r = boundingRect();
1522         r.setHeight(20);
1523         update(r);
1524     }
1525 }
1526
1527 void ClipItem::enableEffects(QList <int> indexes, bool disable)
1528 {
1529     m_effectList.enableEffects(indexes, disable);
1530 }
1531
1532 bool ClipItem::moveEffect(QDomElement effect, int ix)
1533 {
1534     if (ix <= 0 || ix > (m_effectList.count()) || effect.isNull()) {
1535         kDebug() << "Invalid effect index: " << ix;
1536         return false;
1537     }
1538     m_effectList.removeAt(effect.attribute("kdenlive_ix").toInt());
1539     effect.setAttribute("kdenlive_ix", ix);
1540     m_effectList.insert(effect);
1541     m_effectNames = m_effectList.effectNames().join(" / ");
1542     QString id = effect.attribute("id");
1543     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1544         update();
1545     else {
1546         QRectF r = boundingRect();
1547         r.setHeight(20);
1548         update(r);
1549     }
1550     return true;
1551 }
1552
1553 EffectsParameterList ClipItem::addEffect(QDomElement effect, bool /*animate*/)
1554 {
1555     bool needRepaint = false;
1556     QLocale locale;
1557     int ix;
1558     QDomElement insertedEffect;
1559     if (!effect.hasAttribute("kdenlive_ix")) {
1560         // effect dropped from effect list
1561         ix = effectsCounter();
1562     } else ix = effect.attribute("kdenlive_ix").toInt();
1563     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1564         needRepaint = true;
1565         insertedEffect = m_effectList.insert(effect);
1566     } else insertedEffect = m_effectList.append(effect);
1567     
1568     // Update index to the real one
1569     effect.setAttribute("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1570     int effectIn;
1571     int effectOut;
1572
1573     if (effect.attribute("tag") == "affine") {
1574         // special case: the affine effect needs in / out points
1575         effectIn = effect.attribute("in").toInt();
1576         effectOut = effect.attribute("out").toInt();
1577     }
1578     else {
1579         effectIn = EffectsList::parameter(effect, "in").toInt();
1580         effectOut = EffectsList::parameter(effect, "out").toInt();
1581     }
1582     
1583     EffectsParameterList parameters;
1584     parameters.addParam("tag", insertedEffect.attribute("tag"));
1585     parameters.addParam("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1586     if (insertedEffect.hasAttribute("src")) parameters.addParam("src", insertedEffect.attribute("src"));
1587     if (insertedEffect.hasAttribute("disable")) parameters.addParam("disable", insertedEffect.attribute("disable"));
1588
1589     QString effectId = insertedEffect.attribute("id");
1590     if (effectId.isEmpty()) effectId = insertedEffect.attribute("tag");
1591     parameters.addParam("id", effectId);
1592
1593     QDomNodeList params = insertedEffect.elementsByTagName("parameter");
1594     int fade = 0;
1595     bool needInOutSync = false;
1596
1597     // check if it is a fade effect
1598     if (effectId == "fadein") {
1599         needRepaint = true;
1600         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1601             fade = effectOut - effectIn;
1602         }/* else {
1603             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1604             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1605             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1606         }*/
1607     } else if (effectId == "fade_from_black") {
1608         needRepaint = true;
1609         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1610             fade = effectOut - effectIn;
1611         }/* else {
1612             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1613             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1614             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1615         }*/
1616      } else if (effectId == "fadeout") {
1617         needRepaint = true;
1618         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1619             fade = effectIn - effectOut;
1620         } /*else {
1621             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1622             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1623             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1624         }*/
1625     } else if (effectId == "fade_to_black") {
1626         needRepaint = true;
1627         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1628             fade = effectIn - effectOut;
1629         }/* else {
1630             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1631             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1632             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1633         }*/
1634     }
1635
1636     for (int i = 0; i < params.count(); i++) {
1637         QDomElement e = params.item(i).toElement();
1638         if (!e.isNull()) {
1639             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1640                 // Effects with a geometry parameter need to sync in / out with parent clip
1641                 needInOutSync = true;
1642             }
1643             if (e.attribute("type") == "simplekeyframe") {
1644                 QStringList values = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1645                 double factor = locale.toDouble(e.attribute("factor", "1"));
1646                 double offset = e.attribute("offset", "0").toDouble();
1647                 if (factor != 1 || offset != 0) {
1648                     for (int j = 0; j < values.count(); j++) {
1649                         QString pos = values.at(j).section(':', 0, 0);
1650                         double val = (locale.toDouble(values.at(j).section(':', 1, 1)) - offset) / factor;
1651                         values[j] = pos + '=' + locale.toString(val);
1652                     }
1653                 }
1654                 parameters.addParam(e.attribute("name"), values.join(";"));
1655                 /*parameters.addParam("max", e.attribute("max"));
1656                 parameters.addParam("min", e.attribute("min"));
1657                 parameters.addParam("factor", );*/
1658             } else if (e.attribute("type") == "keyframe") {
1659                 parameters.addParam("keyframes", e.attribute("keyframes"));
1660                 parameters.addParam("max", e.attribute("max"));
1661                 parameters.addParam("min", e.attribute("min"));
1662                 parameters.addParam("factor", e.attribute("factor", "1"));
1663                 parameters.addParam("offset", e.attribute("offset", "0"));
1664                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1665                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1666             } else if (e.attribute("factor", "1") == "1" && e.attribute("offset", "0") == "0") {
1667                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1668
1669             } else {
1670                 double fact;
1671                 if (e.attribute("factor").contains('%')) {
1672                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1673                 } else {
1674                     fact = locale.toDouble(e.attribute("factor", "1"));
1675                 }
1676                 double offset = e.attribute("offset", "0").toDouble();
1677                 parameters.addParam(e.attribute("name"), locale.toString((locale.toDouble(e.attribute("value")) - offset) / fact));
1678             }
1679         }
1680     }
1681     if (needInOutSync) {
1682         parameters.addParam("in", QString::number((int) cropStart().frames(m_fps)));
1683         parameters.addParam("out", QString::number((int) (cropStart() + cropDuration()).frames(m_fps) - 1));
1684         parameters.addParam("_sync_in_out", "1");
1685     }
1686     m_effectNames = m_effectList.effectNames().join(" / ");
1687     if (fade > 0) m_startFade = fade;
1688     else if (fade < 0) m_endFade = -fade;
1689
1690     if (m_selectedEffect == -1) {
1691         setSelectedEffect(1);
1692     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1693     if (needRepaint) update(boundingRect());
1694     /*if (animate) {
1695         flashClip();
1696     } */
1697     else { /*if (!needRepaint) */
1698         QRectF r = boundingRect();
1699         r.setHeight(20);
1700         update(r);
1701     }
1702     return parameters;
1703 }
1704
1705 void ClipItem::deleteEffect(QString index)
1706 {
1707     bool needRepaint = false;
1708     int ix = index.toInt();
1709
1710     QDomElement effect = m_effectList.itemFromIndex(ix);
1711     QString effectId = effect.attribute("id");
1712     if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1713         (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1714         m_startFade = 0;
1715         needRepaint = true;
1716     } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1717         (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1718         m_endFade = 0;
1719         needRepaint = true;
1720     } else if (EffectsList::hasKeyFrames(effect)) needRepaint = true;
1721     m_effectList.removeAt(ix);
1722     m_effectNames = m_effectList.effectNames().join(" / ");
1723
1724     if (m_effectList.isEmpty() || m_selectedEffect == ix) {
1725         // Current effect was removed
1726         if (ix > m_effectList.count()) {
1727             setSelectedEffect(m_effectList.count());
1728         } else setSelectedEffect(ix);
1729     }
1730     if (needRepaint) update(boundingRect());
1731     else {
1732         QRectF r = boundingRect();
1733         r.setHeight(20);
1734         update(r);
1735     }
1736     //if (!m_effectList.isEmpty()) flashClip();
1737 }
1738
1739 double ClipItem::speed() const
1740 {
1741     return m_speed;
1742 }
1743
1744 int ClipItem::strobe() const
1745 {
1746     return m_strobe;
1747 }
1748
1749 void ClipItem::setSpeed(const double speed, const int strobe)
1750 {
1751     m_speed = speed;
1752     if (m_speed <= 0 && m_speed > -1)
1753         m_speed = -1.0;
1754     m_strobe = strobe;
1755     if (m_speed == 1.0) m_clipName = m_clip->name();
1756     else m_clipName = m_clip->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1757     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1758     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1759     //update();
1760 }
1761
1762 GenTime ClipItem::maxDuration() const
1763 {
1764     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1765 }
1766
1767 GenTime ClipItem::speedIndependantCropStart() const
1768 {
1769     return m_speedIndependantInfo.cropStart;
1770 }
1771
1772 GenTime ClipItem::speedIndependantCropDuration() const
1773 {
1774     return m_speedIndependantInfo.cropDuration;
1775 }
1776
1777
1778 const ItemInfo ClipItem::speedIndependantInfo() const
1779 {
1780     return m_speedIndependantInfo;
1781 }
1782
1783 int ClipItem::nextFreeEffectGroupIndex() const
1784 {
1785     int freeGroupIndex = 0;
1786     for (int i = 0; i < m_effectList.count(); i++) {
1787         QDomElement effect = m_effectList.at(i);
1788         EffectInfo effectInfo;
1789         effectInfo.fromString(effect.attribute("kdenlive_info"));
1790         if (effectInfo.groupIndex >= freeGroupIndex) {
1791             freeGroupIndex = effectInfo.groupIndex + 1;
1792         }
1793     }
1794     return freeGroupIndex;
1795 }
1796
1797 //virtual
1798 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1799 {
1800     if (event->proposedAction() == Qt::CopyAction && scene() && !scene()->views().isEmpty()) {
1801         const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
1802         event->acceptProposedAction();
1803         QDomDocument doc;
1804         doc.setContent(effects, true);
1805         QDomElement e = doc.documentElement();
1806         if (e.tagName() == "effectgroup") {
1807             // dropped an effect group
1808             QDomNodeList effectlist = e.elementsByTagName("effect");
1809             int freeGroupIndex = nextFreeEffectGroupIndex();
1810             EffectInfo effectInfo;
1811             for (int i = 0; i < effectlist.count(); i++) {
1812                 QDomElement effect = effectlist.at(i).toElement();
1813                 effectInfo.fromString(effect.attribute("kdenlive_info"));
1814                 effectInfo.groupIndex = freeGroupIndex;
1815                 effect.setAttribute("kdenlive_info", effectInfo.toString());
1816                 effect.removeAttribute("kdenlive_ix");
1817             }
1818         } else {
1819             // single effect dropped
1820             e.removeAttribute("kdenlive_ix");
1821         }
1822         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1823         if (view) view->slotDropEffect(this, e, m_info.startPos, track());
1824     }
1825     else return;
1826 }
1827
1828 //virtual
1829 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1830 {
1831     if (isItemLocked()) event->setAccepted(false);
1832     else if (event->mimeData()->hasFormat("kdenlive/effectslist")) {
1833         event->acceptProposedAction();
1834     } else event->setAccepted(false);
1835 }
1836
1837 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1838 {
1839     Q_UNUSED(event)
1840 }
1841
1842 void ClipItem::addTransition(Transition* t)
1843 {
1844     m_transitionsList.append(t);
1845     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1846     QDomDocument doc;
1847     QDomElement e = doc.documentElement();
1848     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1849 }
1850
1851 void ClipItem::setVideoOnly(bool force)
1852 {
1853     m_videoOnly = force;
1854 }
1855
1856 void ClipItem::setAudioOnly(bool force)
1857 {
1858     m_audioOnly = force;
1859     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1860     else {
1861         if (m_clipType == COLOR) {
1862             QString colour = m_clip->getProperty("colour");
1863             colour = colour.replace(0, 2, "#");
1864             m_baseColor = QColor(colour.left(7));
1865         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1866         else m_baseColor = QColor(141, 166, 215);
1867     }
1868     m_audioThumbCachePic.clear();
1869 }
1870
1871 bool ClipItem::isAudioOnly() const
1872 {
1873     return m_audioOnly;
1874 }
1875
1876 bool ClipItem::isVideoOnly() const
1877 {
1878     return m_videoOnly;
1879 }
1880
1881 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1882 {
1883     if (effect.attribute("disable") == "1") return;
1884     QLocale locale;
1885     effect.setAttribute("active_keyframe", pos);
1886     m_editedKeyframe = pos;
1887     QDomNodeList params = effect.elementsByTagName("parameter");
1888     for (int i = 0; i < params.count(); i++) {
1889         QDomElement e = params.item(i).toElement();
1890         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1891             QString kfr = e.attribute("keyframes");
1892             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1893             QStringList newkfr;
1894             bool added = false;
1895             foreach(const QString &str, keyframes) {
1896                 int kpos = str.section(':', 0, 0).toInt();
1897                 double newval = locale.toDouble(str.section(':', 1, 1));
1898                 if (kpos < pos) {
1899                     newkfr.append(str);
1900                 } else if (!added) {
1901                     if (i == m_visibleParam)
1902                         newkfr.append(QString::number(pos) + ':' + QString::number(val));
1903                     else
1904                         newkfr.append(QString::number(pos) + ':' + locale.toString(newval));
1905                     if (kpos > pos) newkfr.append(str);
1906                     added = true;
1907                 } else newkfr.append(str);
1908             }
1909             if (!added) {
1910                 if (i == m_visibleParam)
1911                     newkfr.append(QString::number(pos) + ':' + QString::number(val));
1912                 else
1913                     newkfr.append(QString::number(pos) + ':' + e.attribute("default"));
1914             }
1915             e.setAttribute("keyframes", newkfr.join(";"));
1916         }
1917     }
1918 }
1919
1920 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1921 {
1922     if (effect.attribute("disable") == "1") return;
1923     QLocale locale;
1924     effect.setAttribute("active_keyframe", newpos);
1925     QDomNodeList params = effect.elementsByTagName("parameter");
1926     int start = cropStart().frames(m_fps);
1927     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1928     for (int i = 0; i < params.count(); i++) {
1929         QDomElement e = params.item(i).toElement();
1930         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1931             QString kfr = e.attribute("keyframes");
1932             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1933             QStringList newkfr;
1934             foreach(const QString &str, keyframes) {
1935                 if (str.section(':', 0, 0).toInt() != oldpos) {
1936                     newkfr.append(str);
1937                 } else if (newpos != -1) {
1938                     newpos = qMax(newpos, start);
1939                     newpos = qMin(newpos, end);
1940                     if (i == m_visibleParam)
1941                         newkfr.append(QString::number(newpos) + ':' + locale.toString(value));
1942                     else
1943                         newkfr.append(QString::number(newpos) + ':' + str.section(':', 1, 1));
1944                 }
1945             }
1946             e.setAttribute("keyframes", newkfr.join(";"));
1947         }
1948     }
1949
1950     updateKeyframes(effect);
1951     update();
1952 }
1953
1954 void ClipItem::updateKeyframes(QDomElement effect)
1955 {
1956     m_keyframes.clear();
1957     QLocale locale;
1958     // parse keyframes
1959     QDomNodeList params = effect.elementsByTagName("parameter");
1960     QDomElement e = params.item(m_visibleParam).toElement();
1961     if (e.attribute("intimeline") != "1") {
1962         setSelectedEffect(m_selectedEffect);
1963         return;
1964     }
1965     m_limitedKeyFrames = e.attribute("type") == "keyframe";
1966     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1967     foreach(const QString &str, keyframes) {
1968         int pos = str.section(':', 0, 0).toInt();
1969         double val = locale.toDouble(str.section(':', 1, 1));
1970         m_keyframes[pos] = val;
1971     }
1972     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1973 }
1974
1975 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1976 {
1977     if (isAudioOnly())
1978         return m_clip->audioProducer(track);
1979     else if (isVideoOnly())
1980         return m_clip->videoProducer(track);
1981     else
1982         return m_clip->getProducer(trackSpecific ? track : -1);
1983 }
1984
1985 QMap<int, QDomElement> ClipItem::adjustEffectsToDuration(int width, int height, ItemInfo oldInfo)
1986 {
1987     QMap<int, QDomElement> effects;
1988     for (int i = 0; i < m_effectList.count(); i++) {
1989         QDomElement effect = m_effectList.at(i);
1990
1991         if (effect.attribute("id").startsWith("fade")) {
1992             QString id = effect.attribute("id");
1993             int in = EffectsList::parameter(effect, "in").toInt();
1994             int out = EffectsList::parameter(effect, "out").toInt();
1995             int clipEnd = (cropStart() + cropDuration()).frames(m_fps) - 1;
1996             if (id == "fade_from_black" || id == "fadein") {
1997                 if (in != cropStart().frames(m_fps)) {
1998                     effects[i] = effect.cloneNode().toElement();
1999                     int duration = out - in;
2000                     in = cropStart().frames(m_fps);
2001                     out = in + duration;
2002                     EffectsList::setParameter(effect, "in", QString::number(in));
2003                     EffectsList::setParameter(effect, "out", QString::number(out));
2004                 }
2005                 if (out > clipEnd) {
2006                     if (!effects.contains(i))
2007                         effects[i] = effect.cloneNode().toElement();
2008                     EffectsList::setParameter(effect, "out", QString::number(clipEnd));
2009                 }
2010                 if (effects.contains(i)) {
2011                     setFadeIn(out - in);
2012                 }
2013             } else {
2014                 if (out != clipEnd) {
2015                     effects[i] = effect.cloneNode().toElement();
2016                     int diff = out - clipEnd;
2017                     in = qMax(in - diff, (int) cropStart().frames(m_fps));
2018                     out -= diff;
2019                     EffectsList::setParameter(effect, "in", QString::number(in));
2020                     EffectsList::setParameter(effect, "out", QString::number(out));
2021                 }
2022                 if (in < cropStart().frames(m_fps)) {
2023                     if (!effects.contains(i))
2024                         effects[i] = effect.cloneNode().toElement();
2025                     EffectsList::setParameter(effect, "in", QString::number((int) cropStart().frames(m_fps)));
2026                 }
2027                 if (effects.contains(i))
2028                     setFadeOut(out - in);
2029             }
2030             continue;
2031         } else if (effect.attribute("id") == "freeze" && cropStart() != oldInfo.cropStart) {
2032             effects[i] = effect.cloneNode().toElement();
2033             int diff = (oldInfo.cropStart - cropStart()).frames(m_fps);
2034             int frame = EffectsList::parameter(effect, "frame").toInt();
2035             EffectsList::setParameter(effect, "frame", QString::number(frame - diff));
2036             continue;
2037         } else if (effect.attribute("id") == "pan_zoom") {
2038             effect.setAttribute("in", cropStart().frames(m_fps));
2039             effect.setAttribute("out", (cropStart() + cropDuration()).frames(m_fps) - 1);
2040         }
2041
2042         QDomNodeList params = effect.elementsByTagName("parameter");
2043         for (int j = 0; j < params.count(); j++) {
2044             QDomElement param = params.item(j).toElement();
2045
2046             QString type = param.attribute("type");
2047             if (type == "geometry" && !param.hasAttribute("fixed")) {
2048                 if (!effects.contains(i))
2049                     effects[i] = effect.cloneNode().toElement();
2050                 updateGeometryKeyframes(effect, j, width, height, oldInfo);
2051             } else if (type == "simplekeyframe" || type == "keyframe") {
2052                 if (!effects.contains(i))
2053                     effects[i] = effect.cloneNode().toElement();
2054                 updateNormalKeyframes(param, oldInfo);
2055 #ifdef USE_QJSON
2056             } else if (type == "roto-spline") {
2057                 if (!effects.contains(i))
2058                     effects[i] = effect.cloneNode().toElement();
2059                 QString value = param.attribute("value");
2060                 if (adjustRotoDuration(&value, cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1))
2061                     param.setAttribute("value", value);
2062 #endif    
2063             }
2064         }
2065     }
2066     return effects;
2067 }
2068
2069 bool ClipItem::updateNormalKeyframes(QDomElement parameter, ItemInfo oldInfo)
2070 {
2071     int in = cropStart().frames(m_fps);
2072     int out = (cropStart() + cropDuration()).frames(m_fps) - 1;
2073     int oldin = oldInfo.cropStart.frames(m_fps);
2074     QLocale locale;
2075     bool keyFrameUpdated = false;
2076
2077     const QStringList data = parameter.attribute("keyframes").split(';', QString::SkipEmptyParts);
2078     QMap <int, double> keyframes;
2079     foreach (QString keyframe, data) {
2080         int keyframepos = keyframe.section(':', 0, 0).toInt();
2081         // if keyframe was at clip start, update it
2082         if (keyframepos == oldin) {
2083             keyframepos = in;
2084             keyFrameUpdated = true;
2085         }
2086         keyframes[keyframepos] = locale.toDouble(keyframe.section(':', 1, 1));
2087     }
2088
2089
2090     QMap<int, double>::iterator i = keyframes.end();
2091     int lastPos = -1;
2092     double lastValue = 0;
2093     qreal relPos;
2094
2095     /*
2096      * Take care of resize from start
2097      */
2098     bool startFound = false;
2099     while (i-- != keyframes.begin()) {
2100         if (i.key() < in && !startFound) {
2101             startFound = true;
2102             if (lastPos < 0) {
2103                 keyframes[in] = i.value();
2104             } else {
2105                 relPos = (in - i.key()) / (qreal)(lastPos - i.key() + 1);
2106                 keyframes[in] = i.value() + (lastValue - i.value()) * relPos;
2107             }
2108         }
2109         lastPos = i.key();
2110         lastValue = i.value();
2111         if (startFound)
2112             i = keyframes.erase(i);
2113     }
2114
2115     /*
2116      * Take care of resize from end
2117      */
2118     i = keyframes.begin();
2119     lastPos = -1;
2120     bool endFound = false;
2121     while (i != keyframes.end()) {
2122         if (i.key() > out && !endFound) {
2123             endFound = true;
2124             if (lastPos < 0) {
2125                 keyframes[out] = i.value();
2126             } else {
2127                 relPos = (out - lastPos) / (qreal)(i.key() - lastPos + 1);
2128                 keyframes[out] = lastValue + (i.value() - lastValue) * relPos;
2129             }
2130          }
2131         lastPos = i.key();
2132         lastValue = i.value();
2133         if (endFound)
2134             i = keyframes.erase(i);
2135         else
2136             ++i;
2137     }
2138
2139     if (startFound || endFound || keyFrameUpdated) {
2140         QString newkfr;
2141         QMap<int, double>::const_iterator k = keyframes.constBegin();
2142         while (k != keyframes.constEnd()) {
2143             newkfr.append(QString::number(k.key()) + ':' + QString::number(qRound(k.value())) + ';');
2144             ++k;
2145         }
2146         parameter.setAttribute("keyframes", newkfr);
2147         return true;
2148     }
2149
2150     return false;
2151 }
2152
2153 void ClipItem::updateGeometryKeyframes(QDomElement effect, int paramIndex, int width, int height, ItemInfo oldInfo)
2154 {
2155     QDomElement param = effect.elementsByTagName("parameter").item(paramIndex).toElement();
2156     int offset = oldInfo.cropStart.frames(m_fps);
2157     QString data = param.attribute("value");
2158     if (offset > 0) {
2159         QStringList kfrs = data.split(';');
2160         data.clear();
2161         foreach (const QString &keyframe, kfrs) {
2162             if (keyframe.contains('=')) {
2163                 int pos = keyframe.section('=', 0, 0).toInt();
2164                 pos += offset;
2165                 data.append(QString::number(pos) + '=' + keyframe.section('=', 1) + ";");
2166             }
2167             else data.append(keyframe + ';');
2168         }
2169     }
2170     Mlt::Geometry geometry(data.toUtf8().data(), oldInfo.cropDuration.frames(m_fps), width, height);
2171     param.setAttribute("value", geometry.serialise(cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1));
2172 }
2173
2174 void ClipItem::slotGotThumbsCache()
2175 {
2176     disconnect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
2177     update();
2178 }
2179
2180
2181 #include "clipitem.moc"
2182