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