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