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