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