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