]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Merge branch 'master' into next
[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 #ifdef USE_QJSON
31 #include "rotoscoping/rotowidget.h"
32 #endif
33
34 #include <KDebug>
35 #include <KIcon>
36
37 #include <QPainter>
38 #include <QTimer>
39 #include <QStyleOptionGraphicsItem>
40 #include <QGraphicsScene>
41 #include <QMimeData>
42
43 static int FRAME_SIZE;
44
45 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, double speed, int strobe, int frame_width, bool generateThumbs) :
46         AbstractClipItem(info, QRectF(), fps),
47         m_clip(clip),
48         m_startFade(0),
49         m_endFade(0),
50         m_audioOnly(false),
51         m_videoOnly(false),
52         m_startPix(QPixmap()),
53         m_endPix(QPixmap()),
54         m_hasThumbs(false),
55         m_selectedEffect(-1),
56         m_timeLine(0),
57         m_startThumbRequested(false),
58         m_endThumbRequested(false),
59         //m_hover(false),
60         m_speed(speed),
61         m_strobe(strobe),
62         m_framePixelWidth(0),
63         m_limitedKeyFrames(false)
64 {
65     setZValue(2);
66     FRAME_SIZE = frame_width;
67     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (double) itemHeight());
68     setPos(info.startPos.frames(fps), (double)(info.track * KdenliveSettings::trackheight()) + 1 + itemOffset());
69
70     // set speed independant info
71     if (m_speed <= 0 && m_speed > -1)
72         m_speed = -1.0;
73     m_speedIndependantInfo = m_info;
74     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
75     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
76
77     m_videoPix = KIcon("kdenlive-show-video").pixmap(QSize(16, 16));
78     m_audioPix = KIcon("kdenlive-show-audio").pixmap(QSize(16, 16));
79
80     if (m_speed == 1.0)
81         m_clipName = m_clip->name();
82     else
83         m_clipName = m_clip->name() + " - " + QString::number(m_speed * 100, 'f', 0) + '%';
84
85     m_producer = m_clip->getId();
86     m_clipType = m_clip->clipType();
87     //m_cropStart = info.cropStart;
88     m_maxDuration = m_clip->maxDuration();
89     setAcceptDrops(true);
90     m_audioThumbReady = m_clip->audioThumbCreated();
91     //setAcceptsHoverEvents(true);
92     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
93
94     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
95         m_baseColor = QColor(141, 166, 215);
96         if (!m_clip->isPlaceHolder()) {
97             m_hasThumbs = true;
98             m_startThumbTimer.setSingleShot(true);
99             connect(&m_startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
100             m_endThumbTimer.setSingleShot(true);
101             connect(&m_endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
102             connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
103             connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
104             if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
105         }
106
107     } else if (m_clipType == COLOR) {
108         QString colour = m_clip->getProperty("colour");
109         colour = colour.replace(0, 2, "#");
110         m_baseColor = QColor(colour.left(7));
111     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
112         m_baseColor = QColor(141, 166, 215);
113         if (m_clipType == TEXT) {
114             connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
115         }
116         //m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
117     } else if (m_clipType == AUDIO) {
118         m_baseColor = QColor(141, 215, 166);
119         connect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
120     }
121 }
122
123
124 ClipItem::~ClipItem()
125 {
126     blockSignals(true);
127     if (scene()) scene()->removeItem(this);
128     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
129         //disconnect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QImage)), this, SLOT(slotThumbReady(int, QImage)));
130         //disconnect(m_clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
131     }
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, m_strobe, FRAME_SIZE);
138     if (m_clipType == IMAGE || m_clipType == TEXT) duplicate->slotSetStartThumb(m_startPix);
139     else if (m_clipType != COLOR) {
140         if (info.cropStart == m_info.cropStart) duplicate->slotSetStartThumb(m_startPix);
141         if (info.cropStart + (info.endPos - info.startPos) == m_info.cropStart + m_info.cropDuration) {
142             duplicate->slotSetEndThumb(m_endPix);
143         }
144     }
145     //kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
146     duplicate->setEffectList(m_effectList);
147     duplicate->setVideoOnly(m_videoOnly);
148     duplicate->setAudioOnly(m_audioOnly);
149     duplicate->setFades(fadeIn(), fadeOut());
150     //duplicate->setSpeed(m_speed);
151     return duplicate;
152 }
153
154 void ClipItem::setEffectList(const EffectsList effectList)
155 {
156     m_effectList.clone(effectList);
157     m_effectNames = m_effectList.effectNames().join(" / ");
158     if (!m_effectList.isEmpty()) {
159         for (int i = 0; i < m_effectList.count(); i++) {
160             QString effectId = m_effectList.item(i).attribute("id");
161             // check if it is a fade effect
162             QDomNodeList params = m_effectList.item(i).elementsByTagName("parameter");
163             int fade = 0;
164             for (int j = 0; j < params.count(); j++) {
165                 QDomElement e = params.item(j).toElement();
166                 if (!e.isNull()) {
167                     if (effectId == "fadein") {
168                         if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
169                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
170                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
171                         } else {
172                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
173                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
174                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
175                         }
176                     } else if (effectId == "fade_from_black") {
177                         if (m_effectList.hasEffect(QString(), "fadein") == -1) {
178                             if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
179                             else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
180                         } else {
181                             QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
182                             if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
183                             else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
184                         }
185                     } else if (effectId == "fadeout") {
186                         if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
187                             if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
188                             else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
189                         } else {
190                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
191                             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
192                             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
193                         }
194                     } else if (effectId == "fade_to_black") {
195                         if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
196                             if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
197                             else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
198                         } else {
199                             QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
200                             if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
201                             else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
202                         }
203                     }
204                 }
205             }
206             if (fade > 0)
207                 m_startFade = fade;
208             else if (fade < 0)
209                 m_endFade = -fade;
210         }
211         setSelectedEffect(0);
212     }
213 }
214
215 const EffectsList ClipItem::effectList() const
216 {
217     return m_effectList;
218 }
219
220 int ClipItem::selectedEffectIndex() const
221 {
222     return m_selectedEffect;
223 }
224
225 void ClipItem::initEffect(QDomElement effect, int diff)
226 {
227     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
228     // not be changed
229     if (effect.attribute("kdenlive_ix").toInt() == 0)
230         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
231
232     if (effect.attribute("id") == "freeze" && diff > 0) {
233         EffectsList::setParameter(effect, "frame", QString::number(diff));
234     }
235
236     // Init parameter value & keyframes if required
237     QDomNodeList params = effect.elementsByTagName("parameter");
238     for (int i = 0; i < params.count(); i++) {
239         QDomElement e = params.item(i).toElement();
240
241         if (e.isNull())
242             continue;
243
244         // Check if this effect has a variable parameter
245         if (e.attribute("default").contains('%')) {
246             double evaluatedValue = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("default"));
247             e.setAttribute("default", evaluatedValue);
248             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
249                 e.setAttribute("value", evaluatedValue);
250             }
251         }
252
253         if (effect.attribute("id") == "crop") {
254             // default use_profile to 1 for clips with proxies to avoid problems when rendering
255             if (e.attribute("name") == "use_profile" && !(m_clip->getProperty("proxy").isEmpty() || m_clip->getProperty("proxy") == "-"))
256                 e.setAttribute("value", "1");
257         }
258
259         if ((e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && e.attribute("keyframes").isEmpty()) {
260             // Effect has a keyframe type parameter, we need to set the values
261             e.setAttribute("keyframes", QString::number(cropStart().frames(m_fps)) + ':' + e.attribute("default"));
262         }
263     }
264     if (effect.attribute("tag") == "volume" || effect.attribute("tag") == "brightness") {
265         if (effect.attribute("id") == "fadeout" || effect.attribute("id") == "fade_to_black") {
266             int end = (cropDuration() + cropStart()).frames(m_fps) - 1;
267             int start = end;
268             if (effect.attribute("id") == "fadeout") {
269                 if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
270                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
271                     if (effectDuration > cropDuration().frames(m_fps)) {
272                         effectDuration = cropDuration().frames(m_fps) / 2;
273                     }
274                     start -= effectDuration;
275                 } else {
276                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
277                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
278                 }
279             } else if (effect.attribute("id") == "fade_to_black") {
280                 if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
281                     int effectDuration = EffectsList::parameter(effect, "in").toInt();
282                     if (effectDuration > cropDuration().frames(m_fps)) {
283                         effectDuration = cropDuration().frames(m_fps) / 2;
284                     }
285                     start -= effectDuration;
286                 } else {
287                     QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
288                     start -= EffectsList::parameter(fadeout, "out").toInt() - EffectsList::parameter(fadeout, "in").toInt();
289                 }
290             }
291             EffectsList::setParameter(effect, "in", QString::number(start));
292             EffectsList::setParameter(effect, "out", QString::number(end));
293         } else if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fade_from_black") {
294             int start = cropStart().frames(m_fps);
295             int end = start;
296             if (effect.attribute("id") == "fadein") {
297                 if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
298                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
299                     if (effectDuration > cropDuration().frames(m_fps)) {
300                         effectDuration = cropDuration().frames(m_fps) / 2;
301                     }
302                     end += effectDuration;
303                 } else
304                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fade_from_black"), "out").toInt();
305             } else if (effect.attribute("id") == "fade_from_black") {
306                 if (m_effectList.hasEffect(QString(), "fadein") == -1) {
307                     int effectDuration = EffectsList::parameter(effect, "out").toInt();
308                     if (effectDuration > cropDuration().frames(m_fps)) {
309                         effectDuration = cropDuration().frames(m_fps) / 2;
310                     }
311                     end += effectDuration;
312                 } else
313                     end += EffectsList::parameter(m_effectList.getEffectByTag(QString(), "fadein"), "out").toInt();
314             }
315             EffectsList::setParameter(effect, "in", QString::number(start));
316             EffectsList::setParameter(effect, "out", QString::number(end));
317         }
318     }
319 }
320
321 bool ClipItem::checkKeyFrames()
322 {
323     bool clipEffectsModified = false;
324     QLocale locale;
325     // go through all effects this clip has
326     for (int ix = 0; ix < m_effectList.count(); ++ix) {
327         QStringList keyframeParams = keyframes(ix);
328         QStringList newKeyFrameParams;
329         bool effModified = false;
330
331         // go through all params which have keyframes
332         foreach(const QString &kfr, keyframeParams) {
333             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
334             QStringList newKeyFrames;
335             bool cutKeyFrame = false;
336             bool modified = false;
337             int lastPos = -1;
338             double lastValue = -1;
339             int start = cropStart().frames(m_fps);
340             int end = (cropStart() + cropDuration()).frames(m_fps);
341
342             // go through all keyframes for one param
343             foreach(const QString &str, keyframes) {
344                 int pos = str.section(':', 0, 0).toInt();
345                 double val = locale.toDouble(str.section(':', 1, 1));
346                 if (pos - start < 0) {
347                     // a keyframe is defined before the start of the clip
348                     cutKeyFrame = true;
349                 } else if (cutKeyFrame) {
350                     // create new keyframe at clip start, calculate interpolated value
351                     if (pos > start) {
352                         int diff = pos - lastPos;
353                         double ratio = (double)(start - lastPos) / diff;
354                         double newValue = lastValue + (val - lastValue) * ratio;
355                         newKeyFrames.append(QString::number(start) + ':' + locale.toString(newValue));
356                         modified = true;
357                     }
358                     cutKeyFrame = false;
359                 }
360                 if (!cutKeyFrame) {
361                     if (pos > end) {
362                         // create new keyframe at clip end, calculate interpolated value
363                         int diff = pos - lastPos;
364                         if (diff != 0) {
365                             double ratio = (double)(end - lastPos) / diff;
366                             double newValue = lastValue + (val - lastValue) * ratio;
367                             newKeyFrames.append(QString::number(end) + ':' + locale.toString(newValue));
368                             modified = true;
369                         }
370                         break;
371                     } else {
372                         newKeyFrames.append(QString::number(pos) + ':' + locale.toString(val));
373                     }
374                 }
375                 lastPos = pos;
376                 lastValue = val;
377             }
378
379             newKeyFrameParams.append(newKeyFrames.join(";"));
380             if (modified)
381                 effModified = true;
382         }
383
384         if (effModified) {
385             // update KeyFrames
386             setKeyframes(ix, newKeyFrameParams);
387             clipEffectsModified = true;
388         }
389     }
390     return clipEffectsModified;
391 }
392
393 void ClipItem::setKeyframes(const int ix, const QStringList keyframes)
394 {
395     QDomElement effect = getEffectAt(ix);
396     if (effect.attribute("disable") == "1") return;
397     QLocale locale;
398     QDomNodeList params = effect.elementsByTagName("parameter");
399     int keyframeParams = 0;
400     for (int i = 0; i < params.count(); i++) {
401         QDomElement e = params.item(i).toElement();
402         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && e.attribute("intimeline") == "1") {
403             e.setAttribute("keyframes", keyframes.at(keyframeParams));
404             if (ix == m_selectedEffect && keyframeParams == 0) {
405                 m_keyframes.clear();
406                 m_visibleParam = i;
407                 double max = locale.toDouble(e.attribute("max"));
408                 double min = locale.toDouble(e.attribute("min"));
409                 m_keyframeFactor = 100.0 / (max - min);
410                 m_keyframeOffset = min;
411                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
412                 m_selectedKeyframe = 0;
413                 // parse keyframes
414                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
415                 foreach(const QString &str, keyframes) {
416                     int pos = str.section(':', 0, 0).toInt();
417                     double val = locale.toDouble(str.section(':', 1, 1));
418                     m_keyframes[pos] = val;
419                 }
420                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
421                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end()) m_editedKeyframe = -1;
422                 update();
423             }
424             ++keyframeParams;
425         }
426     }
427 }
428
429
430 void ClipItem::setSelectedEffect(const int ix)
431 {
432     m_selectedEffect = ix;
433     QLocale locale;
434     QDomElement effect = effectAt(m_selectedEffect);
435     if (!effect.isNull() && effect.attribute("disable") != "1") {
436         QDomNodeList params = effect.elementsByTagName("parameter");
437         for (int i = 0; i < params.count(); i++) {
438             QDomElement e = params.item(i).toElement();
439             if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe") && e.attribute("intimeline") == "1") {
440                 m_keyframes.clear();
441                 m_limitedKeyFrames = e.attribute("type") == "keyframe";
442                 m_visibleParam = i;
443                 double max = locale.toDouble(e.attribute("max"));
444                 double min = locale.toDouble(e.attribute("min"));
445                 m_keyframeFactor = 100.0 / (max - min);
446                 m_keyframeOffset = min;
447                 m_keyframeDefault = locale.toDouble(e.attribute("default"));
448                 m_selectedKeyframe = 0;
449
450                 // parse keyframes
451                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
452                 foreach(const QString &str, keyframes) {
453                     int pos = str.section(':', 0, 0).toInt();
454                     double val = locale.toDouble(str.section(':', 1, 1));
455                     m_keyframes[pos] = val;
456                 }
457                 if (m_keyframes.find(m_editedKeyframe) == m_keyframes.end())
458                     m_editedKeyframe = -1;
459                 update();
460                 return;
461             }
462         }
463     }
464
465     if (!m_keyframes.isEmpty()) {
466         m_keyframes.clear();
467         update();
468     }
469 }
470
471 QStringList ClipItem::keyframes(const int index)
472 {
473     QStringList result;
474     QDomElement effect = effectAt(index);
475     QDomNodeList params = effect.elementsByTagName("parameter");
476
477     for (int i = 0; i < params.count(); i++) {
478         QDomElement e = params.item(i).toElement();
479         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe"))
480             result.append(e.attribute("keyframes"));
481     }
482     return result;
483 }
484
485 void ClipItem::updateKeyframeEffect()
486 {
487     // regenerate xml parameter from the clip keyframes
488     QDomElement effect = getEffectAt(m_selectedEffect);
489     if (effect.attribute("disable") == "1") return;
490     QDomNodeList params = effect.elementsByTagName("parameter");
491     QDomElement e = params.item(m_visibleParam).toElement();
492
493     if (!e.isNull()) {
494         QString keyframes;
495         if (m_keyframes.count() > 0) {
496             QMap<int, int>::const_iterator i = m_keyframes.constBegin();
497             while (i != m_keyframes.constEnd()) {
498                 keyframes.append(QString::number(i.key()) + ':' + QString::number(i.value()) + ';');
499                 ++i;
500             }
501         }
502         // Effect has a keyframe type parameter, we need to set the values
503         e.setAttribute("keyframes", keyframes);
504     }
505 }
506
507 QDomElement ClipItem::selectedEffect()
508 {
509     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
510     return effectAt(m_selectedEffect);
511 }
512
513 void ClipItem::resetThumbs(bool clearExistingThumbs)
514 {
515     if (clearExistingThumbs) {
516         m_startPix = QPixmap();
517         m_endPix = QPixmap();
518         m_audioThumbCachePic.clear();
519     }
520     slotFetchThumbs();
521 }
522
523
524 void ClipItem::refreshClip(bool checkDuration, bool forceResetThumbs)
525 {
526     if (checkDuration && (m_maxDuration != m_clip->maxDuration())) {
527         m_maxDuration = m_clip->maxDuration();
528         if (m_clipType != IMAGE && m_clipType != TEXT && m_clipType != COLOR) {
529             if (m_maxDuration != GenTime() && m_info.cropStart + m_info.cropDuration > m_maxDuration) {
530                 // Clip duration changed, make sure to stay in correct range
531                 if (m_info.cropStart > m_maxDuration) {
532                     m_info.cropStart = GenTime();
533                     m_info.cropDuration = qMin(m_info.cropDuration, m_maxDuration);
534                 } else {
535                     m_info.cropDuration = m_maxDuration;
536                 }
537                 updateRectGeometry();
538             }
539         }
540     }
541     if (m_clipType == COLOR) {
542         QString colour = m_clip->getProperty("colour");
543         colour = colour.replace(0, 2, "#");
544         m_baseColor = QColor(colour.left(7));
545         update();
546     } else resetThumbs(forceResetThumbs);
547 }
548
549 void ClipItem::slotFetchThumbs()
550 {
551     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
552     if (m_clipType == IMAGE) {
553         if (m_startPix.isNull()) {
554             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
555             update();
556         }
557         return;
558     }
559
560     if (m_clipType == TEXT) {
561         if (m_startPix.isNull()) slotGetStartThumb();
562         return;
563     }
564
565     QList <int> frames;
566     if (m_startPix.isNull()) {
567         m_startThumbRequested = true;
568         frames.append((int)m_speedIndependantInfo.cropStart.frames(m_fps));
569     }
570
571     if (m_endPix.isNull()) {
572         m_endThumbRequested = true;
573         frames.append((int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
574     }
575
576     m_clip->slotExtractImage(frames);
577 }
578
579 void ClipItem::slotGetStartThumb()
580 {
581     m_startThumbRequested = true;
582     m_clip->slotExtractImage(QList<int>() << (int)m_speedIndependantInfo.cropStart.frames(m_fps));
583 }
584
585 void ClipItem::slotGetEndThumb()
586 {
587     m_endThumbRequested = true;
588     m_clip->slotExtractImage(QList<int>() << (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
589 }
590
591
592 void ClipItem::slotSetStartThumb(QImage img)
593 {
594     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
595         QPixmap pix = QPixmap::fromImage(img);
596         m_startPix = pix;
597         QRectF r = sceneBoundingRect();
598         r.setRight(pix.width() + 2);
599         update(r);
600     }
601 }
602
603 void ClipItem::slotSetEndThumb(QImage img)
604 {
605     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
606         QPixmap pix = QPixmap::fromImage(img);
607         m_endPix = pix;
608         QRectF r = sceneBoundingRect();
609         r.setLeft(r.right() - pix.width() - 2);
610         update(r);
611     }
612 }
613
614 void ClipItem::slotThumbReady(int frame, QImage img)
615 {
616     if (scene() == NULL) return;
617     QRectF r = boundingRect();
618     QPixmap pix = QPixmap::fromImage(img);
619     double width = pix.width() / projectScene()->scale().x();
620     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
621         m_startPix = pix;
622         m_startThumbRequested = false;
623         update(r.left(), r.top(), width, pix.height());
624         if (m_clipType == IMAGE || m_clipType == TEXT) {
625             update(r.right() - width, r.top(), width, pix.height());
626         }
627     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
628         m_endPix = pix;
629         m_endThumbRequested = false;
630         update(r.right() - width, r.top(), width, pix.height());
631     }
632 }
633
634 void ClipItem::slotSetStartThumb(const QPixmap pix)
635 {
636     m_startPix = pix;
637 }
638
639 void ClipItem::slotSetEndThumb(const QPixmap pix)
640 {
641     m_endPix = pix;
642 }
643
644 QPixmap ClipItem::startThumb() const
645 {
646     return m_startPix;
647 }
648
649 QPixmap ClipItem::endThumb() const
650 {
651     return m_endPix;
652 }
653
654 void ClipItem::slotGotAudioData()
655 {
656     m_audioThumbReady = true;
657     if (m_clipType == AV && !isAudioOnly()) {
658         QRectF r = boundingRect();
659         r.setTop(r.top() + r.height() / 2 - 1);
660         update(r);
661     } else update();
662 }
663
664 int ClipItem::type() const
665 {
666     return AVWIDGET;
667 }
668
669 DocClipBase *ClipItem::baseClip() const
670 {
671     return m_clip;
672 }
673
674 QDomElement ClipItem::xml() const
675 {
676     return itemXml();
677 }
678
679 QDomElement ClipItem::itemXml() const
680 {
681     QDomElement xml = m_clip->toXML();
682     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
683     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
684     if (m_audioOnly) xml.setAttribute("audio_only", 1);
685     else if (m_videoOnly) xml.setAttribute("video_only", 1);
686     return xml;
687 }
688
689 int ClipItem::clipType() const
690 {
691     return m_clipType;
692 }
693
694 QString ClipItem::clipName() const
695 {
696     return m_clipName;
697 }
698
699 void ClipItem::setClipName(const QString &name)
700 {
701     m_clipName = name;
702 }
703
704 const QString ClipItem::clipProducer() const
705 {
706     return m_producer;
707 }
708
709 void ClipItem::flashClip()
710 {
711     if (m_timeLine == 0) {
712         m_timeLine = new QTimeLine(750, this);
713         m_timeLine->setUpdateInterval(80);
714         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
715         m_timeLine->setFrameRange(0, 100);
716         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
717     }
718     //m_timeLine->start();
719 }
720
721 void ClipItem::animate(qreal /*value*/)
722 {
723     QRectF r = boundingRect();
724     r.setHeight(20);
725     update(r);
726 }
727
728 // virtual
729 void ClipItem::paint(QPainter *painter,
730                      const QStyleOptionGraphicsItem *option,
731                      QWidget *)
732 {
733     QColor paintColor;
734     QPen framePen;
735     if (parentItem()) paintColor = QColor(255, 248, 149);
736     else paintColor = m_baseColor;
737     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
738         paintColor = paintColor.darker();
739         framePen.setColor(Qt::red);
740         framePen.setWidthF(2.0);
741     }
742     else {
743         framePen.setColor(paintColor.darker());
744     }
745
746     const QRectF exposed = option->exposedRect;
747     painter->setClipRect(exposed);
748     painter->fillRect(exposed, paintColor);
749     painter->setWorldMatrixEnabled(false);;
750     const QRectF mapped = painter->worldTransform().mapRect(rect());
751     // draw thumbnails
752     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
753         QPen pen = painter->pen();
754         pen.setColor(QColor(255, 255, 255, 150));
755         painter->setPen(pen);
756         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
757             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
758             painter->drawPixmap(top, m_startPix);
759             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
760             painter->drawLine(l2);
761         } else if (!m_endPix.isNull()) {
762             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
763             painter->drawPixmap(top, m_endPix);
764             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
765             painter->drawLine(l2);
766         }
767         if (!m_startPix.isNull()) {
768             painter->drawPixmap(mapped.topLeft(), m_startPix);
769             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
770             painter->drawLine(l2);
771         }
772
773         // if we are in full zoom, paint thumbnail for every frame
774         if (m_clip->thumbProducer() && clipType() != COLOR && clipType() != AUDIO && !m_audioOnly && painter->worldTransform().m11() == FRAME_SIZE) {
775             int offset = (m_info.startPos - m_info.cropStart).frames(m_fps);
776             int left = qMax((int) m_info.cropStart.frames(m_fps) + 1, (int) mapToScene(exposed.left(), 0).x() - offset);
777             int right = qMin((int)(m_info.cropStart + m_info.cropDuration).frames(m_fps) - 1, (int) mapToScene(exposed.right(), 0).x() - offset);
778             QPointF startPos = mapped.topLeft();
779             int startOffset = m_info.cropStart.frames(m_fps);
780             if (clipType() == IMAGE || clipType() == TEXT) {
781                 for (int i = left; i <= right; i++) {
782                     painter->drawPixmap(startPos + QPointF(FRAME_SIZE *(i - startOffset), 0), m_startPix);
783                 }
784             }
785             else {
786 #if KDE_IS_VERSION(4,5,0)
787                 if (m_clip && m_clip->thumbProducer()) {
788                     QString path = m_clip->fileURL().path() + "_";
789                     QImage img;
790                     QPen pen(Qt::white);
791                     pen.setStyle(Qt::DotLine);
792                     painter->setPen(pen);
793                     QList <int> missing;
794                     for (int i = left; i <= right; i++) {
795                         img = m_clip->thumbProducer()->findCachedThumb(path + QString::number(i));
796                         QPointF xpos = startPos + QPointF(FRAME_SIZE *(i - startOffset), 0);
797                         if (img.isNull()) missing << i;
798                         else painter->drawImage(xpos, img);
799                         painter->drawLine(xpos, xpos + QPointF(0, mapped.height()));
800                     }
801                     if (!missing.isEmpty()) {
802                         m_clip->thumbProducer()->queryIntraThumbs(missing);
803                         connect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
804                     }
805                 }
806 #endif
807             }
808         }
809         painter->setPen(Qt::black);
810     }
811
812     // draw audio thumbnails
813     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
814
815         double startpixel = exposed.left();
816         if (startpixel < 0)
817             startpixel = 0;
818         double endpixel = exposed.right();
819         if (endpixel < 0)
820             endpixel = 0;
821         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
822
823         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
824         QRectF mappedRect;
825         if (m_clipType == AV && !isAudioOnly()) {
826             mappedRect = mapped;
827             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
828         } else mappedRect = mapped;
829
830         double scale = painter->worldTransform().m11();
831         int channels = 0;
832         if (isEnabled() && m_clip) channels = m_clip->getProperty("channels").toInt();
833         if (scale != m_framePixelWidth)
834             m_audioThumbCachePic.clear();
835         double cropLeft = m_info.cropStart.frames(m_fps);
836         const int clipStart = mappedRect.x();
837         const int mappedStartPixel =  painter->worldTransform().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
838         const int mappedEndPixel =  painter->worldTransform().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
839         cropLeft = cropLeft * scale;
840
841         if (channels >= 1) {
842             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
843         }
844
845         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
846             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
847                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
848         }
849     }
850
851     // only paint details if clip is big enough
852     if (mapped.width() > 20) {
853
854         // Draw effects names
855         if (!m_effectNames.isEmpty() && mapped.width() > 40) {
856             QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
857             QColor bgColor;
858             if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
859                 qreal value = m_timeLine->currentValue();
860                 txtBounding.setWidth(txtBounding.width() * value);
861                 bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
862             } else bgColor.setRgb(50, 50, 90, 180);
863
864             QPainterPath rounded;
865             rounded.moveTo(txtBounding.bottomRight());
866             rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
867             rounded.lineTo(txtBounding.topLeft());
868             rounded.lineTo(txtBounding.bottomLeft());
869             painter->fillPath(rounded, bgColor);
870             painter->setPen(Qt::lightGray);
871             painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
872         }
873
874         const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
875         painter->setBrush(framePen.color());
876         painter->setPen(Qt::NoPen);
877         painter->drawRoundedRect(txtBounding2, 3, 3);
878         painter->setBrush(QBrush(Qt::NoBrush));
879
880         if (m_videoOnly) {
881             painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
882         } else if (m_audioOnly) {
883             painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
884         }
885         painter->setPen(Qt::white);
886         painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
887
888
889         // draw markers
890         if (isEnabled() && m_clip) {
891             QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
892             QList < CommentedTime >::Iterator it = markers.begin();
893             GenTime pos;
894             double framepos;
895             QBrush markerBrush(QColor(120, 120, 0, 140));
896             QPen pen = painter->pen();
897             pen.setColor(QColor(255, 255, 255, 200));
898             pen.setStyle(Qt::DotLine);
899
900             for (; it != markers.end(); ++it) {
901                 pos = GenTime((int)((*it).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
902                 if (pos > GenTime()) {
903                     if (pos > cropDuration()) break;
904                     QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
905                     QLineF l2 = painter->worldTransform().map(l);
906                     painter->setPen(pen);
907                     painter->drawLine(l2);
908                     if (KdenliveSettings::showmarkers()) {
909                         framepos = rect().x() + pos.frames(m_fps);
910                         const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
911                         const QRectF r2 = painter->worldTransform().mapRect(r1);
912                         const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
913                         painter->setBrush(markerBrush);
914                         painter->setPen(Qt::NoPen);
915                         painter->drawRoundedRect(txtBounding3, 3, 3);
916                         painter->setBrush(QBrush(Qt::NoBrush));
917                         painter->setPen(Qt::white);
918                         painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
919                     }
920                     //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
921                 }
922             }
923         }
924
925         // draw start / end fades
926         QBrush fades;
927         if (isSelected()) {
928             fades = QBrush(QColor(200, 50, 50, 150));
929         } else fades = QBrush(QColor(200, 200, 200, 200));
930
931         if (m_startFade != 0) {
932             QPainterPath fadeInPath;
933             fadeInPath.moveTo(0, 0);
934             fadeInPath.lineTo(0, rect().height());
935             fadeInPath.lineTo(m_startFade, 0);
936             fadeInPath.closeSubpath();
937             QPainterPath f1 = painter->worldTransform().map(fadeInPath);
938             painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
939             /*if (isSelected()) {
940                 QLineF l(m_startFade * scale, 0, 0, itemHeight);
941                 painter->drawLine(l);
942             }*/
943         }
944         if (m_endFade != 0) {
945             QPainterPath fadeOutPath;
946             fadeOutPath.moveTo(rect().width(), 0);
947             fadeOutPath.lineTo(rect().width(), rect().height());
948             fadeOutPath.lineTo(rect().width() - m_endFade, 0);
949             fadeOutPath.closeSubpath();
950             QPainterPath f1 = painter->worldTransform().map(fadeOutPath);
951             painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
952             /*if (isSelected()) {
953                 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
954                 painter->drawLine(l);
955             }*/
956         }
957
958
959         painter->setPen(QPen(Qt::lightGray));
960         // draw effect or transition keyframes
961         drawKeyFrames(painter, m_limitedKeyFrames);
962     }
963     
964     // draw clip border
965     // expand clip rect to allow correct painting of clip border
966     painter->setClipping(false);
967     painter->setPen(framePen);
968     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
969         painter->drawRect(mapped.adjusted(0.5, 0.5, -0.5, -0.5));
970     }
971     else {
972         painter->drawRect(mapped.adjusted(0, 0, -0.5, 0));
973     }
974 }
975
976
977 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
978 {
979     if (isItemLocked()) return NONE;
980     const double scale = projectScene()->scale().x();
981     double maximumOffset = 6 / scale;
982     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
983         int kf = mouseOverKeyFrames(pos, maximumOffset);
984         if (kf != -1) {
985             m_editedKeyframe = kf;
986             return KEYFRAME;
987         }
988     }
989     QRectF rect = sceneBoundingRect();
990     int addtransitionOffset = 10;
991     // Don't allow add transition if track height is very small
992     if (rect.height() < 30) addtransitionOffset = 0;
993
994     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
995         return FADEIN;
996     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
997         return RESIZESTART;
998     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
999         return FADEOUT;
1000     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
1001         return RESIZEEND;
1002     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
1003         return TRANSITIONSTART;
1004     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
1005         return TRANSITIONEND;
1006     }
1007
1008     return MOVE;
1009 }
1010
1011 int ClipItem::itemHeight()
1012 {
1013     return KdenliveSettings::trackheight() - 2;
1014 }
1015
1016 void ClipItem::resetFrameWidth(int width)
1017 {
1018     FRAME_SIZE = width;
1019     update();
1020 }
1021
1022 QList <GenTime> ClipItem::snapMarkers() const
1023 {
1024     QList < GenTime > snaps;
1025     QList < GenTime > markers = baseClip()->snapMarkers();
1026     GenTime pos;
1027
1028     for (int i = 0; i < markers.size(); i++) {
1029         pos = GenTime((int)(markers.at(i).frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1030         if (pos > GenTime()) {
1031             if (pos > cropDuration()) break;
1032             else snaps.append(pos + startPos());
1033         }
1034     }
1035     return snaps;
1036 }
1037
1038 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
1039 {
1040     QList < CommentedTime > snaps;
1041     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
1042     GenTime pos;
1043
1044     for (int i = 0; i < markers.size(); i++) {
1045         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1046         if (pos > GenTime()) {
1047             if (pos > cropDuration()) break;
1048             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
1049         }
1050     }
1051     return snaps;
1052 }
1053
1054 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
1055 {
1056     QRectF re =  sceneBoundingRect();
1057     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
1058
1059     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
1060     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
1061
1062     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
1063         //kDebug() << "creating " << startCache;
1064         //if (framePixelWidth!=pixelForOneFrame  ||
1065         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
1066             continue;
1067         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
1068             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
1069             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
1070         }
1071         bool fullAreaDraw = pixelForOneFrame < 10;
1072         QMap<int, QPainterPath > positiveChannelPaths;
1073         QMap<int, QPainterPath > negativeChannelPaths;
1074         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
1075         QPen audiopen;
1076         audiopen.setWidth(0);
1077         pixpainter.setPen(audiopen);
1078         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
1079         //pixpainter.drawLine(0,0,100,re.height());
1080         // Bail out, if caller provided invalid data
1081         if (channels <= 0) {
1082             kWarning() << "Unable to draw image with " << channels << "number of channels";
1083             return;
1084         }
1085
1086         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
1087
1088         for (int i = 0; i < channels; i++) {
1089
1090             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1091             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1092         }
1093
1094         for (int samples = 0; samples <= 100; samples++) {
1095             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
1096             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
1097             if (frame < 0 || sample < 0 || sample > 19)
1098                 continue;
1099             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
1100
1101             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
1102
1103                 int y = channelHeight * channel + channelHeight / 2;
1104                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
1105                 if (fullAreaDraw) {
1106                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
1107                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
1108                 } else {
1109                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
1110                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
1111                 }
1112             }
1113             for (int channel = 0; channel < channels ; channel++)
1114                 if (fullAreaDraw && samples == 100) {
1115                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1116                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1117                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1118                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1119                 }
1120
1121         }
1122         pixpainter.setPen(QPen(QColor(0, 0, 0)));
1123         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
1124
1125         for (int i = 0; i < channels; i++) {
1126             if (fullAreaDraw) {
1127                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
1128                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
1129             } else
1130                 pixpainter.drawPath(positiveChannelPaths[i]);
1131         }
1132     }
1133     //audioThumbWasDrawn=true;
1134     m_framePixelWidth = pixelForOneFrame;
1135
1136     //}
1137 }
1138
1139 int ClipItem::fadeIn() const
1140 {
1141     return m_startFade;
1142 }
1143
1144 int ClipItem::fadeOut() const
1145 {
1146     return m_endFade;
1147 }
1148
1149
1150 void ClipItem::setFadeIn(int pos)
1151 {
1152     if (pos == m_startFade) return;
1153     int oldIn = m_startFade;
1154     m_startFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1155     QRectF rect = boundingRect();
1156     update(rect.x(), rect.y(), qMax(oldIn, m_startFade), rect.height());
1157 }
1158
1159 void ClipItem::setFadeOut(int pos)
1160 {
1161     if (pos == m_endFade) return;
1162     int oldOut = m_endFade;
1163     m_endFade = qBound(0, pos, (int)cropDuration().frames(m_fps));
1164     QRectF rect = boundingRect();
1165     update(rect.x() + rect.width() - qMax(oldOut, m_endFade), rect.y(), qMax(oldOut, m_endFade), rect.height());
1166
1167 }
1168
1169 void ClipItem::setFades(int in, int out)
1170 {
1171     m_startFade = in;
1172     m_endFade = out;
1173 }
1174
1175 /*
1176 //virtual
1177 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1178 {
1179     //if (e->pos().x() < 20) m_hover = true;
1180     return;
1181     if (isItemLocked()) return;
1182     m_hover = true;
1183     QRectF r = boundingRect();
1184     double width = 35 / projectScene()->scale().x();
1185     double height = r.height() / 2;
1186     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1187     update(r.x(), r.y() + height, width, height);
1188     update(r.right() - width, r.y() + height, width, height);
1189 }
1190
1191 //virtual
1192 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1193 {
1194     if (isItemLocked()) return;
1195     m_hover = false;
1196     QRectF r = boundingRect();
1197     double width = 35 / projectScene()->scale().x();
1198     double height = r.height() / 2;
1199     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1200     update(r.x(), r.y() + height, width, height);
1201     update(r.right() - width, r.y() + height, width, height);
1202 }
1203 */
1204
1205 void ClipItem::resizeStart(int posx, bool /*size*/)
1206 {
1207     bool sizeLimit = false;
1208     if (clipType() != IMAGE && clipType() != COLOR && clipType() != TEXT) {
1209         const int min = (startPos() - cropStart()).frames(m_fps);
1210         if (posx < min) posx = min;
1211         sizeLimit = true;
1212     }
1213
1214     if (posx == startPos().frames(m_fps)) return;
1215     const int previous = cropStart().frames(m_fps);
1216     AbstractClipItem::resizeStart(posx, sizeLimit);
1217
1218     // set speed independant info
1219     m_speedIndependantInfo = m_info;
1220     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1221     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1222
1223     if ((int) cropStart().frames(m_fps) != previous) {
1224         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1225             m_startThumbTimer.start(150);
1226         }
1227     }
1228 }
1229
1230 void ClipItem::resizeEnd(int posx)
1231 {
1232     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1233     if (posx > max && maxDuration() != GenTime()) posx = max;
1234     if (posx == endPos().frames(m_fps)) return;
1235     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1236     const int previous = cropDuration().frames(m_fps);
1237     AbstractClipItem::resizeEnd(posx);
1238
1239     // set speed independant info
1240     m_speedIndependantInfo = m_info;
1241     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1242     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1243
1244     if ((int) cropDuration().frames(m_fps) != previous) {
1245         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1246             m_endThumbTimer.start(150);
1247         }
1248     }
1249 }
1250
1251 //virtual
1252 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1253 {
1254     if (change == QGraphicsItem::ItemSelectedChange) {
1255         if (value.toBool()) setZValue(10);
1256         else setZValue(2);
1257     }
1258     if (change == ItemPositionChange && scene()) {
1259         // calculate new position.
1260         //if (parentItem()) return pos();
1261         QPointF newPos = value.toPointF();
1262         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1263         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1264         xpos = qMax(xpos, 0);
1265         newPos.setX(xpos);
1266         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1267         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1268         newTrack = qMax(newTrack, 0);
1269         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1270         // Only one clip is moving
1271         QRectF sceneShape = rect();
1272         sceneShape.translate(newPos);
1273         QList<QGraphicsItem*> items;
1274         if (projectScene()->editMode() == NORMALEDIT)
1275             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1276         items.removeAll(this);
1277         bool forwardMove = newPos.x() > pos().x();
1278         int offset = 0;
1279         if (!items.isEmpty()) {
1280             for (int i = 0; i < items.count(); i++) {
1281                 if (!items.at(i)->isEnabled()) continue;
1282                 if (items.at(i)->type() == type()) {
1283                     // Collision!
1284                     QPointF otherPos = items.at(i)->pos();
1285                     if ((int) otherPos.y() != (int) pos().y()) {
1286                         return pos();
1287                     }
1288                     if (forwardMove) {
1289                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1290                     } else {
1291                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1292                     }
1293
1294                     if (offset > 0) {
1295                         if (forwardMove) {
1296                             sceneShape.translate(QPointF(-offset, 0));
1297                             newPos.setX(newPos.x() - offset);
1298                         } else {
1299                             sceneShape.translate(QPointF(offset, 0));
1300                             newPos.setX(newPos.x() + offset);
1301                         }
1302                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1303                         subitems.removeAll(this);
1304                         for (int j = 0; j < subitems.count(); j++) {
1305                             if (!subitems.at(j)->isEnabled()) continue;
1306                             if (subitems.at(j)->type() == type()) {
1307                                 // move was not successful, revert to previous pos
1308                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1309                                 return pos();
1310                             }
1311                         }
1312                     }
1313
1314                     m_info.track = newTrack;
1315                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1316
1317                     return newPos;
1318                 }
1319             }
1320         }
1321         m_info.track = newTrack;
1322         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1323         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1324         return newPos;
1325     }
1326     return QGraphicsItem::itemChange(change, value);
1327 }
1328
1329 // virtual
1330 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1331 }*/
1332
1333 int ClipItem::effectsCounter()
1334 {
1335     return effectsCount() + 1;
1336 }
1337
1338 int ClipItem::effectsCount()
1339 {
1340     return m_effectList.count();
1341 }
1342
1343 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1344 {
1345     return m_effectList.hasEffect(tag, id);
1346 }
1347
1348 QStringList ClipItem::effectNames()
1349 {
1350     return m_effectList.effectNames();
1351 }
1352
1353 QDomElement ClipItem::effectAt(int ix) const
1354 {
1355     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1356     return m_effectList.at(ix).cloneNode().toElement();
1357 }
1358
1359 QDomElement ClipItem::getEffectAt(int ix) const
1360 {
1361     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1362     return m_effectList.at(ix);
1363 }
1364
1365 void ClipItem::setEffectAt(int ix, QDomElement effect)
1366 {
1367     if (ix < 0 || ix > (m_effectList.count() - 1) || effect.isNull()) {
1368         kDebug() << "Invalid effect index: " << ix;
1369         return;
1370     }
1371     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1372     effect.setAttribute("kdenlive_ix", ix + 1);
1373     m_effectList.replace(ix, effect);
1374     m_effectNames = m_effectList.effectNames().join(" / ");
1375     QString id = effect.attribute("id");
1376     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1377         update();
1378     else {
1379         QRectF r = boundingRect();
1380         r.setHeight(20);
1381         update(r);
1382     }
1383 }
1384
1385 EffectsParameterList ClipItem::addEffect(const QDomElement effect, bool /*animate*/)
1386 {
1387     bool needRepaint = false;
1388     QLocale locale;
1389     int ix;
1390     if (!effect.hasAttribute("kdenlive_ix")) {
1391         ix = effectsCounter();
1392     } else ix = effect.attribute("kdenlive_ix").toInt();
1393     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1394         needRepaint = true;
1395         m_effectList.insert(ix - 1, effect);
1396         for (int i = ix; i < m_effectList.count(); i++) {
1397             int index = m_effectList.item(i).attribute("kdenlive_ix").toInt();
1398             if (index >= ix) m_effectList.item(i).setAttribute("kdenlive_ix", index + 1);
1399         }
1400     } else m_effectList.append(effect);
1401     EffectsParameterList parameters;
1402     parameters.addParam("tag", effect.attribute("tag"));
1403     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1404     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1405     if (effect.hasAttribute("disable")) parameters.addParam("disable", effect.attribute("disable"));
1406
1407     QString effectId = effect.attribute("id");
1408     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1409     parameters.addParam("id", effectId);
1410
1411     // special case: the affine effect needs in / out points
1412
1413     QDomNodeList params = effect.elementsByTagName("parameter");
1414     int fade = 0;
1415     bool needInOutSync = false;
1416     for (int i = 0; i < params.count(); i++) {
1417         QDomElement e = params.item(i).toElement();
1418         if (!e.isNull()) {
1419             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1420                 // Effects with a geometry parameter need to sync in / out with parent clip
1421                 needInOutSync = true;
1422             }
1423             if (e.attribute("type") == "simplekeyframe") {
1424                 QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1425                 double factor = locale.toDouble(e.attribute("factor", "1"));
1426                 double offset = e.attribute("offset", "0").toDouble();
1427                 if (factor != 1 || offset != 0) {
1428                     for (int j = 0; j < values.count(); j++) {
1429                         QString pos = values.at(j).section(':', 0, 0);
1430                         double val = (locale.toDouble(values.at(j).section(':', 1, 1)) - offset) / factor;
1431                         values[j] = pos + "=" + locale.toString(val);
1432                     }
1433                 }
1434                 parameters.addParam(e.attribute("name"), values.join(";"));
1435                 /*parameters.addParam("max", e.attribute("max"));
1436                 parameters.addParam("min", e.attribute("min"));
1437                 parameters.addParam("factor", );*/
1438             } else if (e.attribute("type") == "keyframe") {
1439                 parameters.addParam("keyframes", e.attribute("keyframes"));
1440                 parameters.addParam("max", e.attribute("max"));
1441                 parameters.addParam("min", e.attribute("min"));
1442                 parameters.addParam("factor", e.attribute("factor", "1"));
1443                 parameters.addParam("offset", e.attribute("offset", "0"));
1444                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1445                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1446             } else if (e.attribute("factor", "1") == "1" && e.attribute("offset", "0") == "0") {
1447                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1448
1449                 // check if it is a fade effect
1450                 if (effectId == "fadein") {
1451                     needRepaint = true;
1452                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1453                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1454                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1455                     } else {
1456                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1457                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1458                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1459                     }
1460                 } else if (effectId == "fade_from_black") {
1461                     needRepaint = true;
1462                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1463                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1464                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1465                     } else {
1466                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1467                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1468                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1469                     }
1470                 } else if (effectId == "fadeout") {
1471                     needRepaint = true;
1472                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1473                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1474                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1475                     } else {
1476                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1477                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1478                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1479                     }
1480                 } else if (effectId == "fade_to_black") {
1481                     needRepaint = true;
1482                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1483                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1484                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1485                     } else {
1486                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1487                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1488                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1489                     }
1490                 }
1491             } else {
1492                 double fact;
1493                 if (e.attribute("factor").contains('%')) {
1494                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1495                 } else {
1496                     fact = locale.toDouble(e.attribute("factor", "1"));
1497                 }
1498                 double offset = e.attribute("offset", "0").toDouble();
1499                 parameters.addParam(e.attribute("name"), locale.toString((locale.toDouble(e.attribute("value")) - offset) / fact));
1500             }
1501         }
1502     }
1503     if (needInOutSync) {
1504         parameters.addParam("in", QString::number(cropStart().frames(m_fps)));
1505         parameters.addParam("out", QString::number((cropStart() + cropDuration()).frames(m_fps) - 1));
1506         parameters.addParam("_sync_in_out", "1");
1507     }
1508     m_effectNames = m_effectList.effectNames().join(" / ");
1509     if (fade > 0) m_startFade = fade;
1510     else if (fade < 0) m_endFade = -fade;
1511
1512     if (m_selectedEffect == -1) {
1513         setSelectedEffect(0);
1514     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1515     if (needRepaint) update(boundingRect());
1516     /*if (animate) {
1517         flashClip();
1518     } */
1519     else { /*if (!needRepaint) */
1520         QRectF r = boundingRect();
1521         r.setHeight(20);
1522         update(r);
1523     }
1524     return parameters;
1525 }
1526
1527 void ClipItem::deleteEffect(QString index)
1528 {
1529     bool needRepaint = false;
1530     QString ix;
1531
1532     for (int i = 0; i < m_effectList.count(); ++i) {
1533         ix = m_effectList.at(i).attribute("kdenlive_ix");
1534         if (ix == index) {
1535             QString effectId = m_effectList.at(i).attribute("id");
1536             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1537                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1538                 m_startFade = 0;
1539                 needRepaint = true;
1540             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1541                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1542                 m_endFade = 0;
1543                 needRepaint = true;
1544             } else if (EffectsList::hasKeyFrames(m_effectList.at(i))) needRepaint = true;
1545             m_effectList.removeAt(i);
1546             i--;
1547         } else if (ix.toInt() > index.toInt()) {
1548             m_effectList.item(i).setAttribute("kdenlive_ix", ix.toInt() - 1);
1549         }
1550     }
1551     m_effectNames = m_effectList.effectNames().join(" / ");
1552
1553     if (m_effectList.isEmpty() || m_selectedEffect + 1 == index.toInt()) {
1554         // Current effect was removed
1555         if (index.toInt() > m_effectList.count() - 1) {
1556             setSelectedEffect(m_effectList.count() - 1);
1557         } else setSelectedEffect(index.toInt());
1558     }
1559     if (needRepaint) update(boundingRect());
1560     else {
1561         QRectF r = boundingRect();
1562         r.setHeight(20);
1563         update(r);
1564     }
1565     //if (!m_effectList.isEmpty()) flashClip();
1566 }
1567
1568 double ClipItem::speed() const
1569 {
1570     return m_speed;
1571 }
1572
1573 int ClipItem::strobe() const
1574 {
1575     return m_strobe;
1576 }
1577
1578 void ClipItem::setSpeed(const double speed, const int strobe)
1579 {
1580     m_speed = speed;
1581     if (m_speed <= 0 && m_speed > -1)
1582         m_speed = -1.0;
1583     m_strobe = strobe;
1584     if (m_speed == 1.0) m_clipName = baseClip()->name();
1585     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1586     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1587     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1588     //update();
1589 }
1590
1591 GenTime ClipItem::maxDuration() const
1592 {
1593     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1594 }
1595
1596 GenTime ClipItem::speedIndependantCropStart() const
1597 {
1598     return m_speedIndependantInfo.cropStart;
1599 }
1600
1601 GenTime ClipItem::speedIndependantCropDuration() const
1602 {
1603     return m_speedIndependantInfo.cropDuration;
1604 }
1605
1606
1607 const ItemInfo ClipItem::speedIndependantInfo() const
1608 {
1609     return m_speedIndependantInfo;
1610 }
1611
1612 //virtual
1613 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1614 {
1615     const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
1616     QDomDocument doc;
1617     doc.setContent(effects, true);
1618     const QDomElement e = doc.documentElement();
1619     if (scene() && !scene()->views().isEmpty()) {
1620         event->accept();
1621         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1622         if (view) view->slotAddEffect(e, m_info.startPos, track());
1623     }
1624 }
1625
1626 //virtual
1627 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1628 {
1629     if (isItemLocked()) event->setAccepted(false);
1630     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1631 }
1632
1633 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1634 {
1635     Q_UNUSED(event)
1636 }
1637
1638 void ClipItem::addTransition(Transition* t)
1639 {
1640     m_transitionsList.append(t);
1641     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1642     QDomDocument doc;
1643     QDomElement e = doc.documentElement();
1644     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1645 }
1646
1647 void ClipItem::setVideoOnly(bool force)
1648 {
1649     m_videoOnly = force;
1650 }
1651
1652 void ClipItem::setAudioOnly(bool force)
1653 {
1654     m_audioOnly = force;
1655     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1656     else {
1657         if (m_clipType == COLOR) {
1658             QString colour = m_clip->getProperty("colour");
1659             colour = colour.replace(0, 2, "#");
1660             m_baseColor = QColor(colour.left(7));
1661         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1662         else m_baseColor = QColor(141, 166, 215);
1663     }
1664     m_audioThumbCachePic.clear();
1665 }
1666
1667 bool ClipItem::isAudioOnly() const
1668 {
1669     return m_audioOnly;
1670 }
1671
1672 bool ClipItem::isVideoOnly() const
1673 {
1674     return m_videoOnly;
1675 }
1676
1677 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1678 {
1679     if (effect.attribute("disable") == "1") return;
1680     QLocale locale;
1681     effect.setAttribute("active_keyframe", pos);
1682     m_editedKeyframe = pos;
1683     QDomNodeList params = effect.elementsByTagName("parameter");
1684     for (int i = 0; i < params.count(); i++) {
1685         QDomElement e = params.item(i).toElement();
1686         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1687             QString kfr = e.attribute("keyframes");
1688             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1689             QStringList newkfr;
1690             bool added = false;
1691             foreach(const QString &str, keyframes) {
1692                 int kpos = str.section(':', 0, 0).toInt();
1693                 double newval = locale.toDouble(str.section(':', 1, 1));
1694                 if (kpos < pos) {
1695                     newkfr.append(str);
1696                 } else if (!added) {
1697                     if (i == m_visibleParam)
1698                         newkfr.append(QString::number(pos) + ":" + QString::number(val));
1699                     else
1700                         newkfr.append(QString::number(pos) + ":" + locale.toString(newval));
1701                     if (kpos > pos) newkfr.append(str);
1702                     added = true;
1703                 } else newkfr.append(str);
1704             }
1705             if (!added) {
1706                 if (i == m_visibleParam)
1707                     newkfr.append(QString::number(pos) + ":" + QString::number(val));
1708                 else
1709                     newkfr.append(QString::number(pos) + ":" + e.attribute("default"));
1710             }
1711             e.setAttribute("keyframes", newkfr.join(";"));
1712         }
1713     }
1714 }
1715
1716 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1717 {
1718     if (effect.attribute("disable") == "1") return;
1719     QLocale locale;
1720     effect.setAttribute("active_keyframe", newpos);
1721     QDomNodeList params = effect.elementsByTagName("parameter");
1722     int start = cropStart().frames(m_fps);
1723     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1724     for (int i = 0; i < params.count(); i++) {
1725         QDomElement e = params.item(i).toElement();
1726         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1727             QString kfr = e.attribute("keyframes");
1728             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1729             QStringList newkfr;
1730             foreach(const QString &str, keyframes) {
1731                 if (str.section(':', 0, 0).toInt() != oldpos) {
1732                     newkfr.append(str);
1733                 } else if (newpos != -1) {
1734                     newpos = qMax(newpos, start);
1735                     newpos = qMin(newpos, end);
1736                     if (i == m_visibleParam)
1737                         newkfr.append(QString::number(newpos) + ":" + locale.toString(value));
1738                     else
1739                         newkfr.append(QString::number(newpos) + ":" + str.section(':', 1, 1));
1740                 }
1741             }
1742             e.setAttribute("keyframes", newkfr.join(";"));
1743         }
1744     }
1745
1746     updateKeyframes(effect);
1747     update();
1748 }
1749
1750 void ClipItem::updateKeyframes(QDomElement effect)
1751 {
1752     m_keyframes.clear();
1753     QLocale locale;
1754     // parse keyframes
1755     QDomNodeList params = effect.elementsByTagName("parameter");
1756     QDomElement e = params.item(m_visibleParam).toElement();
1757     if (e.attribute("intimeline") != "1") {
1758         setSelectedEffect(m_selectedEffect);
1759         return;
1760     }
1761     m_limitedKeyFrames = e.attribute("type") == "keyframe";
1762     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1763     foreach(const QString &str, keyframes) {
1764         int pos = str.section(':', 0, 0).toInt();
1765         double val = locale.toDouble(str.section(':', 1, 1));
1766         m_keyframes[pos] = val;
1767     }
1768     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1769 }
1770
1771 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1772 {
1773     if (isAudioOnly())
1774         return m_clip->audioProducer(track);
1775     else if (isVideoOnly())
1776         return m_clip->videoProducer();
1777     else
1778         return m_clip->getProducer(trackSpecific ? track : -1);
1779 }
1780
1781 QMap<int, QDomElement> ClipItem::adjustEffectsToDuration(int width, int height, ItemInfo oldInfo)
1782 {
1783     QMap<int, QDomElement> effects;
1784     for (int i = 0; i < m_effectList.count(); i++) {
1785         QDomElement effect = m_effectList.at(i);
1786
1787         if (effect.attribute("id").startsWith("fade")) {
1788             QString id = effect.attribute("id");
1789             int in = EffectsList::parameter(effect, "in").toInt();
1790             int out = EffectsList::parameter(effect, "out").toInt();
1791             int clipEnd = (cropStart() + cropDuration()).frames(m_fps) - 1;
1792             if (id == "fade_from_black" || id == "fadein") {
1793                 if (in != cropStart().frames(m_fps)) {
1794                     effects[i] = effect.cloneNode().toElement();
1795                     int diff = in - cropStart().frames(m_fps);
1796                     in -= diff;
1797                     out -= diff;
1798                     EffectsList::setParameter(effect, "in", QString::number(in));
1799                     EffectsList::setParameter(effect, "out", QString::number(out));
1800                 }
1801                 if (out > clipEnd) {
1802                     if (!effects.contains(i))
1803                         effects[i] = effect.cloneNode().toElement();
1804                     EffectsList::setParameter(effect, "out", QString::number(clipEnd));
1805                 }
1806                 if (effects.contains(i))
1807                     setFadeIn(out - in);
1808             } else {
1809                 if (out != clipEnd) {
1810                     effects[i] = effect.cloneNode().toElement();
1811                     int diff = out - clipEnd;
1812                     in = qMax(in - diff, (int) cropStart().frames(m_fps));
1813                     out -= diff;
1814                     EffectsList::setParameter(effect, "in", QString::number(in));
1815                     EffectsList::setParameter(effect, "out", QString::number(out));
1816                 }
1817                 if (in < cropStart().frames(m_fps)) {
1818                     if (!effects.contains(i))
1819                         effects[i] = effect.cloneNode().toElement();
1820                     EffectsList::setParameter(effect, "in", QString::number(cropStart().frames(m_fps)));
1821                 }
1822                 if (effects.contains(i))
1823                     setFadeOut(out - in);
1824             }
1825             continue;
1826         } else if (effect.attribute("id") == "freeze" && cropStart() != oldInfo.cropStart) {
1827             effects[i] = effect.cloneNode().toElement();
1828             int diff = (oldInfo.cropStart - cropStart()).frames(m_fps);
1829             int frame = EffectsList::parameter(effect, "frame").toInt();
1830             EffectsList::setParameter(effect, "frame", QString::number(frame - diff));
1831             continue;
1832         }
1833
1834         QDomNodeList params = effect.elementsByTagName("parameter");
1835         for (int j = 0; j < params.count(); j++) {
1836             QDomElement param = params.item(j).toElement();
1837
1838             QString type = param.attribute("type");
1839             if (type == "geometry" && !param.hasAttribute("fixed")) {
1840                 if (!effects.contains(i))
1841                     effects[i] = effect.cloneNode().toElement();
1842                 updateGeometryKeyframes(effect, j, width, height, oldInfo);
1843             } else if (type == "simplekeyframe" || type == "keyframe") {
1844                 if (!effects.contains(i))
1845                     effects[i] = effect.cloneNode().toElement();
1846                 updateNormalKeyframes(param);
1847 #ifdef USE_QJSON
1848             } else if (type == "roto-spline") {
1849                 if (!effects.contains(i))
1850                     effects[i] = effect.cloneNode().toElement();
1851                 QString value = param.attribute("value");
1852                 if (adjustRotoDuration(&value, cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1))
1853                     param.setAttribute("value", value);
1854 #endif    
1855             }
1856         }
1857     }
1858     return effects;
1859 }
1860
1861 bool ClipItem::updateNormalKeyframes(QDomElement parameter)
1862 {
1863     int in = cropStart().frames(m_fps);
1864     int out = (cropStart() + cropDuration()).frames(m_fps) - 1;
1865     QLocale locale;
1866
1867     const QStringList data = parameter.attribute("keyframes").split(';', QString::SkipEmptyParts);
1868     QMap <int, double> keyframes;
1869     foreach (QString keyframe, data)
1870         keyframes[keyframe.section(':', 0, 0).toInt()] = locale.toDouble(keyframe.section(':', 1, 1));
1871
1872
1873     QMap<int, double>::iterator i = keyframes.end();
1874     int lastPos = -1;
1875     double lastValue = 0;
1876     qreal relPos;
1877
1878     /*
1879      * Take care of resize from start
1880      */
1881     bool startFound = false;
1882     while (i-- != keyframes.begin()) {
1883         if (i.key() < in && !startFound) {
1884             startFound = true;
1885             if (lastPos < 0) {
1886                 keyframes[in] = i.value();
1887             } else {
1888                 relPos = (in - i.key()) / (qreal)(lastPos - i.key() + 1);
1889                 keyframes[in] = i.value() + (lastValue - i.value()) * relPos;
1890             }
1891         }
1892         lastPos = i.key();
1893         lastValue = i.value();
1894         if (startFound)
1895             i = keyframes.erase(i);
1896     }
1897
1898     /*
1899      * Take care of resize from end
1900      */
1901     i = keyframes.begin();
1902     lastPos = -1;
1903     bool endFound = false;
1904     while (i != keyframes.end()) {
1905         if (i.key() > out && !endFound) {
1906             endFound = true;
1907             if (lastPos < 0) {
1908                 keyframes[out] = i.value();
1909             } else {
1910                 relPos = (out - lastPos) / (qreal)(i.key() - lastPos + 1);
1911                 keyframes[out] = lastValue + (i.value() - lastValue) * relPos;
1912             }
1913          }
1914         lastPos = i.key();
1915         lastValue = i.value();
1916         if (endFound)
1917             i = keyframes.erase(i);
1918         else
1919             ++i;
1920     }
1921
1922     if (startFound || endFound) {
1923         QString newkfr;
1924         QMap<int, double>::const_iterator k = keyframes.constBegin();
1925         while (k != keyframes.constEnd()) {
1926             newkfr.append(QString::number(k.key()) + ':' + QString::number(qRound(k.value())) + ';');
1927             ++k;
1928         }
1929         parameter.setAttribute("keyframes", newkfr);
1930         return true;
1931     }
1932
1933     return false;
1934 }
1935
1936 void ClipItem::updateGeometryKeyframes(QDomElement effect, int paramIndex, int width, int height, ItemInfo oldInfo)
1937 {
1938
1939     QDomElement param = effect.elementsByTagName("parameter").item(paramIndex).toElement();
1940     int offset = oldInfo.cropStart.frames(m_fps);
1941     QString data = param.attribute("value");
1942     if (offset > 0) {
1943         QStringList kfrs = data.split(';');
1944         data.clear();
1945         foreach (QString keyframe, kfrs) {
1946             if (keyframe.contains('=')) {
1947                 int pos = keyframe.section('=', 0, 0).toInt();
1948                 pos += offset;
1949                 data.append(QString::number(pos) + "=" + keyframe.section('=', 1) + ";");
1950             }
1951             else data.append(keyframe + ";");
1952         }
1953     }
1954     Mlt::Geometry geometry(data.toUtf8().data(), oldInfo.cropDuration.frames(m_fps), width, height);
1955     param.setAttribute("value", geometry.serialise(cropStart().frames(m_fps), (cropStart() + cropDuration()).frames(m_fps) - 1));
1956 }
1957
1958 void ClipItem::slotGotThumbsCache()
1959 {
1960     disconnect(m_clip->thumbProducer(), SIGNAL(thumbsCached()), this, SLOT(slotGotThumbsCache()));
1961     update();
1962 }
1963
1964 #include "clipitem.moc"
1965