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