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