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