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