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