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