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