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