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