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