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