]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
several keyframe effect fixes
[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
22 #include <QPainter>
23 #include <QTimer>
24 #include <QStyleOptionGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
27 #include <QScrollBar>
28 #include <QMimeData>
29 #include <QApplication>
30
31 #include <KDebug>
32
33 #include "clipitem.h"
34 #include "customtrackview.h"
35 #include "renderer.h"
36 #include "docclipbase.h"
37 #include "transition.h"
38 #include "events.h"
39 #include "kdenlivesettings.h"
40 #include "kthumb.h"
41
42 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, GenTime cropStart, double scale, double fps)
43         : AbstractClipItem(info, QRectF(), fps), m_clip(clip), m_resizeMode(NONE), m_grabPoint(0), m_maxTrack(0), m_hasThumbs(false), startThumbTimer(NULL), endThumbTimer(NULL), m_effectsCounter(1), audioThumbWasDrawn(false), m_opacity(1.0), m_timeLine(0), m_thumbsRequested(0), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1) {
44     QRectF rect((double) info.startPos.frames(fps) * scale, (double)(info.track * KdenliveSettings::trackheight() + 1), (double)(info.endPos - info.startPos).frames(fps) * scale, (double)(KdenliveSettings::trackheight() - 1));
45     setRect(rect);
46
47     m_clipName = clip->name();
48     m_producer = clip->getId();
49     m_clipType = clip->clipType();
50     m_cropStart = cropStart;
51     m_maxDuration = clip->maxDuration();
52     setAcceptDrops(true);
53     audioThumbReady = clip->audioThumbCreated();
54     /*m_keyframes[0] = 50;
55     m_keyframes[30] = 20;
56     m_keyframes[70] = 90;
57     m_keyframes[100] = 10;*/
58     /*
59       m_cropStart = xml.attribute("in", 0).toInt();
60       m_maxDuration = xml.attribute("duration", 0).toInt();
61       if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
62
63       if (duration != -1) m_cropDuration = duration;
64       else m_cropDuration = m_maxDuration;*/
65
66
67     setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
68     setAcceptsHoverEvents(true);
69     connect(this , SIGNAL(prepareAudioThumb(double, QPainterPath, int, int)) , this, SLOT(slotPrepareAudioThumb(double, QPainterPath, int, int)));
70
71     setBrush(QColor(141, 166, 215));
72     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) {
73         m_hasThumbs = true;
74         connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
75         connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
76         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
77         QTimer::singleShot(300, this, SLOT(slotFetchThumbs()));
78
79         startThumbTimer = new QTimer(this);
80         startThumbTimer->setSingleShot(true);
81         connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
82         endThumbTimer = new QTimer(this);
83         endThumbTimer->setSingleShot(true);
84         connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
85     } else if (m_clipType == COLOR) {
86         QString colour = clip->getProperty("colour");
87         colour = colour.replace(0, 2, "#");
88         setBrush(QColor(colour.left(7)));
89     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
90         m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
91         m_endPix = m_startPix;
92     } else if (m_clipType == AUDIO) {
93         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
94     }
95 }
96
97
98 ClipItem::~ClipItem() {
99     if (startThumbTimer) delete startThumbTimer;
100     if (endThumbTimer) delete endThumbTimer;
101 }
102
103 int ClipItem::selectedEffectIndex() const {
104     return m_selectedEffect;
105 }
106
107 void ClipItem::initEffect(QDomElement effect) {
108     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
109     // not be changed
110     if (effect.attribute("kdenlive_ix").toInt() == 0)
111         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
112     // init keyframes if required
113     QDomNodeList params = effect.elementsByTagName("parameter");
114     for (int i = 0; i < params.count(); i++) {
115         QDomElement e = params.item(i).toElement();
116         if (!e.isNull() && e.attribute("type") == "keyframe") {
117             double max = e.attribute("max").toDouble();
118             double min = e.attribute("min").toDouble();
119             double def = e.attribute("default").toDouble();
120             double factor = e.attribute("factor", "1").toDouble();
121
122             // Effect has a keyframe type parameter, we need to set the values
123             if (e.attribute("keyframes").isEmpty()) {
124                 // no keyframes defined, set up 2 keyframes (start and end) with default value.
125                 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + QString::number(100 * def / (max - min)) + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + QString::number(100 * def / (max - min)));
126                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
127                 break;
128             }
129         }
130     }
131 }
132
133
134 void ClipItem::setSelectedEffect(int ix) {
135     //if (ix == m_selectedEffect) return;
136     m_selectedEffect = ix;
137     QDomElement effect = effectAt(m_selectedEffect);
138     QDomNodeList params = effect.elementsByTagName("parameter");
139     for (int i = 0; i < params.count(); i++) {
140         QDomElement e = params.item(i).toElement();
141         if (!e.isNull() && e.attribute("type") == "keyframe") {
142             m_keyframes.clear();
143             double max = e.attribute("max").toDouble();
144             double min = e.attribute("min").toDouble();
145             double def = e.attribute("default").toDouble();
146             double factor = e.attribute("factor", "1").toDouble();
147
148             // Effect has a keyframe type parameter, we need to set the values
149             /*if (e.attribute("keyframes").isEmpty()) {
150                 // no keyframes defined, set up 2 keyframes (start and end) with default value.
151                 m_keyframes[m_cropStart.frames(m_fps)] = 100 * def / (max - min);
152                 m_keyframes[(m_cropStart + m_cropDuration).frames(m_fps)] = 100 * def / (max - min);
153             e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + QString::number(100 * def / (max - min)) + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + QString::number(100 * def / (max - min)));
154             } else {*/
155             // parse keyframes
156             QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
157             foreach(QString str, keyframes) {
158                 int pos = str.section(":", 0, 0).toInt();
159                 double val = str.section(":", 1, 1).toDouble();
160                 m_keyframes[pos] = val;
161                 //}
162             }
163             update();
164             return;
165         }
166     }
167     if (!m_keyframes.isEmpty()) {
168         m_keyframes.clear();
169         update();
170     }
171 }
172
173 void ClipItem::updateKeyframeEffect() {
174     QDomElement effect = effectAt(m_selectedEffect);
175     QDomNodeList params = effect.elementsByTagName("parameter");
176
177     for (int i = 0; i < params.count(); i++) {
178         QDomElement e = params.item(i).toElement();
179         if (!e.isNull() && e.attribute("type") == "keyframe") {
180             int max = e.attribute("max").toInt();
181             int min = e.attribute("min").toInt();
182             int def = e.attribute("default").toInt();
183             double factor = e.attribute("factor", "1").toDouble();
184             QString keyframes;
185
186             if (m_keyframes.count() > 1) {
187                 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
188                 double x1;
189                 double y1;
190                 while (i != m_keyframes.constEnd()) {
191                     keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
192                     ++i;
193                 }
194             }
195             // Effect has a keyframe type parameter, we need to set the values
196             kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
197             e.setAttribute("keyframes", keyframes);
198             break;
199         }
200     }
201 }
202
203 QDomElement ClipItem::selectedEffect() {
204     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
205     return effectAt(m_selectedEffect);
206 }
207
208 void ClipItem::resetThumbs() {
209     slotFetchThumbs();
210     audioThumbCachePic.clear();
211 }
212
213
214 void ClipItem::refreshClip() {
215     m_maxDuration = m_clip->maxDuration();
216     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) slotFetchThumbs();
217     else if (m_clipType == COLOR) {
218         QString colour = m_clip->getProperty("colour");
219         colour = colour.replace(0, 2, "#");
220         setBrush(QColor(colour.left(7)));
221     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
222         m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
223         m_endPix = m_startPix;
224     }
225 }
226
227 void ClipItem::slotFetchThumbs() {
228     m_thumbsRequested += 2;
229     emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps));
230 }
231
232 void ClipItem::slotGetStartThumb() {
233     m_thumbsRequested++;
234     emit getThumb((int)m_cropStart.frames(m_fps), -1);
235 }
236
237 void ClipItem::slotGetEndThumb() {
238     m_thumbsRequested++;
239     emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps));
240 }
241
242 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
243     if (m_thumbsRequested == 0) return;
244     if (frame == m_cropStart.frames(m_fps)) {
245         m_startPix = pix;
246         QRectF r = boundingRect();
247         r.setRight(pix.width() + 2);
248         update(r);
249     } else {
250         m_endPix = pix;
251         QRectF r = boundingRect();
252         r.setLeft(r.right() - pix.width() - 2);
253         update(r);
254     }
255     m_thumbsRequested--;
256 }
257
258 void ClipItem::slotGotAudioData() {
259     audioThumbReady = true;
260     if (m_clipType == AV) {
261         QRectF r = boundingRect();
262         r.setTop(r.top() + r.height() / 2 - 1);
263         update(r);
264     } else update();
265 }
266
267 int ClipItem::type() const {
268     return AVWIDGET;
269 }
270
271 DocClipBase *ClipItem::baseClip() const {
272     return m_clip;
273 }
274
275 QDomElement ClipItem::xml() const {
276     return m_clip->toXML();
277 }
278
279 int ClipItem::clipType() const {
280     return m_clipType;
281 }
282
283 QString ClipItem::clipName() const {
284     return m_clipName;
285 }
286
287 int ClipItem::clipProducer() const {
288     return m_producer;
289 }
290
291 void ClipItem::flashClip() {
292     if (m_timeLine == 0) {
293         m_timeLine = new QTimeLine(750, this);
294         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
295         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
296     }
297     m_timeLine->start();
298 }
299
300 void ClipItem::animate(qreal value) {
301     QRectF r = boundingRect();
302     r.setHeight(20);
303     update(r);
304 }
305
306 // virtual
307 void ClipItem::paint(QPainter *painter,
308                      const QStyleOptionGraphicsItem *option,
309                      QWidget *) {
310     painter->setOpacity(m_opacity);
311     QBrush paintColor = brush();
312     if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
313     QRectF br = rect();
314     double scale = br.width() / m_cropDuration.frames(m_fps);
315
316     // kDebug()<<"///   EXPOSED RECT: "<<option->exposedRect.x()<<" X "<<option->exposedRect.right();
317
318     int startpixel = (int)option->exposedRect.x() - rect().x();
319
320     if (startpixel < 0)
321         startpixel = 0;
322     int endpixel = (int)option->exposedRect.right() - rect().x();
323     if (endpixel < 0)
324         endpixel = 0;
325
326     //painter->setRenderHints(QPainter::Antialiasing);
327
328     QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
329     painter->setClipRect(option->exposedRect);
330
331     // build path around clip
332     QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
333     painter->fillPath(resultClipPath, paintColor);
334
335     painter->setClipPath(resultClipPath, Qt::IntersectClip);
336     // draw thumbnails
337     if (!m_startPix.isNull() && KdenliveSettings::videothumbnails()) {
338         if (m_clipType == IMAGE) {
339             painter->drawPixmap(QPointF(br.right() - m_startPix.width(), br.y()), m_startPix);
340             QLine l(br.right() - m_startPix.width(), br.y(), br.right() - m_startPix.width(), br.y() + br.height());
341             painter->drawLine(l);
342         } else {
343             painter->drawPixmap(QPointF(br.right() - m_endPix.width(), br.y()), m_endPix);
344             QLine l(br.right() - m_endPix.width(), br.y(), br.right() - m_endPix.width(), br.y() + br.height());
345             painter->drawLine(l);
346         }
347
348         painter->drawPixmap(QPointF(br.x(), br.y()), m_startPix);
349         QLine l2(br.x() + m_startPix.width(), br.y(), br.x() + m_startPix.width(), br.y() + br.height());
350         painter->drawLine(l2);
351     }
352
353     // draw audio thumbnails
354     if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && option->exposedRect.bottom() > br.height() / 2) || m_clipType == AUDIO) && audioThumbReady) {
355
356         QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;
357         if (m_clipType == AV) painter->fillPath(path, QBrush(QColor(200, 200, 200, 140)));
358
359         int channels = 2;
360         if (scale != framePixelWidth)
361             audioThumbCachePic.clear();
362         emit prepareAudioThumb(scale, path, startpixel, endpixel + 200);//200 more for less missing parts before repaint after scrolling
363         int cropLeft = (int)((m_cropStart).frames(m_fps) * scale);
364         for (int startCache = startpixel - startpixel % 100; startCache < endpixel + 300;startCache += 100) {
365             if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
366                 painter->drawPixmap((int)(roundRectPathUpper.united(roundRectPathLower).boundingRect().x() + startCache - cropLeft), (int)(path.boundingRect().y()), audioThumbCachePic[startCache]);
367         }
368     }
369
370     // draw markers
371     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
372     QList < CommentedTime >::Iterator it = markers.begin();
373     GenTime pos;
374     double framepos;
375     const int markerwidth = 4;
376     QBrush markerBrush;
377     markerBrush = QBrush(QColor(120, 120, 0, 100));
378     QPen pen = painter->pen();
379     pen.setColor(QColor(255, 255, 255, 200));
380     pen.setStyle(Qt::DotLine);
381     painter->setPen(pen);
382     for (; it != markers.end(); ++it) {
383         pos = (*it).time() - cropStart();
384         if (pos > GenTime()) {
385             if (pos > duration()) break;
386             framepos = scale * pos.frames(m_fps);
387             QLineF l(br.x() + framepos, br.y() + 5, br.x() + framepos, br.y() + br.height() - 5);
388             painter->drawLine(l);
389             if (KdenliveSettings::showmarkers()) {
390                 const QRectF txtBounding = painter->boundingRect(br.x() + framepos + 1, br.y() + 10, br.width() - framepos - 2, br.height() - 10, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
391                 QPainterPath path;
392                 path.addRoundedRect(txtBounding, 3, 3);
393                 painter->fillPath(path, markerBrush);
394                 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
395             }
396             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
397         }
398     }
399     pen.setColor(Qt::black);
400     pen.setStyle(Qt::SolidLine);
401     painter->setPen(pen);
402
403     // draw start / end fades
404     QBrush fades;
405     if (isSelected()) {
406         fades = QBrush(QColor(200, 50, 50, 150));
407     } else fades = QBrush(QColor(200, 200, 200, 200));
408
409     if (m_startFade != 0) {
410         QPainterPath fadeInPath;
411         fadeInPath.moveTo(br.x() , br.y());
412         fadeInPath.lineTo(br.x() , br.bottom());
413         fadeInPath.lineTo(br.x() + m_startFade * scale, br.y());
414         fadeInPath.closeSubpath();
415         painter->fillPath(fadeInPath/*.intersected(resultClipPath)*/, fades);
416         if (isSelected()) {
417             QLineF l(br.x() + m_startFade * scale, br.y(), br.x(), br.bottom());
418             painter->drawLine(l);
419         }
420     }
421     if (m_endFade != 0) {
422         QPainterPath fadeOutPath;
423         fadeOutPath.moveTo(br.right(), br.y());
424         fadeOutPath.lineTo(br.right(), br.bottom());
425         fadeOutPath.lineTo(br.right() - m_endFade * scale, br.y());
426         fadeOutPath.closeSubpath();
427         painter->fillPath(fadeOutPath/*.intersected(resultClipPath)*/, fades);
428         if (isSelected()) {
429             QLineF l(br.right() - m_endFade * scale, br.y(), br.x() + br.width(), br.bottom());
430             painter->drawLine(l);
431         }
432     }
433
434     // Draw effects names
435     if (!m_effectNames.isEmpty() && br.width() > 30) {
436         QRectF txtBounding = painter->boundingRect(br, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
437         txtBounding.setRight(txtBounding.right() + 15);
438         painter->setPen(Qt::white);
439         QBrush markerBrush(Qt::SolidPattern);
440         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
441             qreal value = m_timeLine->currentValue();
442             txtBounding.setWidth(txtBounding.width() * value);
443             markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
444         } else markerBrush.setColor(QColor(50, 50, 50, 150));
445         QPainterPath path;
446         path.addRoundedRect(txtBounding, 4, 4);
447         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
448         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
449         painter->setPen(Qt::black);
450     }
451
452     // Draw clip name
453     QRectF txtBounding = painter->boundingRect(br, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
454     //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
455     painter->setPen(QColor(0, 0, 0, 180));
456     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
457     txtBounding.translate(QPointF(1, 1));
458     painter->setPen(QColor(255, 255, 255, 255));
459     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
460     // draw frame around clip
461     if (isSelected()) {
462         pen.setColor(Qt::red);
463         //pen.setWidth(2);
464     } else {
465         pen.setColor(Qt::black);
466         //pen.setWidth(1);
467     }
468
469
470     // draw effect or transition keyframes
471     if (br.width() > 20) drawKeyFrames(painter, option->exposedRect);
472
473     // draw clip border
474     painter->setClipRect(option->exposedRect);
475     painter->setPen(pen);
476     //painter->setClipRect(option->exposedRect);
477     painter->drawPath(resultClipPath);
478
479     if (m_hover && br.width() > 30) {
480         painter->setBrush(QColor(180, 180, 50, 180)); //gradient);
481
482         // draw transitions handles
483         QPainterPath transitionHandle;
484         const int handle_size = 4;
485         transitionHandle.moveTo(0, 0);
486         transitionHandle.lineTo(handle_size, handle_size);
487         transitionHandle.lineTo(handle_size * 2, 0);
488         transitionHandle.lineTo(handle_size * 3, handle_size);
489         transitionHandle.lineTo(handle_size * 2, handle_size * 2);
490         transitionHandle.lineTo(handle_size * 3, handle_size * 3);
491         transitionHandle.lineTo(0, handle_size * 3);
492         transitionHandle.closeSubpath();
493         int pointy = (int)(br.y() + br.height() / 2);
494         int pointx1 = (int)(br.x() + 10);
495         int pointx2 = (int)(br.x() + br.width() - (10 + handle_size * 3));
496 #if 0
497         painter->setPen(QPen(Qt::black));
498         painter->setBrush(QBrush(QColor(50, 50, 0)));
499 #else
500         /*QRadialGradient gradient(pointx1 + 5, pointy + 5 , 5, 2, 2);
501         gradient.setColorAt(0.2, Qt::white);
502         gradient.setColorAt(0.8, Qt::yellow);
503         gradient.setColorAt(1, Qt::black);*/
504
505 #endif
506         painter->translate(pointx1, pointy);
507         painter->drawPath(transitionHandle); //Ellipse(0, 0 , 10, 10);
508         painter->translate(-pointx1, -pointy);
509
510         /*        QRadialGradient gradient1(pointx2 + 5, pointy + 5 , 5, 2, 2);
511                 gradient1.setColorAt(0.2, Qt::white);
512                 gradient1.setColorAt(0.8, Qt::yellow);
513                 gradient1.setColorAt(1, Qt::black);
514                 painter->setBrush(gradient1);*/
515         painter->translate(pointx2, pointy);
516         QMatrix m;
517         m.scale(-1.0, 1.0);
518         //painter->setMatrix(m);
519         painter->drawPath(transitionHandle); // Ellipse(0, 0, 10, 10);
520         //painter->setMatrix(m);
521         painter->translate(- pointx2, -pointy);
522     }
523 }
524
525
526 OPERATIONTYPE ClipItem::operationMode(QPointF pos, double scale) {
527     if (isSelected()) {
528         m_editedKeyframe = mouseOverKeyFrames(pos);
529         if (m_editedKeyframe != -1) return KEYFRAME;
530     }
531     if (qAbs((int)(pos.x() - (rect().x() + scale * m_startFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
532         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
533         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
534         return FADEIN;
535     } else if (qAbs((int)(pos.x() - rect().x())) < 6) {
536         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
537         return RESIZESTART;
538     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - scale * m_endFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
539         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
540         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
541         return FADEOUT;
542     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width()))) < 6) {
543         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
544         return RESIZEEND;
545     } else if (qAbs((int)(pos.x() - (rect().x() + 16))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
546         setToolTip(i18n("Add transition"));
547         return TRANSITIONSTART;
548     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - 21))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
549         setToolTip(i18n("Add transition"));
550         return TRANSITIONEND;
551     }
552     setToolTip(QString());
553     return MOVE;
554 }
555
556 QList <GenTime> ClipItem::snapMarkers() const {
557     QList < GenTime > snaps;
558     QList < GenTime > markers = baseClip()->snapMarkers();
559     GenTime pos;
560     double framepos;
561
562     for (int i = 0; i < markers.size(); i++) {
563         pos = markers.at(i) - cropStart();
564         if (pos > GenTime()) {
565             if (pos > duration()) break;
566             else snaps.append(pos + startPos());
567         }
568     }
569     return snaps;
570 }
571
572 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, QPainterPath path, int startpixel, int endpixel) {
573     int channels = 2;
574
575     QRectF re = path.boundingRect();
576
577     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
578
579     for (int startCache = startpixel - startpixel % 100;startCache + 100 < endpixel ;startCache += 100) {
580         //kDebug() << "creating " << startCache;
581         //if (framePixelWidth!=pixelForOneFrame  ||
582         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
583             continue;
584         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
585             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
586             audioThumbCachePic[startCache].fill(QColor(200, 200, 200, 0));
587         }
588         bool fullAreaDraw = pixelForOneFrame < 10;
589         QMap<int, QPainterPath > positiveChannelPaths;
590         QMap<int, QPainterPath > negativeChannelPaths;
591         QPainter pixpainter(&audioThumbCachePic[startCache]);
592         QPen audiopen;
593         audiopen.setWidth(0);
594         pixpainter.setPen(audiopen);
595         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
596         //pixpainter.drawLine(0,0,100,re.height());
597         int channelHeight = audioThumbCachePic[startCache].height() / channels;
598
599         for (int i = 0;i < channels;i++) {
600
601             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
602             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
603         }
604
605         for (int samples = 0;samples <= 100;samples++) {
606             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
607             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
608             if (frame < 0 || sample < 0 || sample > 19)
609                 continue;
610             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
611
612             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
613
614                 int y = channelHeight * channel + channelHeight / 2;
615                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
616                 if (fullAreaDraw) {
617                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
618                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
619                 } else {
620                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
621                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
622                 }
623             }
624             for (int channel = 0;channel < channels ;channel++)
625                 if (fullAreaDraw && samples == 100) {
626                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
627                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
628                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
629                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
630                 }
631
632         }
633         if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
634         else {
635             pixpainter.setPen(QPen(QColor(0, 0, 0)));
636             pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
637         }
638         for (int i = 0;i < channels;i++) {
639             if (fullAreaDraw) {
640                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
641                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
642             } else
643                 pixpainter.drawPath(positiveChannelPaths[i]);
644         }
645     }
646     //audioThumbWasDrawn=true;
647     framePixelWidth = pixelForOneFrame;
648
649     //}
650 }
651
652 uint ClipItem::fadeIn() const {
653     return m_startFade;
654 }
655
656 uint ClipItem::fadeOut() const {
657     return m_endFade;
658 }
659
660
661 void ClipItem::setFadeIn(int pos, double scale) {
662     int oldIn = m_startFade;
663     if (pos < 0) pos = 0;
664     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
665     m_startFade = pos;
666     update(rect().x(), rect().y(), qMax(oldIn, pos) * scale, rect().height());
667 }
668
669 void ClipItem::setFadeOut(int pos, double scale) {
670     int oldOut = m_endFade;
671     if (pos < 0) pos = 0;
672     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
673     m_endFade = pos;
674     update(rect().x() + rect().width() - qMax(oldOut, pos) * scale, rect().y(), pos * scale, rect().height());
675
676 }
677
678 // virtual
679 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
680     /*m_resizeMode = operationMode(event->pos());
681     if (m_resizeMode == MOVE) {
682       m_maxTrack = scene()->sceneRect().height();
683       m_grabPoint = (int) (event->pos().x() - rect().x());
684     }*/
685     QGraphicsRectItem::mousePressEvent(event);
686 }
687
688 // virtual
689 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
690     m_resizeMode = NONE;
691     QGraphicsRectItem::mouseReleaseEvent(event);
692 }
693
694 //virtual
695 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *) {
696     m_hover = true;
697     QRectF r = boundingRect();
698     qreal width = qMin(25.0, r.width());
699     update(r.x(), r.y(), width, r.height());
700     update(r.right() - width, r.y(), width, r.height());
701 }
702
703 //virtual
704 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
705     m_hover = false;
706     QRectF r = boundingRect();
707     qreal width = qMin(25.0, r.width());
708     update(r.x(), r.y(), width, r.height());
709     update(r.right() - width, r.y(), width, r.height());
710 }
711
712 void ClipItem::resizeStart(int posx, double scale) {
713     const int previous = cropStart().frames(m_fps);
714     AbstractClipItem::resizeStart(posx, scale);
715     checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
716     if (m_hasThumbs && KdenliveSettings::videothumbnails()) startThumbTimer->start(100);
717 }
718
719 void ClipItem::resizeEnd(int posx, double scale) {
720     const int previous = (cropStart() + duration()).frames(m_fps);
721     AbstractClipItem::resizeEnd(posx, scale);
722     checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
723     if (m_hasThumbs && KdenliveSettings::videothumbnails()) endThumbTimer->start(100);
724 }
725
726
727 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
728     for (int i = 0; i < m_effectList.size(); i++) {
729         QDomElement effect = m_effectList.at(i);
730         QDomNodeList params = effect.elementsByTagName("parameter");
731         for (int j = 0; j < params.count(); j++) {
732             QDomElement e = params.item(i).toElement();
733             if (e.attribute("type") == "keyframe") {
734                 // parse keyframes and adjust values
735                 QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
736                 QMap <int, double> kfr;
737                 foreach(QString str, keyframes) {
738                     int pos = str.section(":", 0, 0).toInt();
739                     double val = str.section(":", 1, 1).toDouble();
740                     if (pos == previous) kfr[current] = val;
741                     else {
742                         if (fromStart && pos >= current) kfr[pos] = val;
743                         else if (!fromStart && pos <= current) kfr[pos] = val;
744                     }
745                 }
746                 QString newkfr;
747                 QMap<int, double>::const_iterator k = kfr.constBegin();
748                 while (k != kfr.constEnd()) {
749                     newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
750                     ++k;
751                 }
752                 e.setAttribute("keyframes", newkfr);
753                 break;
754             }
755         }
756     }
757     setSelectedEffect(m_selectedEffect);
758 }
759
760
761 // virtual
762 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
763 }*/
764
765 int ClipItem::effectsCounter() {
766     return m_effectsCounter++;
767 }
768
769 int ClipItem::effectsCount() {
770     return m_effectList.size();
771 }
772
773 QStringList ClipItem::effectNames() {
774     return m_effectList.effectNames();
775 }
776
777 QDomElement ClipItem::effectAt(int ix) {
778     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
779     return m_effectList.at(ix);
780 }
781
782 void ClipItem::setEffectAt(int ix, QDomElement effect) {
783     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
784     m_effectList.insert(ix, effect);
785     m_effectList.removeAt(ix + 1);
786     m_effectNames = m_effectList.effectNames().join(" / ");
787     if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
788     else {
789         QRectF r = boundingRect();
790         r.setHeight(20);
791         update(r);
792     }
793 }
794
795 QMap <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
796     QMap <QString, QString> effectParams;
797     bool needRepaint = false;
798     /*QDomDocument doc;
799     doc.appendChild(doc.importNode(effect, true));
800     kDebug() << "///////  CLIP ADD EFFECT: "<< doc.toString();*/
801     m_effectList.append(effect);
802     effectParams["tag"] = effect.attribute("tag");
803     QString effectId = effect.attribute("id");
804     if (effectId.isEmpty()) effectId = effect.attribute("tag");
805     effectParams["id"] = effectId;
806     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
807     QString state = effect.attribute("disabled");
808     if (!state.isEmpty()) effectParams["disabled"] = state;
809     QDomNodeList params = effect.elementsByTagName("parameter");
810     int fade = 0;
811     for (int i = 0; i < params.count(); i++) {
812         QDomElement e = params.item(i).toElement();
813         if (!e.isNull()) {
814             if (e.attribute("type") == "keyframe") {
815                 effectParams["keyframes"] = e.attribute("keyframes");
816                 effectParams["min"] = e.attribute("min");
817                 effectParams["max"] = e.attribute("max");
818                 effectParams["factor"] = e.attribute("factor", "1");
819                 effectParams["starttag"] = e.attribute("starttag", "start");
820                 effectParams["endtag"] = e.attribute("endtag", "end");
821             }
822
823             double f = e.attribute("factor", "1").toDouble();
824
825             if (f == 1) {
826                 effectParams[e.attribute("name")] = e.attribute("value");
827                 // check if it is a fade effect
828                 if (effectId == "fadein") {
829                     needRepaint = true;
830                     if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
831                     else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
832                 } else if (effectId == "fadeout") {
833                     needRepaint = true;
834                     if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
835                     else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
836                 }
837             } else {
838                 effectParams[e.attribute("name")] =  QString::number(effectParams[e.attribute("name")].toDouble() / f);
839             }
840         }
841     }
842     m_effectNames = m_effectList.effectNames().join(" / ");
843     if (fade > 0) m_startFade = fade;
844     else if (fade < 0) m_endFade = -fade;
845     if (needRepaint) update(boundingRect());
846     if (animate) {
847         flashClip();
848     } else if (!needRepaint) {
849         QRectF r = boundingRect();
850         r.setHeight(20);
851         update(r);
852     }
853     return effectParams;
854 }
855
856 QMap <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
857     QMap <QString, QString> effectParams;
858     effectParams["tag"] = effect.attribute("tag");
859     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
860     effectParams["id"] = effect.attribute("id");
861     QString state = effect.attribute("disabled");
862     if (!state.isEmpty()) effectParams["disabled"] = state;
863     QDomNodeList params = effect.elementsByTagName("parameter");
864     for (int i = 0; i < params.count(); i++) {
865         QDomElement e = params.item(i).toElement();
866         kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
867         if (e.attribute("type") == "keyframe") {
868             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
869             effectParams["keyframes"] = e.attribute("keyframes");
870             effectParams["max"] = e.attribute("max");
871             effectParams["min"] = e.attribute("min");
872             effectParams["factor"] = e.attribute("factor", "1");
873             effectParams["starttag"] = e.attribute("starttag", "start");
874             effectParams["endtag"] = e.attribute("endtag", "end");
875         } else if (e.attribute("namedesc").contains(";")) {
876             QString format = e.attribute("format");
877             QStringList separators = format.split("%d", QString::SkipEmptyParts);
878             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
879             QString neu;
880             QTextStream txtNeu(&neu);
881             if (values.size() > 0)
882                 txtNeu << (int)values[0].toDouble();
883             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
884                 txtNeu << separators[i];
885                 txtNeu << (int)(values[i+1].toDouble());
886             }
887             effectParams["start"] = neu;
888         } else {
889             if (e.attribute("factor", "1") != "1")
890                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
891             else effectParams[e.attribute("name")] = e.attribute("value");
892         }
893     }
894     return effectParams;
895 }
896
897 void ClipItem::deleteEffect(QString index) {
898     bool needRepaint = false;
899     for (int i = 0; i < m_effectList.size(); ++i) {
900         if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
901             if (m_effectList.at(i).attribute("id") == "fadein") {
902                 m_startFade = 0;
903                 needRepaint = true;
904             } else if (m_effectList.at(i).attribute("id") == "fadeout") {
905                 m_endFade = 0;
906                 needRepaint = true;
907             }
908             m_effectList.removeAt(i);
909             break;
910         }
911     }
912     m_effectNames = m_effectList.effectNames().join(" / ");
913     if (needRepaint) update(boundingRect());
914     flashClip();
915 }
916
917 //virtual
918 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
919     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
920     QDomDocument doc;
921     doc.setContent(effects, true);
922     QDomElement e = doc.documentElement();
923     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
924     if (view) view->slotAddEffect(e, m_startPos, track());
925 }
926
927 //virtual
928 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
929     event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
930 }
931
932 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
933     Q_UNUSED(event);
934 }
935 void ClipItem::addTransition(Transition* t) {
936     m_transitionsList.append(t);
937     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
938     QDomDocument doc;
939     QDomElement e = doc.documentElement();
940     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
941 }
942 // virtual
943 /*
944 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
945 {
946   int pos = event->x();
947   if (event->modifiers() == Qt::ControlModifier)
948     setDragMode(QGraphicsView::ScrollHandDrag);
949   else if (event->modifiers() == Qt::ShiftModifier)
950     setDragMode(QGraphicsView::RubberBandDrag);
951   else {
952     QGraphicsItem * item = itemAt(event->pos());
953     if (item) {
954     }
955     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
956   }
957   kDebug()<<pos;
958   QGraphicsView::mousePressEvent(event);
959 }
960
961 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
962 {
963   QGraphicsView::mouseReleaseEvent(event);
964   setDragMode(QGraphicsView::NoDrag);
965 }
966 */
967
968 #include "clipitem.moc"