]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Prevent crash when deleting a clip while playing:
[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                 if (m_clip && m_clip->thumbProducer()) {
777                     m_clip->thumbProducer()->queryIntraThumbs(left, right);
778                     connect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
779                     QString path = m_clip->fileURL().path() + "_";
780                     for (int i = left; i <= right; i++) {
781                         painter->drawImage(startPos + QPointF(twidth *(i - startOffset), 0), m_clip->thumbProducer()->findCachedThumb(path + QString::number(i)));
782                     }
783                 }
784 #endif
785             }
786         }
787         painter->setPen(Qt::black);
788     }
789
790     // draw audio thumbnails
791     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
792
793         double startpixel = exposed.left();
794         if (startpixel < 0)
795             startpixel = 0;
796         double endpixel = exposed.right();
797         if (endpixel < 0)
798             endpixel = 0;
799         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
800
801         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
802         QRectF mappedRect;
803         if (m_clipType == AV && !isAudioOnly()) {
804             mappedRect = mapped;
805             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
806         } else mappedRect = mapped;
807
808         double scale = painter->matrix().m11();
809         int channels = 0;
810         if (isEnabled() && m_clip) channels = m_clip->getProperty("channels").toInt();
811         if (scale != m_framePixelWidth)
812             m_audioThumbCachePic.clear();
813         double cropLeft = m_info.cropStart.frames(m_fps);
814         const int clipStart = mappedRect.x();
815         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
816         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
817         cropLeft = cropLeft * scale;
818
819
820         if (channels >= 1) {
821             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
822         }
823
824         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
825             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
826                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
827         }
828     }
829
830     // Draw effects names
831     if (!m_effectNames.isEmpty() && mapped.width() > 40) {
832         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
833         QColor bgColor;
834         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
835             qreal value = m_timeLine->currentValue();
836             txtBounding.setWidth(txtBounding.width() * value);
837             bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
838         } else bgColor.setRgb(50, 50, 90, 180);
839
840         QPainterPath rounded;
841         rounded.moveTo(txtBounding.bottomRight());
842         rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
843         rounded.lineTo(txtBounding.topLeft());
844         rounded.lineTo(txtBounding.bottomLeft());
845         painter->fillPath(rounded, bgColor);
846         painter->setPen(Qt::lightGray);
847         painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
848     }
849
850     // Draw clip name
851     QColor frameColor(paintColor.darker());
852     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
853         frameColor = QColor(Qt::red);
854     }
855     frameColor.setAlpha(160);
856
857     const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
858     //painter->fillRect(txtBounding2, frameColor);
859     painter->setBrush(frameColor);
860     painter->setPen(Qt::NoPen);
861     painter->drawRoundedRect(txtBounding2, 3, 3);
862     painter->setBrush(QBrush(Qt::NoBrush));
863
864     //painter->setPen(QColor(0, 0, 0, 180));
865     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
866     if (m_videoOnly) {
867         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
868     } else if (m_audioOnly) {
869         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
870     }
871     painter->setPen(Qt::white);
872     painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
873
874
875     // draw markers
876     if (isEnabled() && m_clip) {
877         QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
878         QList < CommentedTime >::Iterator it = markers.begin();
879         GenTime pos;
880         double framepos;
881         QBrush markerBrush(QColor(120, 120, 0, 140));
882         QPen pen = painter->pen();
883         pen.setColor(QColor(255, 255, 255, 200));
884         pen.setStyle(Qt::DotLine);
885
886         for (; it != markers.end(); ++it) {
887             pos = GenTime((int)((*it).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
888             if (pos > GenTime()) {
889                 if (pos > cropDuration()) break;
890                 QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
891                 QLineF l2 = painter->matrix().map(l);
892                 painter->setPen(pen);
893                 painter->drawLine(l2);
894                 if (KdenliveSettings::showmarkers()) {
895                     framepos = rect().x() + pos.frames(m_fps);
896                     const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
897                     const QRectF r2 = painter->matrix().mapRect(r1);
898                     const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
899                     painter->setBrush(markerBrush);
900                     painter->setPen(Qt::NoPen);
901                     painter->drawRoundedRect(txtBounding3, 3, 3);
902                     painter->setBrush(QBrush(Qt::NoBrush));
903                     painter->setPen(Qt::white);
904                     painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
905                 }
906                 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
907             }
908         }
909     }
910
911     // draw start / end fades
912     QBrush fades;
913     if (isSelected()) {
914         fades = QBrush(QColor(200, 50, 50, 150));
915     } else fades = QBrush(QColor(200, 200, 200, 200));
916
917     if (m_startFade != 0) {
918         QPainterPath fadeInPath;
919         fadeInPath.moveTo(0, 0);
920         fadeInPath.lineTo(0, rect().height());
921         fadeInPath.lineTo(m_startFade, 0);
922         fadeInPath.closeSubpath();
923         QPainterPath f1 = painter->matrix().map(fadeInPath);
924         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
925         /*if (isSelected()) {
926             QLineF l(m_startFade * scale, 0, 0, itemHeight);
927             painter->drawLine(l);
928         }*/
929     }
930     if (m_endFade != 0) {
931         QPainterPath fadeOutPath;
932         fadeOutPath.moveTo(rect().width(), 0);
933         fadeOutPath.lineTo(rect().width(), rect().height());
934         fadeOutPath.lineTo(rect().width() - m_endFade, 0);
935         fadeOutPath.closeSubpath();
936         QPainterPath f1 = painter->matrix().map(fadeOutPath);
937         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
938         /*if (isSelected()) {
939             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
940             painter->drawLine(l);
941         }*/
942     }
943
944
945     painter->setPen(QPen(Qt::lightGray));
946     // draw effect or transition keyframes
947     if (mapped.width() > 20) drawKeyFrames(painter, m_limitedKeyFrames);
948
949     //painter->setMatrixEnabled(true);
950
951     // draw clip border
952     // expand clip rect to allow correct painting of clip border
953     QPen pen1(frameColor);
954     painter->setPen(pen1);
955     painter->setClipping(false);
956     painter->drawRect(painter->matrix().mapRect(rect()));
957 }
958
959
960 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
961 {
962     if (isItemLocked()) return NONE;
963     const double scale = projectScene()->scale().x();
964     double maximumOffset = 6 / scale;
965     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
966         int kf = mouseOverKeyFrames(pos, maximumOffset);
967         if (kf != -1) {
968             m_editedKeyframe = kf;
969             return KEYFRAME;
970         }
971     }
972     QRectF rect = sceneBoundingRect();
973     int addtransitionOffset = 10;
974     // Don't allow add transition if track height is very small
975     if (rect.height() < 30) addtransitionOffset = 0;
976
977     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
978         return FADEIN;
979     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
980         return RESIZESTART;
981     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
982         return FADEOUT;
983     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
984         return RESIZEEND;
985     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
986         return TRANSITIONSTART;
987     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
988         return TRANSITIONEND;
989     }
990
991     return MOVE;
992 }
993
994 int ClipItem::itemHeight()
995 {
996     return KdenliveSettings::trackheight() - 2;
997 }
998
999 QList <GenTime> ClipItem::snapMarkers() const
1000 {
1001     QList < GenTime > snaps;
1002     QList < GenTime > markers = baseClip()->snapMarkers();
1003     GenTime pos;
1004
1005     for (int i = 0; i < markers.size(); i++) {
1006         pos = GenTime((int)(markers.at(i).frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1007         if (pos > GenTime()) {
1008             if (pos > cropDuration()) break;
1009             else snaps.append(pos + startPos());
1010         }
1011     }
1012     return snaps;
1013 }
1014
1015 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
1016 {
1017     QList < CommentedTime > snaps;
1018     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
1019     GenTime pos;
1020
1021     for (int i = 0; i < markers.size(); i++) {
1022         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1023         if (pos > GenTime()) {
1024             if (pos > cropDuration()) break;
1025             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
1026         }
1027     }
1028     return snaps;
1029 }
1030
1031 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
1032 {
1033     QRectF re =  sceneBoundingRect();
1034     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
1035
1036     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
1037     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
1038
1039     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
1040         //kDebug() << "creating " << startCache;
1041         //if (framePixelWidth!=pixelForOneFrame  ||
1042         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
1043             continue;
1044         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
1045             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
1046             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
1047         }
1048         bool fullAreaDraw = pixelForOneFrame < 10;
1049         QMap<int, QPainterPath > positiveChannelPaths;
1050         QMap<int, QPainterPath > negativeChannelPaths;
1051         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
1052         QPen audiopen;
1053         audiopen.setWidth(0);
1054         pixpainter.setPen(audiopen);
1055         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
1056         //pixpainter.drawLine(0,0,100,re.height());
1057         // Bail out, if caller provided invalid data
1058         if (channels <= 0) {
1059             kWarning() << "Unable to draw image with " << channels << "number of channels";
1060             return;
1061         }
1062
1063         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
1064
1065         for (int i = 0; i < channels; i++) {
1066
1067             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1068             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1069         }
1070
1071         for (int samples = 0; samples <= 100; samples++) {
1072             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
1073             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
1074             if (frame < 0 || sample < 0 || sample > 19)
1075                 continue;
1076             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
1077
1078             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
1079
1080                 int y = channelHeight * channel + channelHeight / 2;
1081                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
1082                 if (fullAreaDraw) {
1083                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
1084                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
1085                 } else {
1086                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
1087                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
1088                 }
1089             }
1090             for (int channel = 0; channel < channels ; channel++)
1091                 if (fullAreaDraw && samples == 100) {
1092                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1093                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1094                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1095                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1096                 }
1097
1098         }
1099         pixpainter.setPen(QPen(QColor(0, 0, 0)));
1100         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
1101
1102         for (int i = 0; i < channels; i++) {
1103             if (fullAreaDraw) {
1104                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
1105                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
1106             } else
1107                 pixpainter.drawPath(positiveChannelPaths[i]);
1108         }
1109     }
1110     //audioThumbWasDrawn=true;
1111     m_framePixelWidth = pixelForOneFrame;
1112
1113     //}
1114 }
1115
1116 int ClipItem::fadeIn() const
1117 {
1118     return m_startFade;
1119 }
1120
1121 int ClipItem::fadeOut() const
1122 {
1123     return m_endFade;
1124 }
1125
1126
1127 void ClipItem::setFadeIn(int pos)
1128 {
1129     if (pos == m_startFade) return;
1130     int oldIn = m_startFade;
1131     m_startFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1132     QRectF rect = boundingRect();
1133     update(rect.x(), rect.y(), qMax(oldIn, m_startFade), rect.height());
1134 }
1135
1136 void ClipItem::setFadeOut(int pos)
1137 {
1138     if (pos == m_endFade) return;
1139     int oldOut = m_endFade;
1140     m_endFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1141     QRectF rect = boundingRect();
1142     update(rect.x() + rect.width() - qMax(oldOut, m_endFade), rect.y(), qMax(oldOut, m_endFade), rect.height());
1143
1144 }
1145
1146 void ClipItem::setFades(int in, int out)
1147 {
1148     m_startFade = in;
1149     m_endFade = out;
1150 }
1151
1152 /*
1153 //virtual
1154 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1155 {
1156     //if (e->pos().x() < 20) m_hover = true;
1157     return;
1158     if (isItemLocked()) return;
1159     m_hover = true;
1160     QRectF r = boundingRect();
1161     double width = 35 / projectScene()->scale().x();
1162     double height = r.height() / 2;
1163     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1164     update(r.x(), r.y() + height, width, height);
1165     update(r.right() - width, r.y() + height, width, height);
1166 }
1167
1168 //virtual
1169 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1170 {
1171     if (isItemLocked()) return;
1172     m_hover = false;
1173     QRectF r = boundingRect();
1174     double width = 35 / projectScene()->scale().x();
1175     double height = r.height() / 2;
1176     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1177     update(r.x(), r.y() + height, width, height);
1178     update(r.right() - width, r.y() + height, width, height);
1179 }
1180 */
1181
1182 void ClipItem::resizeStart(int posx, bool /*size*/)
1183 {
1184     bool sizeLimit = false;
1185     if (clipType() != IMAGE && clipType() != COLOR && clipType() != TEXT) {
1186         const int min = (startPos() - cropStart()).frames(m_fps);
1187         if (posx < min) posx = min;
1188         sizeLimit = true;
1189     }
1190
1191     if (posx == startPos().frames(m_fps)) return;
1192     const int previous = cropStart().frames(m_fps);
1193     AbstractClipItem::resizeStart(posx, sizeLimit);
1194
1195     // set speed independant info
1196     m_speedIndependantInfo = m_info;
1197     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1198     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1199
1200     if ((int) cropStart().frames(m_fps) != previous) {
1201         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1202             m_startThumbTimer.start(150);
1203         }
1204     }
1205 }
1206
1207 void ClipItem::resizeEnd(int posx)
1208 {
1209     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1210     if (posx > max && maxDuration() != GenTime()) posx = max;
1211     if (posx == endPos().frames(m_fps)) return;
1212     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1213     const int previous = cropDuration().frames(m_fps);
1214     AbstractClipItem::resizeEnd(posx);
1215
1216     // set speed independant info
1217     m_speedIndependantInfo = m_info;
1218     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1219     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1220
1221     if ((int) cropDuration().frames(m_fps) != previous) {
1222         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1223             m_endThumbTimer.start(150);
1224         }
1225     }
1226 }
1227
1228 //virtual
1229 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1230 {
1231     if (change == QGraphicsItem::ItemSelectedChange) {
1232         if (value.toBool()) setZValue(10);
1233         else setZValue(2);
1234     }
1235     if (change == ItemPositionChange && scene()) {
1236         // calculate new position.
1237         //if (parentItem()) return pos();
1238         QPointF newPos = value.toPointF();
1239         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1240         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1241         xpos = qMax(xpos, 0);
1242         newPos.setX(xpos);
1243         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1244         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1245         newTrack = qMax(newTrack, 0);
1246         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1247         // Only one clip is moving
1248         QRectF sceneShape = rect();
1249         sceneShape.translate(newPos);
1250         QList<QGraphicsItem*> items;
1251         if (projectScene()->editMode() == NORMALEDIT)
1252             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1253         items.removeAll(this);
1254         bool forwardMove = newPos.x() > pos().x();
1255         int offset = 0;
1256         if (!items.isEmpty()) {
1257             for (int i = 0; i < items.count(); i++) {
1258                 if (!items.at(i)->isEnabled()) continue;
1259                 if (items.at(i)->type() == type()) {
1260                     // Collision!
1261                     QPointF otherPos = items.at(i)->pos();
1262                     if ((int) otherPos.y() != (int) pos().y()) {
1263                         return pos();
1264                     }
1265                     if (forwardMove) {
1266                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1267                     } else {
1268                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1269                     }
1270
1271                     if (offset > 0) {
1272                         if (forwardMove) {
1273                             sceneShape.translate(QPointF(-offset, 0));
1274                             newPos.setX(newPos.x() - offset);
1275                         } else {
1276                             sceneShape.translate(QPointF(offset, 0));
1277                             newPos.setX(newPos.x() + offset);
1278                         }
1279                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1280                         subitems.removeAll(this);
1281                         for (int j = 0; j < subitems.count(); j++) {
1282                             if (!subitems.at(j)->isEnabled()) continue;
1283                             if (subitems.at(j)->type() == type()) {
1284                                 // move was not successful, revert to previous pos
1285                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1286                                 return pos();
1287                             }
1288                         }
1289                     }
1290
1291                     m_info.track = newTrack;
1292                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1293
1294                     return newPos;
1295                 }
1296             }
1297         }
1298         m_info.track = newTrack;
1299         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1300         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1301         return newPos;
1302     }
1303     return QGraphicsItem::itemChange(change, value);
1304 }
1305
1306 // virtual
1307 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1308 }*/
1309
1310 int ClipItem::effectsCounter()
1311 {
1312     return effectsCount() + 1;
1313 }
1314
1315 int ClipItem::effectsCount()
1316 {
1317     return m_effectList.count();
1318 }
1319
1320 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1321 {
1322     return m_effectList.hasEffect(tag, id);
1323 }
1324
1325 QStringList ClipItem::effectNames()
1326 {
1327     return m_effectList.effectNames();
1328 }
1329
1330 QDomElement ClipItem::effectAt(int ix) const
1331 {
1332     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1333     return m_effectList.at(ix).cloneNode().toElement();
1334 }
1335
1336 QDomElement ClipItem::getEffectAt(int ix) const
1337 {
1338     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1339     return m_effectList.at(ix);
1340 }
1341
1342 void ClipItem::setEffectAt(int ix, QDomElement effect)
1343 {
1344     if (ix < 0 || ix > (m_effectList.count() - 1) || effect.isNull()) {
1345         kDebug() << "Invalid effect index: " << ix;
1346         return;
1347     }
1348     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1349     effect.setAttribute("kdenlive_ix", ix + 1);
1350     m_effectList.replace(ix, effect);
1351     m_effectNames = m_effectList.effectNames().join(" / ");
1352     QString id = effect.attribute("id");
1353     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1354         update();
1355     else {
1356         QRectF r = boundingRect();
1357         r.setHeight(20);
1358         update(r);
1359     }
1360 }
1361
1362 EffectsParameterList ClipItem::addEffect(const QDomElement effect, bool /*animate*/)
1363 {
1364     bool needRepaint = false;
1365     int ix;
1366     if (!effect.hasAttribute("kdenlive_ix")) {
1367         ix = effectsCounter();
1368     } else ix = effect.attribute("kdenlive_ix").toInt();
1369     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1370         needRepaint = true;
1371         m_effectList.insert(ix - 1, effect);
1372         for (int i = ix; i < m_effectList.count(); i++) {
1373             int index = m_effectList.item(i).attribute("kdenlive_ix").toInt();
1374             if (index >= ix) m_effectList.item(i).setAttribute("kdenlive_ix", index + 1);
1375         }
1376     } else m_effectList.append(effect);
1377     EffectsParameterList parameters;
1378     parameters.addParam("tag", effect.attribute("tag"));
1379     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1380     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1381     if (effect.hasAttribute("disable")) parameters.addParam("disable", effect.attribute("disable"));
1382
1383     QString effectId = effect.attribute("id");
1384     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1385     parameters.addParam("id", effectId);
1386
1387     // special case: the affine effect needs in / out points
1388
1389     QDomNodeList params = effect.elementsByTagName("parameter");
1390     int fade = 0;
1391     bool needInOutSync = false;
1392     for (int i = 0; i < params.count(); i++) {
1393         QDomElement e = params.item(i).toElement();
1394         if (!e.isNull()) {
1395             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1396                 // Effects with a geometry parameter need to sync in / out with parent clip
1397                 needInOutSync = true;
1398             }
1399             if (e.attribute("type") == "simplekeyframe") {
1400                 QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1401                 double factor = e.attribute("factor", "1").toDouble();
1402                 if (factor != 1) {
1403                     for (int j = 0; j < values.count(); j++) {
1404                         QString pos = values.at(j).section(':', 0, 0);
1405                         double val = values.at(j).section(':', 1, 1).toDouble() / factor;
1406                         values[j] = pos + "=" + QString::number(val);
1407                     }
1408                 }
1409                 parameters.addParam(e.attribute("name"), values.join(";"));
1410                 /*parameters.addParam("max", e.attribute("max"));
1411                 parameters.addParam("min", e.attribute("min"));
1412                 parameters.addParam("factor", );*/
1413             } else if (e.attribute("type") == "keyframe") {
1414                 parameters.addParam("keyframes", e.attribute("keyframes"));
1415                 parameters.addParam("max", e.attribute("max"));
1416                 parameters.addParam("min", e.attribute("min"));
1417                 parameters.addParam("factor", e.attribute("factor", "1"));
1418                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1419                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1420             } else if (e.attribute("factor", "1") == "1") {
1421                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1422
1423                 // check if it is a fade effect
1424                 if (effectId == "fadein") {
1425                     needRepaint = true;
1426                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1427                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1428                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1429                     } else {
1430                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1431                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1432                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1433                     }
1434                 } else if (effectId == "fade_from_black") {
1435                     needRepaint = true;
1436                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1437                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1438                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1439                     } else {
1440                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1441                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1442                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1443                     }
1444                 } else if (effectId == "fadeout") {
1445                     needRepaint = true;
1446                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1447                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1448                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1449                     } else {
1450                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1451                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1452                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1453                     }
1454                 } else if (effectId == "fade_to_black") {
1455                     needRepaint = true;
1456                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1457                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1458                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1459                     } else {
1460                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1461                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1462                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1463                     }
1464                 }
1465             } else {
1466                 double fact;
1467                 if (e.attribute("factor").contains('%')) {
1468                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1469                 } else fact = e.attribute("factor", "1").toDouble();
1470                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1471             }
1472         }
1473     }
1474     if (needInOutSync) {
1475         parameters.addParam("in", QString::number(cropStart().frames(m_fps)));
1476         parameters.addParam("out", QString::number((cropStart() + cropDuration()).frames(m_fps) - 1));
1477         parameters.addParam("_sync_in_out", "1");
1478     }
1479     m_effectNames = m_effectList.effectNames().join(" / ");
1480     if (fade > 0) m_startFade = fade;
1481     else if (fade < 0) m_endFade = -fade;
1482
1483     if (m_selectedEffect == -1) {
1484         setSelectedEffect(0);
1485     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1486     if (needRepaint) update(boundingRect());
1487     /*if (animate) {
1488         flashClip();
1489     } */
1490     else { /*if (!needRepaint) */
1491         QRectF r = boundingRect();
1492         r.setHeight(20);
1493         update(r);
1494     }
1495     return parameters;
1496 }
1497
1498 void ClipItem::deleteEffect(QString index)
1499 {
1500     bool needRepaint = false;
1501     QString ix;
1502
1503     for (int i = 0; i < m_effectList.count(); ++i) {
1504         ix = m_effectList.at(i).attribute("kdenlive_ix");
1505         if (ix == index) {
1506             QString effectId = m_effectList.at(i).attribute("id");
1507             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1508                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1509                 m_startFade = 0;
1510                 needRepaint = true;
1511             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1512                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1513                 m_endFade = 0;
1514                 needRepaint = true;
1515             } else if (EffectsList::hasKeyFrames(m_effectList.at(i))) needRepaint = true;
1516             m_effectList.removeAt(i);
1517             i--;
1518         } else if (ix.toInt() > index.toInt()) {
1519             m_effectList.item(i).setAttribute("kdenlive_ix", ix.toInt() - 1);
1520         }
1521     }
1522     m_effectNames = m_effectList.effectNames().join(" / ");
1523
1524     if (m_effectList.isEmpty() || m_selectedEffect + 1 == index.toInt()) {
1525         // Current effect was removed
1526         if (index.toInt() > m_effectList.count() - 1) {
1527             setSelectedEffect(m_effectList.count() - 1);
1528         } else setSelectedEffect(index.toInt());
1529     }
1530     if (needRepaint) update(boundingRect());
1531     else {
1532         QRectF r = boundingRect();
1533         r.setHeight(20);
1534         update(r);
1535     }
1536     //if (!m_effectList.isEmpty()) flashClip();
1537 }
1538
1539 double ClipItem::speed() const
1540 {
1541     return m_speed;
1542 }
1543
1544 int ClipItem::strobe() const
1545 {
1546     return m_strobe;
1547 }
1548
1549 void ClipItem::setSpeed(const double speed, const int strobe)
1550 {
1551     m_speed = speed;
1552     if (m_speed <= 0 && m_speed > -1)
1553         m_speed = -1.0;
1554     m_strobe = strobe;
1555     if (m_speed == 1.0) m_clipName = baseClip()->name();
1556     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1557     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1558     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1559     //update();
1560 }
1561
1562 GenTime ClipItem::maxDuration() const
1563 {
1564     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1565 }
1566
1567 GenTime ClipItem::speedIndependantCropStart() const
1568 {
1569     return m_speedIndependantInfo.cropStart;
1570 }
1571
1572 GenTime ClipItem::speedIndependantCropDuration() const
1573 {
1574     return m_speedIndependantInfo.cropDuration;
1575 }
1576
1577
1578 const ItemInfo ClipItem::speedIndependantInfo() const
1579 {
1580     return m_speedIndependantInfo;
1581 }
1582
1583 //virtual
1584 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1585 {
1586     const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
1587     QDomDocument doc;
1588     doc.setContent(effects, true);
1589     const QDomElement e = doc.documentElement();
1590     if (scene() && !scene()->views().isEmpty()) {
1591         event->accept();
1592         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1593         if (view) view->slotAddEffect(e, m_info.startPos, track());
1594     }
1595 }
1596
1597 //virtual
1598 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1599 {
1600     if (isItemLocked()) event->setAccepted(false);
1601     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1602 }
1603
1604 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1605 {
1606     Q_UNUSED(event)
1607 }
1608
1609 void ClipItem::addTransition(Transition* t)
1610 {
1611     m_transitionsList.append(t);
1612     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1613     QDomDocument doc;
1614     QDomElement e = doc.documentElement();
1615     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1616 }
1617
1618 void ClipItem::setVideoOnly(bool force)
1619 {
1620     m_videoOnly = force;
1621 }
1622
1623 void ClipItem::setAudioOnly(bool force)
1624 {
1625     m_audioOnly = force;
1626     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1627     else {
1628         if (m_clipType == COLOR) {
1629             QString colour = m_clip->getProperty("colour");
1630             colour = colour.replace(0, 2, "#");
1631             m_baseColor = QColor(colour.left(7));
1632         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1633         else m_baseColor = QColor(141, 166, 215);
1634     }
1635     m_audioThumbCachePic.clear();
1636 }
1637
1638 bool ClipItem::isAudioOnly() const
1639 {
1640     return m_audioOnly;
1641 }
1642
1643 bool ClipItem::isVideoOnly() const
1644 {
1645     return m_videoOnly;
1646 }
1647
1648 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1649 {
1650     if (effect.attribute("disable") == "1") return;
1651     effect.setAttribute("active_keyframe", pos);
1652     m_editedKeyframe = pos;
1653     QDomNodeList params = effect.elementsByTagName("parameter");
1654     for (int i = 0; i < params.count(); i++) {
1655         QDomElement e = params.item(i).toElement();
1656         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1657             QString kfr = e.attribute("keyframes");
1658             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1659             QStringList newkfr;
1660             bool added = false;
1661             foreach(const QString &str, keyframes) {
1662                 int kpos = str.section(':', 0, 0).toInt();
1663                 double newval = str.section(':', 1, 1).toDouble();
1664                 if (kpos < pos) {
1665                     newkfr.append(str);
1666                 } else if (!added) {
1667                     if (i == m_visibleParam)
1668                         newkfr.append(QString::number(pos) + ":" + QString::number(val));
1669                     else
1670                         newkfr.append(QString::number(pos) + ":" + QString::number(newval));
1671                     if (kpos > pos) newkfr.append(str);
1672                     added = true;
1673                 } else newkfr.append(str);
1674             }
1675             if (!added) {
1676                 if (i == m_visibleParam)
1677                     newkfr.append(QString::number(pos) + ":" + QString::number(val));
1678                 else
1679                     newkfr.append(QString::number(pos) + ":" + e.attribute("default"));
1680             }
1681             e.setAttribute("keyframes", newkfr.join(";"));
1682         }
1683     }
1684 }
1685
1686 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1687 {
1688     if (effect.attribute("disable") == "1") return;
1689     effect.setAttribute("active_keyframe", newpos);
1690     QDomNodeList params = effect.elementsByTagName("parameter");
1691     int start = cropStart().frames(m_fps);
1692     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1693     for (int i = 0; i < params.count(); i++) {
1694         QDomElement e = params.item(i).toElement();
1695         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1696             QString kfr = e.attribute("keyframes");
1697             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1698             QStringList newkfr;
1699             foreach(const QString &str, keyframes) {
1700                 if (str.section(':', 0, 0).toInt() != oldpos) {
1701                     newkfr.append(str);
1702                 } else if (newpos != -1) {
1703                     newpos = qMax(newpos, start);
1704                     newpos = qMin(newpos, end);
1705                     if (i == m_visibleParam)
1706                         newkfr.append(QString::number(newpos) + ":" + QString::number(value));
1707                     else
1708                         newkfr.append(QString::number(newpos) + ":" + str.section(':', 1, 1));
1709                 }
1710             }
1711             e.setAttribute("keyframes", newkfr.join(";"));
1712         }
1713     }
1714
1715     updateKeyframes(effect);
1716     update();
1717 }
1718
1719 void ClipItem::updateKeyframes(QDomElement effect)
1720 {
1721     m_keyframes.clear();
1722     // parse keyframes
1723     QDomNodeList params = effect.elementsByTagName("parameter");
1724     QDomElement e = params.item(m_visibleParam).toElement();
1725     if (e.attribute("intimeline") != "1") {
1726         setSelectedEffect(m_selectedEffect);
1727         return;
1728     }
1729     m_limitedKeyFrames = e.attribute("type") == "keyframe";
1730     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1731     foreach(const QString &str, keyframes) {
1732         int pos = str.section(':', 0, 0).toInt();
1733         double val = str.section(':', 1, 1).toDouble();
1734         m_keyframes[pos] = val;
1735     }
1736     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1737 }
1738
1739 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1740 {
1741     if (isAudioOnly())
1742         return m_clip->audioProducer(track);
1743     else if (isVideoOnly())
1744         return m_clip->videoProducer();
1745     else
1746         return m_clip->producer(trackSpecific ? track : -1);
1747 }
1748
1749 QMap<int, QDomElement> ClipItem::adjustEffectsToDuration(int width, int height, ItemInfo oldInfo)
1750 {
1751     QMap<int, QDomElement> effects;
1752     for (int i = 0; i < m_effectList.count(); i++) {
1753         QDomElement effect = m_effectList.at(i);
1754
1755         if (effect.attribute("id").startsWith("fade")) {
1756             QString id = effect.attribute("id");
1757             int in = EffectsList::parameter(effect, "in").toInt();
1758             int out = EffectsList::parameter(effect, "out").toInt();
1759             int clipEnd = (cropStart() + cropDuration()).frames(m_fps) - 1;
1760             if (id == "fade_from_black" || id == "fadein") {
1761                 if (in != cropStart().frames(m_fps)) {
1762                     effects[i] = effect.cloneNode().toElement();
1763                     int diff = in - cropStart().frames(m_fps);
1764                     in -= diff;
1765                     out -= diff;
1766                     EffectsList::setParameter(effect, "in", QString::number(in));
1767                     EffectsList::setParameter(effect, "out", QString::number(out));
1768                 }
1769                 if (out > clipEnd) {
1770                     if (!effects.contains(i))
1771                         effects[i] = effect.cloneNode().toElement();
1772                     EffectsList::setParameter(effect, "out", QString::number(clipEnd));
1773                 }
1774                 if (effects.contains(i))
1775                     setFadeIn(out - in);
1776             } else {
1777                 if (out != clipEnd) {
1778                     effects[i] = effect.cloneNode().toElement();
1779                     int diff = out - clipEnd;
1780                     in = qMax(in - diff, (int) cropStart().frames(m_fps));
1781                     out -= diff;
1782                     EffectsList::setParameter(effect, "in", QString::number(in));
1783                     EffectsList::setParameter(effect, "out", QString::number(out));
1784                 }
1785                 if (in < cropStart().frames(m_fps)) {
1786                     if (!effects.contains(i))
1787                         effects[i] = effect.cloneNode().toElement();
1788                     EffectsList::setParameter(effect, "in", QString::number(cropStart().frames(m_fps)));
1789                 }
1790                 if (effects.contains(i))
1791                     setFadeOut(out - in);
1792             }
1793             continue;
1794         } else if (effect.attribute("id") == "freeze" && cropStart() != oldInfo.cropStart) {
1795             effects[i] = effect.cloneNode().toElement();
1796             int diff = (oldInfo.cropStart - cropStart()).frames(m_fps);
1797             int frame = EffectsList::parameter(effect, "frame").toInt();
1798             EffectsList::setParameter(effect, "frame", QString::number(frame - diff));
1799             continue;
1800         }
1801
1802         QDomNodeList params = effect.elementsByTagName("parameter");
1803         for (int j = 0; j < params.count(); j++) {
1804             QDomElement param = params.item(j).toElement();
1805
1806             QString type = param.attribute("type");
1807             if (type == "geometry" && !param.hasAttribute("fixed")) {
1808                 if (!effects.contains(i))
1809                     effects[i] = effect.cloneNode().toElement();
1810                 updateGeometryKeyframes(effect, j, width, height, oldInfo);
1811             } else if (type == "simplekeyframe" || type == "keyframe") {
1812                 if (!effects.contains(i))
1813                     effects[i] = effect.cloneNode().toElement();
1814                 updateNormalKeyframes(param);
1815 #ifdef QJSON
1816             } else if (type == "roto-spline") {
1817                 if (!effects.contains(i))
1818                     effects[i] = effect.cloneNode().toElement();
1819                 QString value = param.attribute("value");
1820                 if (adjustRotoDuration(&value, cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1))
1821                     param.setAttribute("value", value);
1822 #endif    
1823             }
1824         }
1825     }
1826     return effects;
1827 }
1828
1829 bool ClipItem::updateNormalKeyframes(QDomElement parameter)
1830 {
1831     int in = cropStart().frames(m_fps);
1832     int out = (cropStart() + cropDuration()).frames(m_fps) - 1;
1833
1834     const QStringList data = parameter.attribute("keyframes").split(';', QString::SkipEmptyParts);
1835     QMap <int, double> keyframes;
1836     foreach (QString keyframe, data)
1837         keyframes[keyframe.section(':', 0, 0).toInt()] = keyframe.section(':', 1, 1).toDouble();
1838
1839
1840     QMap<int, double>::iterator i = keyframes.end();
1841     int lastPos = -1;
1842     double lastValue = 0;
1843     qreal relPos;
1844
1845     /*
1846      * Take care of resize from start
1847      */
1848     bool startFound = false;
1849     while (i-- != keyframes.begin()) {
1850         if (i.key() < in && !startFound) {
1851             startFound = true;
1852             if (lastPos < 0) {
1853                 keyframes[in] = i.value();
1854             } else {
1855                 relPos = (in - i.key()) / (qreal)(lastPos - i.key() + 1);
1856                 keyframes[in] = i.value() + (lastValue - i.value()) * relPos;
1857             }
1858         }
1859         lastPos = i.key();
1860         lastValue = i.value();
1861         if (startFound)
1862             i = keyframes.erase(i);
1863     }
1864
1865     /*
1866      * Take care of resize from end
1867      */
1868     i = keyframes.begin();
1869     lastPos = -1;
1870     bool endFound = false;
1871     while (i != keyframes.end()) {
1872         if (i.key() > out && !endFound) {
1873             endFound = true;
1874             if (lastPos < 0) {
1875                 keyframes[out] = i.value();
1876             } else {
1877                 relPos = (out - lastPos) / (qreal)(i.key() - lastPos + 1);
1878                 keyframes[out] = lastValue + (i.value() - lastValue) * relPos;
1879             }
1880          }
1881         lastPos = i.key();
1882         lastValue = i.value();
1883         if (endFound)
1884             i = keyframes.erase(i);
1885         else
1886             ++i;
1887     }
1888
1889     if (startFound || endFound) {
1890         QString newkfr;
1891         QMap<int, double>::const_iterator k = keyframes.constBegin();
1892         while (k != keyframes.constEnd()) {
1893             newkfr.append(QString::number(k.key()) + ':' + QString::number(qRound(k.value())) + ';');
1894             ++k;
1895         }
1896         parameter.setAttribute("keyframes", newkfr);
1897         return true;
1898     }
1899
1900     return false;
1901 }
1902
1903 void ClipItem::updateGeometryKeyframes(QDomElement effect, int paramIndex, int width, int height, ItemInfo oldInfo)
1904 {
1905
1906     QDomElement param = effect.elementsByTagName("parameter").item(paramIndex).toElement();
1907     int offset = oldInfo.cropStart.frames(m_fps);
1908     QString data = param.attribute("value");
1909     if (offset > 0) {
1910         QStringList kfrs = data.split(';');
1911         data.clear();
1912         foreach (QString keyframe, kfrs) {
1913             if (keyframe.contains('=')) {
1914                 int pos = keyframe.section('=', 0, 0).toInt();
1915                 pos += offset;
1916                 data.append(QString::number(pos) + "=" + keyframe.section('=', 1) + ";");
1917             }
1918             else data.append(keyframe + ";");
1919         }
1920     }
1921     Mlt::Geometry geometry(data.toUtf8().data(), oldInfo.cropDuration.frames(m_fps), width, height);
1922     param.setAttribute("value", geometry.serialise(cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1));
1923 }
1924
1925 void ClipItem::slotGotThumbsCache()
1926 {
1927     disconnect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
1928     update();
1929 }
1930
1931 #include "clipitem.moc"