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