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