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