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