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