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