]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Fix template title clips & some other title 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         m_cropDuration = m_cropDuration * m_speed;
69     }
70     m_producer = clip->getId();
71     m_clipType = clip->clipType();
72     m_cropStart = info.cropStart;
73     m_maxDuration = clip->maxDuration();
74     setAcceptDrops(true);
75     m_audioThumbReady = clip->audioThumbCreated();
76     //setAcceptsHoverEvents(true);
77     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
78
79     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
80         m_baseColor = QColor(141, 166, 215);
81         m_hasThumbs = true;
82         m_startThumbTimer.setSingleShot(true);
83         connect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
84         m_endThumbTimer.setSingleShot(true);
85         connect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
86
87         connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
88         //connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(getVideoThumbs(int, int)));
89
90         connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
91         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
92         if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
93
94         /*if (m_clip->producer()) {
95             videoThumbProducer.init(this, m_clip->producer(), KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio(), KdenliveSettings::trackheight());
96             slotFetchThumbs();
97         }*/
98     } else if (m_clipType == COLOR) {
99         QString colour = clip->getProperty("colour");
100         colour = colour.replace(0, 2, "#");
101         m_baseColor = QColor(colour.left(7));
102     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
103         m_baseColor = QColor(141, 166, 215);
104         if (m_clipType == TEXT) {
105             connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
106             connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
107         }
108         //m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
109     } else if (m_clipType == AUDIO) {
110         m_baseColor = QColor(141, 215, 166);
111         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
112     }
113 }
114
115
116 ClipItem::~ClipItem()
117 {
118     blockSignals(true);
119     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
120         disconnect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
121         disconnect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
122     }
123     delete m_timeLine;
124 }
125
126 ClipItem *ClipItem::clone(ItemInfo info) const
127 {
128     ClipItem *duplicate = new ClipItem(m_clip, info, m_fps, m_speed, m_strobe);
129     if (m_clipType == IMAGE || m_clipType == TEXT) duplicate->slotSetStartThumb(m_startPix);
130     else {
131         if (info.cropStart == m_cropStart) duplicate->slotSetStartThumb(m_startPix);
132         if (info.cropStart + (info.endPos - info.startPos) == m_cropStart + m_cropDuration) duplicate->slotSetEndThumb(m_endPix);
133     }
134     //kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
135     duplicate->setEffectList(m_effectList);
136     duplicate->setVideoOnly(m_videoOnly);
137     duplicate->setAudioOnly(m_audioOnly);
138     //duplicate->setSpeed(m_speed);
139     return duplicate;
140 }
141
142 void ClipItem::setEffectList(const EffectsList effectList)
143 {
144     m_effectList.clone(effectList);
145     m_effectNames = m_effectList.effectNames().join(" / ");
146     if (!m_effectList.isEmpty()) setSelectedEffect(0);
147 }
148
149 const EffectsList ClipItem::effectList() const
150 {
151     return m_effectList;
152 }
153
154 int ClipItem::selectedEffectIndex() const
155 {
156     return m_selectedEffect;
157 }
158
159 void ClipItem::initEffect(QDomElement effect)
160 {
161     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
162     // not be changed
163     if (effect.attribute("kdenlive_ix").toInt() == 0)
164         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
165     // init keyframes if required
166     QDomNodeList params = effect.elementsByTagName("parameter");
167     for (int i = 0; i < params.count(); i++) {
168         QDomElement e = params.item(i).toElement();
169         kDebug() << "// init eff: " << e.attribute("name");
170
171         // Check if this effect has a variable parameter
172         if (e.attribute("default").startsWith('%')) {
173             double evaluatedValue = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("default"));
174             e.setAttribute("default", evaluatedValue);
175             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
176                 e.setAttribute("value", evaluatedValue);
177             }
178         }
179
180         if (!e.isNull() && e.attribute("type") == "keyframe") {
181             QString def = e.attribute("default");
182             // Effect has a keyframe type parameter, we need to set the values
183             if (e.attribute("keyframes").isEmpty()) {
184                 e.setAttribute("keyframes", QString::number(cropStart().frames(m_fps)) + ':' + def + ';' + QString::number((cropStart() + cropDuration()).frames(m_fps) - 1) + ':' + def);
185                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
186                 break;
187             }
188         }
189     }
190     if (effect.attribute("tag") == "volume" || effect.attribute("tag") == "brightness") {
191         if (effect.attribute("id") == "fadeout" || effect.attribute("id") == "fade_to_black") {
192             int end = (cropDuration() + cropStart()).frames(m_fps);
193             int start = end;
194             if (effect.attribute("id") == "fadeout") {
195                 if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
196                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
197                     if (effectDuration > cropDuration().frames(m_fps)) {
198                         effectDuration = cropDuration().frames(m_fps) / 2;
199                     }
200                     start -= effectDuration;
201                 } else {
202                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
203                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
204                 }
205             } else if (effect.attribute("id") == "fade_to_black") {
206                 if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
207                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
208                     if (effectDuration > cropDuration().frames(m_fps)) {
209                         effectDuration = cropDuration().frames(m_fps) / 2;
210                     }
211                     start -= effectDuration;
212                 } else {
213                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
214                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
215                 }
216             }
217             EffectsList::setParameter(effect, "in", QString::number(start));
218             EffectsList::setParameter(effect, "out", QString::number(end));
219         } else if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fade_from_black") {
220             int start = cropStart().frames(m_fps);
221             int end = start;
222             if (effect.attribute("id") == "fadein") {
223                 if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
224                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
225                     if (effectDuration > cropDuration().frames(m_fps)) {
226                         effectDuration = cropDuration().frames(m_fps) / 2;
227                     }
228                     end += effectDuration;
229                 } else
230                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fade_from_black"), "out").toInt();
231             } else if (effect.attribute("id") == "fade_from_black") {
232                 if (m_effectList.hasEffect(QString(), "fadein") == -1) {
233                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
234                     if (effectDuration > cropDuration().frames(m_fps)) {
235                         effectDuration = cropDuration().frames(m_fps) / 2;
236                     }
237                     end += effectDuration;
238                 } else
239                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fadein"), "out").toInt();
240             }
241             EffectsList::setParameter(effect, "in", QString::number(start));
242             EffectsList::setParameter(effect, "out", QString::number(end));
243         }
244     }
245 }
246
247 bool ClipItem::checkKeyFrames()
248 {
249     bool clipEffectsModified = false;
250     for (int ix = 0; ix < m_effectList.count(); ix ++) {
251         QString kfr = keyframes(ix);
252         if (!kfr.isEmpty()) {
253             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
254             QStringList newKeyFrames;
255             bool cutKeyFrame = false;
256             bool modified = false;
257             int lastPos = -1;
258             double lastValue = -1;
259             int start = m_cropStart.frames(m_fps);
260             int end = (m_cropStart + m_cropDuration).frames(m_fps);
261             foreach(const QString &str, keyframes) {
262                 int pos = str.section(':', 0, 0).toInt();
263                 double val = str.section(':', 1, 1).toDouble();
264                 if (pos - start < 0) {
265                     // a keyframe is defined before the start of the clip
266                     cutKeyFrame = true;
267                 } else if (cutKeyFrame) {
268                     // create new keyframe at clip start, calculate interpolated value
269                     if (pos > start) {
270                         int diff = pos - lastPos;
271                         double ratio = (double)(start - lastPos) / diff;
272                         double newValue = lastValue + (val - lastValue) * ratio;
273                         newKeyFrames.append(QString::number(start) + ':' + QString::number(newValue));
274                         modified = true;
275                     }
276                     cutKeyFrame = false;
277                 }
278                 if (!cutKeyFrame) {
279                     if (pos > end) {
280                         // create new keyframe at clip end, calculate interpolated value
281                         int diff = pos - lastPos;
282                         if (diff != 0) {
283                             double ratio = (double)(end - lastPos) / diff;
284                             double newValue = lastValue + (val - lastValue) * ratio;
285                             newKeyFrames.append(QString::number(end) + ':' + QString::number(newValue));
286                             modified = true;
287                         }
288                         break;
289                     } else {
290                         newKeyFrames.append(QString::number(pos) + ':' + QString::number(val));
291                     }
292                 }
293                 lastPos = pos;
294                 lastValue = val;
295             }
296             if (modified) {
297                 // update KeyFrames
298                 setKeyframes(ix, newKeyFrames.join(";"));
299                 clipEffectsModified = true;
300             }
301         }
302     }
303     return clipEffectsModified;
304 }
305
306 void ClipItem::setKeyframes(const int ix, const QString keyframes)
307 {
308     QDomElement effect = getEffectAt(ix);
309     if (effect.attribute("disabled") == "1") return;
310     QDomNodeList params = effect.elementsByTagName("parameter");
311     for (int i = 0; i < params.count(); i++) {
312         QDomElement e = params.item(i).toElement();
313         if (!e.isNull() && e.attribute("type") == "keyframe") {
314             e.setAttribute("keyframes", keyframes);
315             if (ix == m_selectedEffect) {
316                 m_keyframes.clear();
317                 double max = e.attribute("max").toDouble();
318                 double min = e.attribute("min").toDouble();
319                 m_keyframeFactor = 100.0 / (max - min);
320                 m_keyframeDefault = e.attribute("default").toDouble();
321                 // parse keyframes
322                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
323                 foreach(const QString &str, keyframes) {
324                     int pos = str.section(':', 0, 0).toInt();
325                     double val = str.section(':', 1, 1).toDouble();
326                     m_keyframes[pos] = val;
327                 }
328                 update();
329                 return;
330             }
331             break;
332         }
333     }
334 }
335
336
337 void ClipItem::setSelectedEffect(const int ix)
338 {
339     m_selectedEffect = ix;
340     QDomElement effect = effectAt(m_selectedEffect);
341     if (effect.isNull() == false) {
342         QDomNodeList params = effect.elementsByTagName("parameter");
343         if (effect.attribute("disabled") != "1")
344             for (int i = 0; i < params.count(); i++) {
345                 QDomElement e = params.item(i).toElement();
346                 if (!e.isNull() && e.attribute("type") == "keyframe") {
347                     m_keyframes.clear();
348                     double max = e.attribute("max").toDouble();
349                     double min = e.attribute("min").toDouble();
350                     m_keyframeFactor = 100.0 / (max - min);
351                     m_keyframeDefault = e.attribute("default").toDouble();
352                     // parse keyframes
353                     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
354                     foreach(const QString &str, keyframes) {
355                         int pos = str.section(':', 0, 0).toInt();
356                         double val = str.section(':', 1, 1).toDouble();
357                         m_keyframes[pos] = val;
358                     }
359                     update();
360                     return;
361                 }
362             }
363     }
364     if (!m_keyframes.isEmpty()) {
365         m_keyframes.clear();
366         update();
367     }
368 }
369
370 QString ClipItem::keyframes(const int index)
371 {
372     QString result;
373     QDomElement effect = effectAt(index);
374     QDomNodeList params = effect.elementsByTagName("parameter");
375
376     for (int i = 0; i < params.count(); i++) {
377         QDomElement e = params.item(i).toElement();
378         if (!e.isNull() && e.attribute("type") == "keyframe") {
379             result = e.attribute("keyframes");
380             break;
381         }
382     }
383     return result;
384 }
385
386 void ClipItem::updateKeyframeEffect()
387 {
388     // regenerate xml parameter from the clip keyframes
389     QDomElement effect = getEffectAt(m_selectedEffect);
390     if (effect.attribute("disabled") == "1") return;
391     QDomNodeList params = effect.elementsByTagName("parameter");
392
393     for (int i = 0; i < params.count(); i++) {
394         QDomElement e = params.item(i).toElement();
395         if (!e.isNull() && e.attribute("type") == "keyframe") {
396             QString keyframes;
397             if (m_keyframes.count() > 1) {
398                 QMap<int, int>::const_iterator i = m_keyframes.constBegin();
399                 while (i != m_keyframes.constEnd()) {
400                     keyframes.append(QString::number(i.key()) + ':' + QString::number(i.value()) + ';');
401                     ++i;
402                 }
403             }
404             // Effect has a keyframe type parameter, we need to set the values
405             //kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
406             e.setAttribute("keyframes", keyframes);
407             break;
408         }
409     }
410 }
411
412 QDomElement ClipItem::selectedEffect()
413 {
414     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
415     return effectAt(m_selectedEffect);
416 }
417
418 void ClipItem::resetThumbs(bool clearExistingThumbs)
419 {
420     if (clearExistingThumbs) {
421         m_startPix = QPixmap();
422         m_endPix = QPixmap();
423         m_audioThumbCachePic.clear();
424     }
425     slotFetchThumbs();
426 }
427
428
429 void ClipItem::refreshClip(bool checkDuration)
430 {
431     if (checkDuration && (m_maxDuration != m_clip->maxDuration())) {
432         m_maxDuration = m_clip->maxDuration();
433         if (m_clipType != IMAGE && m_clipType != TEXT && m_clipType != COLOR) {
434             if (m_maxDuration != GenTime() && m_cropStart + m_cropDuration > m_maxDuration) {
435                 // Clip duration changed, make sure to stay in correct range
436                 if (m_cropStart > m_maxDuration) {
437                     m_cropStart = GenTime();
438                     m_cropDuration = qMin(m_cropDuration, m_maxDuration);
439                     updateRectGeometry();
440                 } else {
441                     m_cropDuration = m_maxDuration;
442                     updateRectGeometry();
443                 }
444             }
445         }
446     }
447     if (m_clipType == COLOR) {
448         QString colour = m_clip->getProperty("colour");
449         colour = colour.replace(0, 2, "#");
450         m_baseColor = QColor(colour.left(7));
451     } else resetThumbs(checkDuration);
452 }
453
454 void ClipItem::slotFetchThumbs()
455 {
456     if (m_clipType == IMAGE) {
457         if (m_startPix.isNull()) {
458             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
459             update();
460         }
461         return;
462     }
463
464     if (m_clipType == TEXT) {
465         if (m_startPix.isNull()) slotGetStartThumb();
466         return;
467     }
468
469     if (m_endPix.isNull() && m_startPix.isNull()) {
470         m_startThumbRequested = true;
471         m_endThumbRequested = true;
472         emit getThumb((int)cropStart().frames(m_fps), (int)(cropStart() + cropDuration()).frames(m_fps) - 1);
473     } else {
474         if (m_endPix.isNull()) {
475             slotGetEndThumb();
476         }
477         if (m_startPix.isNull()) {
478             slotGetStartThumb();
479         }
480     }
481     /*
482         if (m_hasThumbs) {
483             if (m_endPix.isNull() && m_startPix.isNull()) {
484                 int frame1 = (int)m_cropStart.frames(m_fps);
485                 int frame2 = (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1;
486                 //videoThumbProducer.setThumbFrames(m_clip->producer(), frame1, frame2);
487                 //videoThumbProducer.start(QThread::LowestPriority);
488             } else {
489                 if (m_endPix.isNull()) slotGetEndThumb();
490                 else slotGetStartThumb();
491             }
492
493         } else if (m_startPix.isNull()) slotGetStartThumb();*/
494 }
495
496 void ClipItem::slotGetStartThumb()
497 {
498     m_startThumbRequested = true;
499     emit getThumb((int)cropStart().frames(m_fps), -1);
500     //videoThumbProducer.setThumbFrames(m_clip->producer(), (int)m_cropStart.frames(m_fps),  - 1);
501     //videoThumbProducer.start(QThread::LowestPriority);
502 }
503
504 void ClipItem::slotGetEndThumb()
505 {
506     m_endThumbRequested = true;
507     emit getThumb(-1, (int)(cropStart() + cropDuration()).frames(m_fps) - 1);
508     //videoThumbProducer.setThumbFrames(m_clip->producer(), -1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
509     //videoThumbProducer.start(QThread::LowestPriority);
510 }
511
512
513 void ClipItem::slotSetStartThumb(QImage img)
514 {
515     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
516         QPixmap pix = QPixmap::fromImage(img);
517         m_startPix = pix;
518         QRectF r = sceneBoundingRect();
519         r.setRight(pix.width() + 2);
520         update(r);
521     }
522 }
523
524 void ClipItem::slotSetEndThumb(QImage img)
525 {
526     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
527         QPixmap pix = QPixmap::fromImage(img);
528         m_endPix = pix;
529         QRectF r = sceneBoundingRect();
530         r.setLeft(r.right() - pix.width() - 2);
531         update(r);
532     }
533 }
534
535 void ClipItem::slotThumbReady(int frame, QPixmap pix)
536 {
537     if (scene() == NULL) return;
538     QRectF r = boundingRect();
539     double width = pix.width() / projectScene()->scale().x();
540     if (m_startThumbRequested && frame == cropStart().frames(m_fps)) {
541         m_startPix = pix;
542         m_startThumbRequested = false;
543         update(r.left(), r.top(), width, pix.height());
544     } else if (m_endThumbRequested && frame == (cropStart() + cropDuration()).frames(m_fps) - 1) {
545         m_endPix = pix;
546         m_endThumbRequested = false;
547         update(r.right() - width, r.y(), width, pix.height());
548     }
549 }
550
551 void ClipItem::slotSetStartThumb(const QPixmap pix)
552 {
553     m_startPix = pix;
554 }
555
556 void ClipItem::slotSetEndThumb(const QPixmap pix)
557 {
558     m_endPix = pix;
559 }
560
561 QPixmap ClipItem::startThumb() const
562 {
563     return m_startPix;
564 }
565
566 QPixmap ClipItem::endThumb() const
567 {
568     return m_endPix;
569 }
570
571 void ClipItem::slotGotAudioData()
572 {
573     m_audioThumbReady = true;
574     if (m_clipType == AV && !isAudioOnly()) {
575         QRectF r = boundingRect();
576         r.setTop(r.top() + r.height() / 2 - 1);
577         update(r);
578     } else update();
579 }
580
581 int ClipItem::type() const
582 {
583     return AVWIDGET;
584 }
585
586 DocClipBase *ClipItem::baseClip() const
587 {
588     return m_clip;
589 }
590
591 QDomElement ClipItem::xml() const
592 {
593     QDomElement xml = m_clip->toXML();
594     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
595     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
596     if (m_audioOnly) xml.setAttribute("audio_only", 1);
597     else if (m_videoOnly) xml.setAttribute("video_only", 1);
598     return xml;
599 }
600
601 int ClipItem::clipType() const
602 {
603     return m_clipType;
604 }
605
606 QString ClipItem::clipName() const
607 {
608     return m_clipName;
609 }
610
611 void ClipItem::setClipName(const QString &name)
612 {
613     m_clipName = name;
614 }
615
616 const QString ClipItem::clipProducer() const
617 {
618     return m_producer;
619 }
620
621 void ClipItem::flashClip()
622 {
623     if (m_timeLine == 0) {
624         m_timeLine = new QTimeLine(750, this);
625         m_timeLine->setUpdateInterval(80);
626         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
627         m_timeLine->setFrameRange(0, 100);
628         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
629     }
630     //m_timeLine->start();
631 }
632
633 void ClipItem::animate(qreal value)
634 {
635     QRectF r = boundingRect();
636     r.setHeight(20);
637     update(r);
638 }
639
640 // virtual
641 void ClipItem::paint(QPainter *painter,
642                      const QStyleOptionGraphicsItem *option,
643                      QWidget *)
644 {
645     QColor paintColor;
646     if (parentItem()) paintColor = QColor(255, 248, 149);
647     else paintColor = m_baseColor;
648     if (isSelected() || (parentItem() && parentItem()->isSelected())) paintColor = paintColor.darker();
649
650     painter->setMatrixEnabled(false);
651     const QRectF mapped = painter->matrix().mapRect(rect()).adjusted(0.5, 0, 0.5, 0);
652     const QRectF exposed = option->exposedRect;
653     painter->setClipRect(mapped);
654     painter->fillRect(mapped, paintColor);
655
656     // draw thumbnails
657     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
658         QPen pen = painter->pen();
659         pen.setColor(QColor(255, 255, 255, 150));
660         const QRectF source(0.0, 0.0, (double) m_startPix.width(), (double) m_startPix.height());
661         painter->setPen(pen);
662         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
663             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
664             painter->drawPixmap(top, m_startPix);
665             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
666             painter->drawLine(l2);
667         } else if (!m_endPix.isNull()) {
668             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
669             painter->drawPixmap(top, m_endPix);
670             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
671             painter->drawLine(l2);
672         }
673         if (!m_startPix.isNull()) {
674             painter->drawPixmap(mapped.topLeft(), m_startPix);
675             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
676             painter->drawLine(l2);
677         }
678         painter->setPen(Qt::black);
679     }
680
681     // draw audio thumbnails
682     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
683
684         double startpixel = exposed.left();
685         if (startpixel < 0)
686             startpixel = 0;
687         double endpixel = exposed.right();
688         if (endpixel < 0)
689             endpixel = 0;
690         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
691
692         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
693         QRectF mappedRect;
694         if (m_clipType == AV && !isAudioOnly()) {
695             mappedRect = mapped;
696             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
697         } else mappedRect = mapped;
698
699         double scale = painter->matrix().m11();
700         int channels = baseClip()->getProperty("channels").toInt();
701         if (scale != m_framePixelWidth)
702             m_audioThumbCachePic.clear();
703         double cropLeft = m_cropStart.frames(m_fps);
704         const int clipStart = mappedRect.x();
705         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
706         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
707         cropLeft = cropLeft * scale;
708
709         if (channels >= 1) {
710             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
711         }
712
713         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
714             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
715                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
716         }
717     }
718
719     // Draw effects names
720     if (!m_effectNames.isEmpty() && mapped.width() > 40) {
721         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
722         QColor bgColor;
723         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
724             qreal value = m_timeLine->currentValue();
725             txtBounding.setWidth(txtBounding.width() * value);
726             bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
727         } else bgColor.setRgb(50, 50, 90, 180);
728
729         QPainterPath rounded;
730         rounded.moveTo(txtBounding.bottomRight());
731         rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
732         rounded.lineTo(txtBounding.topLeft());
733         rounded.lineTo(txtBounding.bottomLeft());
734         painter->fillPath(rounded, bgColor);
735         painter->setPen(Qt::lightGray);
736         painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
737     }
738
739     // Draw clip name
740     QColor frameColor(paintColor.darker());
741     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
742         frameColor = QColor(Qt::red);
743     }
744     frameColor.setAlpha(160);
745
746     const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
747     //painter->fillRect(txtBounding2, frameColor);
748     painter->setBrush(frameColor);
749     painter->setPen(Qt::NoPen);
750     painter->drawRoundedRect(txtBounding2, 3, 3);
751     painter->setBrush(QBrush(Qt::NoBrush));
752
753     //painter->setPen(QColor(0, 0, 0, 180));
754     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
755     if (m_videoOnly) {
756         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
757     } else if (m_audioOnly) {
758         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
759     }
760     painter->setPen(Qt::white);
761     painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
762
763
764     // draw markers
765     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
766     QList < CommentedTime >::Iterator it = markers.begin();
767     GenTime pos;
768     double framepos;
769     QBrush markerBrush(QColor(120, 120, 0, 140));
770     QPen pen = painter->pen();
771     pen.setColor(QColor(255, 255, 255, 200));
772     pen.setStyle(Qt::DotLine);
773     painter->setPen(pen);
774     for (; it != markers.end(); ++it) {
775         pos = (*it).time() / m_speed - cropStart();
776         if (pos > GenTime()) {
777             if (pos > cropDuration()) break;
778             QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
779             QLineF l2 = painter->matrix().map(l);
780             //framepos = scale * pos.frames(m_fps);
781             //QLineF l(framepos, 5, framepos, itemHeight - 5);
782             painter->drawLine(l2);
783             if (KdenliveSettings::showmarkers()) {
784                 framepos = rect().x() + pos.frames(m_fps);
785                 const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
786                 const QRectF r2 = painter->matrix().mapRect(r1);
787                 const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
788                 painter->setBrush(markerBrush);
789                 painter->setPen(Qt::NoPen);
790                 painter->drawRoundedRect(txtBounding3, 3, 3);
791                 painter->setBrush(QBrush(Qt::NoBrush));
792                 painter->setPen(Qt::white);
793                 painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
794             }
795             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
796         }
797     }
798
799     // draw start / end fades
800     QBrush fades;
801     if (isSelected()) {
802         fades = QBrush(QColor(200, 50, 50, 150));
803     } else fades = QBrush(QColor(200, 200, 200, 200));
804
805     if (m_startFade != 0) {
806         QPainterPath fadeInPath;
807         fadeInPath.moveTo(0, 0);
808         fadeInPath.lineTo(0, rect().height());
809         fadeInPath.lineTo(m_startFade, 0);
810         fadeInPath.closeSubpath();
811         QPainterPath f1 = painter->matrix().map(fadeInPath);
812         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
813         /*if (isSelected()) {
814             QLineF l(m_startFade * scale, 0, 0, itemHeight);
815             painter->drawLine(l);
816         }*/
817     }
818     if (m_endFade != 0) {
819         QPainterPath fadeOutPath;
820         fadeOutPath.moveTo(rect().width(), 0);
821         fadeOutPath.lineTo(rect().width(), rect().height());
822         fadeOutPath.lineTo(rect().width() - m_endFade, 0);
823         fadeOutPath.closeSubpath();
824         QPainterPath f1 = painter->matrix().map(fadeOutPath);
825         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
826         /*if (isSelected()) {
827             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
828             painter->drawLine(l);
829         }*/
830     }
831
832
833     painter->setPen(QPen(Qt::lightGray));
834     // draw effect or transition keyframes
835     if (mapped.width() > 20) drawKeyFrames(painter, exposed);
836
837     //painter->setMatrixEnabled(true);
838
839     // draw clip border
840     // expand clip rect to allow correct painting of clip border
841     QPen pen1(frameColor);
842     painter->setPen(pen1);
843     painter->setClipping(false);
844     painter->drawRect(painter->matrix().mapRect(rect()));
845 }
846
847
848 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
849 {
850     if (isItemLocked()) return NONE;
851     const double scale = projectScene()->scale().x();
852     double maximumOffset = 6 / scale;
853     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
854         m_editedKeyframe = mouseOverKeyFrames(pos, maximumOffset);
855         if (m_editedKeyframe != -1) return KEYFRAME;
856     }
857     QRectF rect = sceneBoundingRect();
858     int addtransitionOffset = 10;
859     // Don't allow add transition if track height is very small
860     if (rect.height() < 30) addtransitionOffset = 0;
861
862     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
863         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
864         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
865         return FADEIN;
866     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
867         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
868         return RESIZESTART;
869     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
870         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
871         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
872         return FADEOUT;
873     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
874         setToolTip(i18n("Clip duration: %1s", cropDuration().seconds()));
875         return RESIZEEND;
876     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
877         setToolTip(i18n("Add transition"));
878         return TRANSITIONSTART;
879     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
880         setToolTip(i18n("Add transition"));
881         return TRANSITIONEND;
882     }
883     setToolTip(QString());
884     return MOVE;
885 }
886
887 QList <GenTime> ClipItem::snapMarkers() const
888 {
889     QList < GenTime > snaps;
890     QList < GenTime > markers = baseClip()->snapMarkers();
891     GenTime pos;
892
893     for (int i = 0; i < markers.size(); i++) {
894         pos = markers.at(i) / m_speed - 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 = markers.at(i).time() / m_speed - 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 > m_cropDuration.frames(m_fps)) pos = (int)(m_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 > m_cropDuration.frames(m_fps)) pos = (int)(m_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_startPos = GenTime((int) pos().x(), m_fps);
1194                                 return pos();
1195                             }
1196                         }
1197                     }
1198
1199                     m_track = newTrack;
1200                     m_startPos = GenTime((int) newPos.x(), m_fps);
1201                     return newPos;
1202                 }
1203             }
1204         }
1205         m_track = newTrack;
1206         m_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 m_maxDuration / m_speed;
1494 }
1495
1496 GenTime ClipItem::cropStart() const
1497 {
1498     return m_cropStart / m_speed;
1499 }
1500
1501 GenTime ClipItem::cropDuration() const
1502 {
1503     return m_cropDuration / m_speed;
1504 }
1505
1506 GenTime ClipItem::endPos() const
1507 {
1508     return m_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_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"