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