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