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