]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Merge branch 'master' of git://anongit.kde.org/kdenlive
[kdenlive] / src / clipitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "clipitem.h"
22 #include "customtrackview.h"
23 #include "customtrackscene.h"
24 #include "renderer.h"
25 #include "docclipbase.h"
26 #include "transition.h"
27 #include "kdenlivesettings.h"
28 #include "kthumb.h"
29 #include "profilesdialog.h"
30 #ifdef USE_QJSON
31 #include "rotoscoping/rotowidget.h"
32 #endif
33
34 #include <KDebug>
35 #include <KIcon>
36
37 #include <QPainter>
38 #include <QTimer>
39 #include <QStyleOptionGraphicsItem>
40 #include <QGraphicsScene>
41 #include <QMimeData>
42
43 static int FRAME_SIZE;
44
45 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, double speed, int strobe, int frame_width, bool generateThumbs) :
46         AbstractClipItem(info, QRectF(), fps),
47         m_clip(clip),
48         m_startFade(0),
49         m_endFade(0),
50         m_audioOnly(false),
51         m_videoOnly(false),
52         m_startPix(QPixmap()),
53         m_endPix(QPixmap()),
54         m_hasThumbs(false),
55         m_selectedEffect(-1),
56         m_timeLine(0),
57         m_startThumbRequested(false),
58         m_endThumbRequested(false),
59         //m_hover(false),
60         m_speed(speed),
61         m_strobe(strobe),
62         m_framePixelWidth(0),
63         m_limitedKeyFrames(false)
64 {
65     setZValue(2);
66     m_effectList = EffectsList(true);
67     FRAME_SIZE = frame_width;
68     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (double) itemHeight());
69     setPos(info.startPos.frames(fps), (double)(info.track * KdenliveSettings::trackheight()) + 1 + itemOffset());
70
71     // set speed independant info
72     if (m_speed <= 0 && m_speed > -1)
73         m_speed = -1.0;
74     m_speedIndependantInfo = m_info;
75     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
76     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
77
78     m_videoPix = KIcon("kdenlive-show-video").pixmap(QSize(16, 16));
79     m_audioPix = KIcon("kdenlive-show-audio").pixmap(QSize(16, 16));
80
81     if (m_speed == 1.0)
82         m_clipName = m_clip->name();
83     else
84         m_clipName = m_clip->name() + " - " + QString::number(m_speed * 100, 'f', 0) + '%';
85
86     m_producer = m_clip->getId();
87     m_clipType = m_clip->clipType();
88     //m_cropStart = info.cropStart;
89     m_maxDuration = m_clip->maxDuration();
90     setAcceptDrops(true);
91     m_audioThumbReady = m_clip->audioThumbCreated();
92     //setAcceptsHoverEvents(true);
93     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , 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.at(i);
164             QString effectId = effect.attribute("id");
165             // check if it is a fade effect
166             QDomNodeList params = effect.elementsByTagName("parameter");
167             int fade = 0;
168             for (int j = 0; j < params.count(); j++) {
169                 QDomElement e = params.item(j).toElement();
170                 if (!e.isNull()) {
171                     if (effectId == "fadein") {
172                         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
173                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
174                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
175                         } else {
176                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
177                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
178                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
179                         }
180                     } else if (effectId == "fade_from_black") {
181                         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
182                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
183                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
184                         } else {
185                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
186                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
187                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
188                         }
189                     } else if (effectId == "fadeout") {
190                         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
191                             if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
192                             else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
193                         } else {
194                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
195                             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
196                             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
197                         }
198                     } else if (effectId == "fade_to_black") {
199                         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
200                             if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
201                             else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
202                         } else {
203                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
204                             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
205                             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
206                         }
207                     }
208                 }
209             }
210             if (fade > 0)
211                 m_startFade = fade;
212             else if (fade < 0)
213                 m_endFade = -fade;
214         }
215         setSelectedEffect(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
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 = m_effectList.at(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 = effectAtIndex(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 = m_effectList.at(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 = getEffectAtIndex(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 effectAtIndex(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() + rect.width() / 2) && 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 ((pos.x() >= rect.x() + rect.width() / 2) && (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::effect(int ix) const
1363 {
1364     if (ix >= m_effectList.count() || ix < 0) return QDomElement();
1365     return m_effectList.at(ix).cloneNode().toElement();
1366 }
1367
1368 QDomElement ClipItem::effectAtIndex(int ix) const
1369 {
1370     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1371     return m_effectList.itemFromIndex(ix).cloneNode().toElement();
1372 }
1373
1374 QDomElement ClipItem::getEffectAtIndex(int ix) const
1375 {
1376     if (ix > m_effectList.count() || ix <= 0) return QDomElement();
1377     return m_effectList.itemFromIndex(ix);
1378 }
1379
1380 void ClipItem::updateEffect(QDomElement effect)
1381 {
1382     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1383     m_effectList.updateEffect(effect);
1384     m_effectNames = m_effectList.effectNames().join(" / ");
1385     QString id = effect.attribute("id");
1386     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1387         update();
1388     else {
1389         QRectF r = boundingRect();
1390         r.setHeight(20);
1391         update(r);
1392     }
1393 }
1394
1395 void ClipItem::enableEffects(QList <int> indexes, bool disable)
1396 {
1397     m_effectList.enableEffects(indexes, disable);
1398 }
1399
1400 bool ClipItem::moveEffect(QDomElement effect, int ix)
1401 {
1402     if (ix <= 0 || ix > (m_effectList.count()) || effect.isNull()) {
1403         kDebug() << "Invalid effect index: " << ix;
1404         return false;
1405     }
1406     m_effectList.removeAt(effect.attribute("kdenlive_ix").toInt());
1407     effect.setAttribute("kdenlive_ix", ix);
1408     m_effectList.insert(effect);
1409     m_effectNames = m_effectList.effectNames().join(" / ");
1410     QString id = effect.attribute("id");
1411     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1412         update();
1413     else {
1414         QRectF r = boundingRect();
1415         r.setHeight(20);
1416         update(r);
1417     }
1418     return true;
1419 }
1420
1421 EffectsParameterList ClipItem::addEffect(QDomElement effect, bool /*animate*/)
1422 {
1423     bool needRepaint = false;
1424     QLocale locale;
1425     int ix;
1426     QDomElement insertedEffect;
1427     if (!effect.hasAttribute("kdenlive_ix")) {
1428         // effect dropped from effect list
1429         ix = effectsCounter();
1430     } else ix = effect.attribute("kdenlive_ix").toInt();
1431     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1432         needRepaint = true;
1433         insertedEffect = m_effectList.insert(effect);
1434     } else insertedEffect = m_effectList.append(effect);
1435     
1436     // Update index to the real one
1437     effect.setAttribute("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1438     
1439     EffectsParameterList parameters;
1440     parameters.addParam("tag", insertedEffect.attribute("tag"));
1441     parameters.addParam("kdenlive_ix", insertedEffect.attribute("kdenlive_ix"));
1442     if (insertedEffect.hasAttribute("src")) parameters.addParam("src", insertedEffect.attribute("src"));
1443     if (insertedEffect.hasAttribute("disable")) parameters.addParam("disable", insertedEffect.attribute("disable"));
1444
1445     QString effectId = insertedEffect.attribute("id");
1446     if (effectId.isEmpty()) effectId = insertedEffect.attribute("tag");
1447     parameters.addParam("id", effectId);
1448
1449     // special case: the affine effect needs in / out points
1450
1451     QDomNodeList params = insertedEffect.elementsByTagName("parameter");
1452     int fade = 0;
1453     bool needInOutSync = false;
1454     for (int i = 0; i < params.count(); i++) {
1455         QDomElement e = params.item(i).toElement();
1456         if (!e.isNull()) {
1457             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1458                 // Effects with a geometry parameter need to sync in / out with parent clip
1459                 needInOutSync = true;
1460             }
1461             if (e.attribute("type") == "simplekeyframe") {
1462                 QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1463                 double factor = locale.toDouble(e.attribute("factor", "1"));
1464                 double offset = e.attribute("offset", "0").toDouble();
1465                 if (factor != 1 || offset != 0) {
1466                     for (int j = 0; j < values.count(); j++) {
1467                         QString pos = values.at(j).section(':', 0, 0);
1468                         double val = (locale.toDouble(values.at(j).section(':', 1, 1)) - offset) / factor;
1469                         values[j] = pos + "=" + locale.toString(val);
1470                     }
1471                 }
1472                 parameters.addParam(e.attribute("name"), values.join(";"));
1473                 /*parameters.addParam("max", e.attribute("max"));
1474                 parameters.addParam("min", e.attribute("min"));
1475                 parameters.addParam("factor", );*/
1476             } else if (e.attribute("type") == "keyframe") {
1477                 parameters.addParam("keyframes", e.attribute("keyframes"));
1478                 parameters.addParam("max", e.attribute("max"));
1479                 parameters.addParam("min", e.attribute("min"));
1480                 parameters.addParam("factor", e.attribute("factor", "1"));
1481                 parameters.addParam("offset", e.attribute("offset", "0"));
1482                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1483                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1484             } else if (e.attribute("factor", "1") == "1" && e.attribute("offset", "0") == "0") {
1485                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1486
1487                 // check if it is a fade effect
1488                 if (effectId == "fadein") {
1489                     needRepaint = true;
1490                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1491                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1492                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1493                     } else {
1494                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1495                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1496                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1497                     }
1498                 } else if (effectId == "fade_from_black") {
1499                     needRepaint = true;
1500                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1501                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1502                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1503                     } else {
1504                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1505                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1506                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1507                     }
1508                 } else if (effectId == "fadeout") {
1509                     needRepaint = true;
1510                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1511                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1512                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1513                     } else {
1514                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1515                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1516                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1517                     }
1518                 } else if (effectId == "fade_to_black") {
1519                     needRepaint = true;
1520                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1521                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1522                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1523                     } else {
1524                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1525                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1526                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1527                     }
1528                 }
1529             } else {
1530                 double fact;
1531                 if (e.attribute("factor").contains('%')) {
1532                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1533                 } else {
1534                     fact = locale.toDouble(e.attribute("factor", "1"));
1535                 }
1536                 double offset = e.attribute("offset", "0").toDouble();
1537                 parameters.addParam(e.attribute("name"), locale.toString((locale.toDouble(e.attribute("value")) - offset) / fact));
1538             }
1539         }
1540     }
1541     if (needInOutSync) {
1542         parameters.addParam("in", QString::number(cropStart().frames(m_fps)));
1543         parameters.addParam("out", QString::number((cropStart() + cropDuration()).frames(m_fps) - 1));
1544         parameters.addParam("_sync_in_out", "1");
1545     }
1546     m_effectNames = m_effectList.effectNames().join(" / ");
1547     if (fade > 0) m_startFade = fade;
1548     else if (fade < 0) m_endFade = -fade;
1549
1550     if (m_selectedEffect == -1) {
1551         setSelectedEffect(0);
1552     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1553     if (needRepaint) update(boundingRect());
1554     /*if (animate) {
1555         flashClip();
1556     } */
1557     else { /*if (!needRepaint) */
1558         QRectF r = boundingRect();
1559         r.setHeight(20);
1560         update(r);
1561     }
1562     return parameters;
1563 }
1564
1565 void ClipItem::deleteEffect(QString index)
1566 {
1567     bool needRepaint = false;
1568     int ix = index.toInt();
1569
1570     QDomElement effect = m_effectList.itemFromIndex(ix);
1571     QString effectId = effect.attribute("id");
1572     if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1573         (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1574         m_startFade = 0;
1575         needRepaint = true;
1576     } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1577         (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1578         m_endFade = 0;
1579         needRepaint = true;
1580     } else if (EffectsList::hasKeyFrames(effect)) needRepaint = true;
1581     m_effectList.removeAt(ix);
1582     m_effectNames = m_effectList.effectNames().join(" / ");
1583
1584     if (m_effectList.isEmpty() || m_selectedEffect == ix) {
1585         // Current effect was removed
1586         if (ix > m_effectList.count()) {
1587             setSelectedEffect(m_effectList.count());
1588         } else setSelectedEffect(ix);
1589     }
1590     if (needRepaint) update(boundingRect());
1591     else {
1592         QRectF r = boundingRect();
1593         r.setHeight(20);
1594         update(r);
1595     }
1596     //if (!m_effectList.isEmpty()) flashClip();
1597 }
1598
1599 double ClipItem::speed() const
1600 {
1601     return m_speed;
1602 }
1603
1604 int ClipItem::strobe() const
1605 {
1606     return m_strobe;
1607 }
1608
1609 void ClipItem::setSpeed(const double speed, const int strobe)
1610 {
1611     m_speed = speed;
1612     if (m_speed <= 0 && m_speed > -1)
1613         m_speed = -1.0;
1614     m_strobe = strobe;
1615     if (m_speed == 1.0) m_clipName = baseClip()->name();
1616     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1617     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1618     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1619     //update();
1620 }
1621
1622 GenTime ClipItem::maxDuration() const
1623 {
1624     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1625 }
1626
1627 GenTime ClipItem::speedIndependantCropStart() const
1628 {
1629     return m_speedIndependantInfo.cropStart;
1630 }
1631
1632 GenTime ClipItem::speedIndependantCropDuration() const
1633 {
1634     return m_speedIndependantInfo.cropDuration;
1635 }
1636
1637
1638 const ItemInfo ClipItem::speedIndependantInfo() const
1639 {
1640     return m_speedIndependantInfo;
1641 }
1642
1643 int ClipItem::nextFreeEffectGroupIndex() const
1644 {
1645     int freeGroupIndex = 0;
1646     for (int i = 0; i < m_effectList.count(); i++) {
1647         QDomElement effect = m_effectList.at(i);
1648         EffectInfo effectInfo;
1649         effectInfo.fromString(effect.attribute("kdenlive_info"));
1650         if (effectInfo.groupIndex >= freeGroupIndex) {
1651             freeGroupIndex = effectInfo.groupIndex + 1;
1652         }
1653     }
1654     return freeGroupIndex;
1655 }
1656
1657 //virtual
1658 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1659 {
1660     if (event->proposedAction() == Qt::CopyAction && scene() && !scene()->views().isEmpty()) {
1661         const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
1662         event->acceptProposedAction();
1663         QDomDocument doc;
1664         doc.setContent(effects, true);
1665         QDomElement e = doc.documentElement();
1666         if (e.tagName() == "effectgroup") {
1667             // dropped an effect group
1668             QDomNodeList effectlist = e.elementsByTagName("effect");
1669             int freeGroupIndex = nextFreeEffectGroupIndex();
1670             EffectInfo effectInfo;
1671             for (int i = 0; i < effectlist.count(); i++) {
1672                 QDomElement effect = effectlist.at(i).toElement();
1673                 effectInfo.fromString(effect.attribute("kdenlive_info"));
1674                 effectInfo.groupIndex = freeGroupIndex;
1675                 effect.setAttribute("kdenlive_info", effectInfo.toString());
1676                 effect.removeAttribute("kdenlive_ix");
1677             }
1678         } else {
1679             // single effect dropped
1680             e.removeAttribute("kdenlive_ix");
1681         }
1682         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1683         if (view) view->slotAddEffect(e, m_info.startPos, track());
1684     }
1685     else return;
1686 }
1687
1688 //virtual
1689 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1690 {
1691     if (isItemLocked()) event->setAccepted(false);
1692     else if (event->mimeData()->hasFormat("kdenlive/effectslist")) {
1693         event->acceptProposedAction();
1694     } else event->setAccepted(false);
1695 }
1696
1697 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1698 {
1699     Q_UNUSED(event)
1700 }
1701
1702 void ClipItem::addTransition(Transition* t)
1703 {
1704     m_transitionsList.append(t);
1705     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1706     QDomDocument doc;
1707     QDomElement e = doc.documentElement();
1708     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1709 }
1710
1711 void ClipItem::setVideoOnly(bool force)
1712 {
1713     m_videoOnly = force;
1714 }
1715
1716 void ClipItem::setAudioOnly(bool force)
1717 {
1718     m_audioOnly = force;
1719     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1720     else {
1721         if (m_clipType == COLOR) {
1722             QString colour = m_clip->getProperty("colour");
1723             colour = colour.replace(0, 2, "#");
1724             m_baseColor = QColor(colour.left(7));
1725         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1726         else m_baseColor = QColor(141, 166, 215);
1727     }
1728     m_audioThumbCachePic.clear();
1729 }
1730
1731 bool ClipItem::isAudioOnly() const
1732 {
1733     return m_audioOnly;
1734 }
1735
1736 bool ClipItem::isVideoOnly() const
1737 {
1738     return m_videoOnly;
1739 }
1740
1741 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1742 {
1743     if (effect.attribute("disable") == "1") return;
1744     QLocale locale;
1745     effect.setAttribute("active_keyframe", pos);
1746     m_editedKeyframe = pos;
1747     QDomNodeList params = effect.elementsByTagName("parameter");
1748     for (int i = 0; i < params.count(); i++) {
1749         QDomElement e = params.item(i).toElement();
1750         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1751             QString kfr = e.attribute("keyframes");
1752             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1753             QStringList newkfr;
1754             bool added = false;
1755             foreach(const QString &str, keyframes) {
1756                 int kpos = str.section(':', 0, 0).toInt();
1757                 double newval = locale.toDouble(str.section(':', 1, 1));
1758                 if (kpos < pos) {
1759                     newkfr.append(str);
1760                 } else if (!added) {
1761                     if (i == m_visibleParam)
1762                         newkfr.append(QString::number(pos) + ":" + QString::number(val));
1763                     else
1764                         newkfr.append(QString::number(pos) + ":" + locale.toString(newval));
1765                     if (kpos > pos) newkfr.append(str);
1766                     added = true;
1767                 } else newkfr.append(str);
1768             }
1769             if (!added) {
1770                 if (i == m_visibleParam)
1771                     newkfr.append(QString::number(pos) + ":" + QString::number(val));
1772                 else
1773                     newkfr.append(QString::number(pos) + ":" + e.attribute("default"));
1774             }
1775             e.setAttribute("keyframes", newkfr.join(";"));
1776         }
1777     }
1778 }
1779
1780 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1781 {
1782     if (effect.attribute("disable") == "1") return;
1783     QLocale locale;
1784     effect.setAttribute("active_keyframe", newpos);
1785     QDomNodeList params = effect.elementsByTagName("parameter");
1786     int start = cropStart().frames(m_fps);
1787     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1788     for (int i = 0; i < params.count(); i++) {
1789         QDomElement e = params.item(i).toElement();
1790         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1791             QString kfr = e.attribute("keyframes");
1792             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1793             QStringList newkfr;
1794             foreach(const QString &str, keyframes) {
1795                 if (str.section(':', 0, 0).toInt() != oldpos) {
1796                     newkfr.append(str);
1797                 } else if (newpos != -1) {
1798                     newpos = qMax(newpos, start);
1799                     newpos = qMin(newpos, end);
1800                     if (i == m_visibleParam)
1801                         newkfr.append(QString::number(newpos) + ":" + locale.toString(value));
1802                     else
1803                         newkfr.append(QString::number(newpos) + ":" + str.section(':', 1, 1));
1804                 }
1805             }
1806             e.setAttribute("keyframes", newkfr.join(";"));
1807         }
1808     }
1809
1810     updateKeyframes(effect);
1811     update();
1812 }
1813
1814 void ClipItem::updateKeyframes(QDomElement effect)
1815 {
1816     m_keyframes.clear();
1817     QLocale locale;
1818     // parse keyframes
1819     QDomNodeList params = effect.elementsByTagName("parameter");
1820     QDomElement e = params.item(m_visibleParam).toElement();
1821     if (e.attribute("intimeline") != "1") {
1822         setSelectedEffect(m_selectedEffect);
1823         return;
1824     }
1825     m_limitedKeyFrames = e.attribute("type") == "keyframe";
1826     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1827     foreach(const QString &str, keyframes) {
1828         int pos = str.section(':', 0, 0).toInt();
1829         double val = locale.toDouble(str.section(':', 1, 1));
1830         m_keyframes[pos] = val;
1831     }
1832     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1833 }
1834
1835 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1836 {
1837     if (isAudioOnly())
1838         return m_clip->audioProducer(track);
1839     else if (isVideoOnly())
1840         return m_clip->videoProducer();
1841     else
1842         return m_clip->getProducer(trackSpecific ? track : -1);
1843 }
1844
1845 QMap<int, QDomElement> ClipItem::adjustEffectsToDuration(int width, int height, ItemInfo oldInfo)
1846 {
1847     QMap<int, QDomElement> effects;
1848     for (int i = 0; i < m_effectList.count(); i++) {
1849         QDomElement effect = m_effectList.at(i);
1850
1851         if (effect.attribute("id").startsWith("fade")) {
1852             QString id = effect.attribute("id");
1853             int in = EffectsList::parameter(effect, "in").toInt();
1854             int out = EffectsList::parameter(effect, "out").toInt();
1855             int clipEnd = (cropStart() + cropDuration()).frames(m_fps) - 1;
1856             if (id == "fade_from_black" || id == "fadein") {
1857                 if (in != cropStart().frames(m_fps)) {
1858                     effects[i] = effect.cloneNode().toElement();
1859                     int duration = out - in;
1860                     in = cropStart().frames(m_fps);
1861                     out = in + duration;
1862                     EffectsList::setParameter(effect, "in", QString::number(in));
1863                     EffectsList::setParameter(effect, "out", QString::number(out));
1864                 }
1865                 if (out > clipEnd) {
1866                     if (!effects.contains(i))
1867                         effects[i] = effect.cloneNode().toElement();
1868                     EffectsList::setParameter(effect, "out", QString::number(clipEnd));
1869                 }
1870                 if (effects.contains(i))
1871                     setFadeIn(out - in);
1872             } else {
1873                 if (out != clipEnd) {
1874                     effects[i] = effect.cloneNode().toElement();
1875                     int diff = out - clipEnd;
1876                     in = qMax(in - diff, (int) cropStart().frames(m_fps));
1877                     out -= diff;
1878                     EffectsList::setParameter(effect, "in", QString::number(in));
1879                     EffectsList::setParameter(effect, "out", QString::number(out));
1880                 }
1881                 if (in < cropStart().frames(m_fps)) {
1882                     if (!effects.contains(i))
1883                         effects[i] = effect.cloneNode().toElement();
1884                     EffectsList::setParameter(effect, "in", QString::number(cropStart().frames(m_fps)));
1885                 }
1886                 if (effects.contains(i))
1887                     setFadeOut(out - in);
1888             }
1889             continue;
1890         } else if (effect.attribute("id") == "freeze" && cropStart() != oldInfo.cropStart) {
1891             effects[i] = effect.cloneNode().toElement();
1892             int diff = (oldInfo.cropStart - cropStart()).frames(m_fps);
1893             int frame = EffectsList::parameter(effect, "frame").toInt();
1894             EffectsList::setParameter(effect, "frame", QString::number(frame - diff));
1895             continue;
1896         }
1897
1898         QDomNodeList params = effect.elementsByTagName("parameter");
1899         for (int j = 0; j < params.count(); j++) {
1900             QDomElement param = params.item(j).toElement();
1901
1902             QString type = param.attribute("type");
1903             if (type == "geometry" && !param.hasAttribute("fixed")) {
1904                 if (!effects.contains(i))
1905                     effects[i] = effect.cloneNode().toElement();
1906                 updateGeometryKeyframes(effect, j, width, height, oldInfo);
1907             } else if (type == "simplekeyframe" || type == "keyframe") {
1908                 if (!effects.contains(i))
1909                     effects[i] = effect.cloneNode().toElement();
1910                 updateNormalKeyframes(param);
1911 #ifdef USE_QJSON
1912             } else if (type == "roto-spline") {
1913                 if (!effects.contains(i))
1914                     effects[i] = effect.cloneNode().toElement();
1915                 QString value = param.attribute("value");
1916                 if (adjustRotoDuration(&value, cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1))
1917                     param.setAttribute("value", value);
1918 #endif    
1919             }
1920         }
1921     }
1922     return effects;
1923 }
1924
1925 bool ClipItem::updateNormalKeyframes(QDomElement parameter)
1926 {
1927     int in = cropStart().frames(m_fps);
1928     int out = (cropStart() + cropDuration()).frames(m_fps) - 1;
1929     QLocale locale;
1930
1931     const QStringList data = parameter.attribute("keyframes").split(';', QString::SkipEmptyParts);
1932     QMap <int, double> keyframes;
1933     foreach (QString keyframe, data)
1934         keyframes[keyframe.section(':', 0, 0).toInt()] = locale.toDouble(keyframe.section(':', 1, 1));
1935
1936
1937     QMap<int, double>::iterator i = keyframes.end();
1938     int lastPos = -1;
1939     double lastValue = 0;
1940     qreal relPos;
1941
1942     /*
1943      * Take care of resize from start
1944      */
1945     bool startFound = false;
1946     while (i-- != keyframes.begin()) {
1947         if (i.key() < in && !startFound) {
1948             startFound = true;
1949             if (lastPos < 0) {
1950                 keyframes[in] = i.value();
1951             } else {
1952                 relPos = (in - i.key()) / (qreal)(lastPos - i.key() + 1);
1953                 keyframes[in] = i.value() + (lastValue - i.value()) * relPos;
1954             }
1955         }
1956         lastPos = i.key();
1957         lastValue = i.value();
1958         if (startFound)
1959             i = keyframes.erase(i);
1960     }
1961
1962     /*
1963      * Take care of resize from end
1964      */
1965     i = keyframes.begin();
1966     lastPos = -1;
1967     bool endFound = false;
1968     while (i != keyframes.end()) {
1969         if (i.key() > out && !endFound) {
1970             endFound = true;
1971             if (lastPos < 0) {
1972                 keyframes[out] = i.value();
1973             } else {
1974                 relPos = (out - lastPos) / (qreal)(i.key() - lastPos + 1);
1975                 keyframes[out] = lastValue + (i.value() - lastValue) * relPos;
1976             }
1977          }
1978         lastPos = i.key();
1979         lastValue = i.value();
1980         if (endFound)
1981             i = keyframes.erase(i);
1982         else
1983             ++i;
1984     }
1985
1986     if (startFound || endFound) {
1987         QString newkfr;
1988         QMap<int, double>::const_iterator k = keyframes.constBegin();
1989         while (k != keyframes.constEnd()) {
1990             newkfr.append(QString::number(k.key()) + ':' + QString::number(qRound(k.value())) + ';');
1991             ++k;
1992         }
1993         parameter.setAttribute("keyframes", newkfr);
1994         return true;
1995     }
1996
1997     return false;
1998 }
1999
2000 void ClipItem::updateGeometryKeyframes(QDomElement effect, int paramIndex, int width, int height, ItemInfo oldInfo)
2001 {
2002
2003     QDomElement param = effect.elementsByTagName("parameter").item(paramIndex).toElement();
2004     int offset = oldInfo.cropStart.frames(m_fps);
2005     QString data = param.attribute("value");
2006     if (offset > 0) {
2007         QStringList kfrs = data.split(';');
2008         data.clear();
2009         foreach (QString keyframe, kfrs) {
2010             if (keyframe.contains('=')) {
2011                 int pos = keyframe.section('=', 0, 0).toInt();
2012                 pos += offset;
2013                 data.append(QString::number(pos) + "=" + keyframe.section('=', 1) + ";");
2014             }
2015             else data.append(keyframe + ";");
2016         }
2017     }
2018     Mlt::Geometry geometry(data.toUtf8().data(), oldInfo.cropDuration.frames(m_fps), width, height);
2019     param.setAttribute("value", geometry.serialise(cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1));
2020 }
2021
2022 void ClipItem::slotGotThumbsCache()
2023 {
2024     disconnect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
2025     update();
2026 }
2027
2028 #include "clipitem.moc"
2029