1 /***************************************************************************
2 * Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
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. *
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. *
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 ***************************************************************************/
24 #include <QStyleOptionGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
29 #include <QApplication>
34 #include "customtrackview.h"
35 #include "customtrackscene.h"
37 #include "docclipbase.h"
38 #include "transition.h"
39 #include "kdenlivesettings.h"
43 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps)
44 : 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_startThumbRequested(false), m_endThumbRequested(false), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1), m_speed(1.0), framePixelWidth(0), m_startPix(QPixmap()), m_endPix(QPixmap()) {
45 setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (qreal)(KdenliveSettings::trackheight() - 2));
46 setPos((qreal) info.startPos.frames(fps), (qreal)(info.track * KdenliveSettings::trackheight()) + 1);
48 m_clipName = clip->name();
49 m_producer = clip->getId();
50 m_clipType = clip->clipType();
51 m_cropStart = info.cropStart;
52 m_maxDuration = clip->maxDuration();
54 audioThumbReady = clip->audioThumbCreated();
57 m_cropStart = xml.attribute("in", 0).toInt();
58 m_maxDuration = xml.attribute("duration", 0).toInt();
59 if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
61 if (duration != -1) m_cropDuration = duration;
62 else m_cropDuration = m_maxDuration;*/
65 setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
66 setAcceptsHoverEvents(true);
67 connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
69 setBrush(QColor(141, 166, 215));
70 if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
72 startThumbTimer = new QTimer(this);
73 startThumbTimer->setSingleShot(true);
74 connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
75 endThumbTimer = new QTimer(this);
76 endThumbTimer->setSingleShot(true);
77 connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
79 connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
80 connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
81 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
82 QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
84 /*if (m_clip->producer()) {
85 videoThumbProducer.init(this, m_clip->producer(), KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio(), KdenliveSettings::trackheight());
88 } else if (m_clipType == COLOR) {
89 QString colour = clip->getProperty("colour");
90 colour = colour.replace(0, 2, "#");
91 setBrush(QColor(colour.left(7)));
92 } else if (m_clipType == IMAGE || m_clipType == TEXT) {
93 m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
94 m_endPix = m_startPix;
95 } else if (m_clipType == AUDIO) {
96 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
101 ClipItem::~ClipItem() {
102 if (startThumbTimer) delete startThumbTimer;
103 if (endThumbTimer) delete endThumbTimer;
104 if (m_timeLine) m_timeLine;
107 ClipItem *ClipItem::clone(ItemInfo info) const {
108 ClipItem *duplicate = new ClipItem(m_clip, info, m_fps);
109 if (info.cropStart == cropStart()) duplicate->slotSetStartThumb(m_startPix);
110 if (info.cropStart + (info.endPos - info.startPos) == m_cropStart + m_cropDuration) duplicate->slotSetEndThumb(m_endPix);
111 kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
112 duplicate->setEffectList(m_effectList);
113 duplicate->setSpeed(m_speed);
117 void ClipItem::setEffectList(const EffectsList effectList) {
118 m_effectList = effectList;
119 m_effectNames = m_effectList.effectNames().join(" / ");
122 const EffectsList ClipItem::effectList() {
126 int ClipItem::selectedEffectIndex() const {
127 return m_selectedEffect;
130 void ClipItem::initEffect(QDomElement effect) {
131 // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
133 if (effect.attribute("kdenlive_ix").toInt() == 0)
134 effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
135 // init keyframes if required
136 QDomNodeList params = effect.elementsByTagName("parameter");
137 for (int i = 0; i < params.count(); i++) {
138 QDomElement e = params.item(i).toElement();
139 if (!e.isNull() && e.attribute("type") == "keyframe") {
140 QString def = e.attribute("default");
141 // Effect has a keyframe type parameter, we need to set the values
142 if (e.attribute("keyframes").isEmpty()) {
143 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
144 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
151 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
152 QDomElement effect = effectAt(ix);
153 if (effect.attribute("disabled") == "1") return;
154 QDomNodeList params = effect.elementsByTagName("parameter");
155 for (int i = 0; i < params.count(); i++) {
156 QDomElement e = params.item(i).toElement();
157 if (!e.isNull() && e.attribute("type") == "keyframe") {
158 e.setAttribute("keyframes", keyframes);
159 if (ix == m_selectedEffect) {
161 double max = e.attribute("max").toDouble();
162 double min = e.attribute("min").toDouble();
163 m_keyframeFactor = 100.0 / (max - min);
164 m_keyframeDefault = e.attribute("default").toDouble();
166 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
167 foreach(const QString str, keyframes) {
168 int pos = str.section(":", 0, 0).toInt();
169 double val = str.section(":", 1, 1).toDouble();
170 m_keyframes[pos] = val;
181 void ClipItem::setSelectedEffect(const int ix) {
182 m_selectedEffect = ix;
183 QDomElement effect = effectAt(m_selectedEffect);
184 QDomNodeList params = effect.elementsByTagName("parameter");
185 if (effect.attribute("disabled") != "1")
186 for (int i = 0; i < params.count(); i++) {
187 QDomElement e = params.item(i).toElement();
188 if (!e.isNull() && e.attribute("type") == "keyframe") {
190 double max = e.attribute("max").toDouble();
191 double min = e.attribute("min").toDouble();
192 m_keyframeFactor = 100.0 / (max - min);
193 m_keyframeDefault = e.attribute("default").toDouble();
195 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
196 foreach(const QString str, keyframes) {
197 int pos = str.section(":", 0, 0).toInt();
198 double val = str.section(":", 1, 1).toDouble();
199 m_keyframes[pos] = val;
205 if (!m_keyframes.isEmpty()) {
211 QString ClipItem::keyframes(const int index) {
213 QDomElement effect = effectAt(index);
214 QDomNodeList params = effect.elementsByTagName("parameter");
216 for (int i = 0; i < params.count(); i++) {
217 QDomElement e = params.item(i).toElement();
218 if (!e.isNull() && e.attribute("type") == "keyframe") {
219 result = e.attribute("keyframes");
226 void ClipItem::updateKeyframeEffect() {
227 // regenerate xml parameter from the clip keyframes
228 QDomElement effect = effectAt(m_selectedEffect);
229 if (effect.attribute("disabled") == "1") return;
230 QDomNodeList params = effect.elementsByTagName("parameter");
232 for (int i = 0; i < params.count(); i++) {
233 QDomElement e = params.item(i).toElement();
234 if (!e.isNull() && e.attribute("type") == "keyframe") {
236 if (m_keyframes.count() > 1) {
237 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
240 while (i != m_keyframes.constEnd()) {
241 keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
245 // Effect has a keyframe type parameter, we need to set the values
246 //kDebug() << "::::::::::::::: SETTING EFFECT KEYFRAMES: " << keyframes;
247 e.setAttribute("keyframes", keyframes);
253 QDomElement ClipItem::selectedEffect() {
254 if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
255 return effectAt(m_selectedEffect);
258 void ClipItem::resetThumbs() {
259 m_startPix = QPixmap();
260 m_endPix = QPixmap();
262 audioThumbCachePic.clear();
266 void ClipItem::refreshClip() {
267 m_maxDuration = m_clip->maxDuration();
268 if (m_clipType == COLOR) {
269 QString colour = m_clip->getProperty("colour");
270 colour = colour.replace(0, 2, "#");
271 setBrush(QColor(colour.left(7)));
272 } else slotFetchThumbs();
275 void ClipItem::slotFetchThumbs() {
276 if (m_endPix.isNull() && m_startPix.isNull()) {
277 m_startThumbRequested = true;
278 m_endThumbRequested = true;
279 emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
281 if (m_endPix.isNull()) {
284 if (m_startPix.isNull()) {
290 if (m_endPix.isNull() && m_startPix.isNull()) {
291 int frame1 = (int)m_cropStart.frames(m_fps);
292 int frame2 = (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1;
293 //videoThumbProducer.setThumbFrames(m_clip->producer(), frame1, frame2);
294 //videoThumbProducer.start(QThread::LowestPriority);
296 if (m_endPix.isNull()) slotGetEndThumb();
297 else slotGetStartThumb();
300 } else if (m_startPix.isNull()) slotGetStartThumb();*/
303 void ClipItem::slotGetStartThumb() {
304 m_startThumbRequested = true;
305 emit getThumb((int)m_cropStart.frames(m_fps), -1);
306 //videoThumbProducer.setThumbFrames(m_clip->producer(), (int)m_cropStart.frames(m_fps), - 1);
307 //videoThumbProducer.start(QThread::LowestPriority);
310 void ClipItem::slotGetEndThumb() {
311 m_endThumbRequested = true;
312 emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
313 //videoThumbProducer.setThumbFrames(m_clip->producer(), -1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
314 //videoThumbProducer.start(QThread::LowestPriority);
318 void ClipItem::slotSetStartThumb(QImage img) {
319 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
320 QPixmap pix = QPixmap::fromImage(img);
322 QRectF r = sceneBoundingRect();
323 r.setRight(pix.width() + 2);
328 void ClipItem::slotSetEndThumb(QImage img) {
329 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
330 QPixmap pix = QPixmap::fromImage(img);
332 QRectF r = sceneBoundingRect();
333 r.setLeft(r.right() - pix.width() - 2);
338 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
339 if (scene() == NULL) return;
340 QRectF r = sceneBoundingRect();
341 double width = m_startPix.width() / projectScene()->scale();
342 if (m_startThumbRequested && frame == m_cropStart.frames(m_fps)) {
344 m_startThumbRequested = false;
345 double height = r.height();
346 update(r.x(), r.y(), width, height);
347 } else if (m_endThumbRequested && frame == (m_cropStart + m_cropDuration).frames(m_fps) - 1) {
349 m_endThumbRequested = false;
350 double height = r.height();
351 update(r.right() - width, r.y(), width, height);
355 void ClipItem::slotSetStartThumb(QPixmap pix) {
359 void ClipItem::slotSetEndThumb(QPixmap pix) {
363 void ClipItem::slotGotAudioData() {
364 audioThumbReady = true;
365 if (m_clipType == AV) {
366 QRectF r = boundingRect();
367 r.setTop(r.top() + r.height() / 2 - 1);
372 int ClipItem::type() const {
376 DocClipBase *ClipItem::baseClip() const {
380 QDomElement ClipItem::xml() const {
381 return m_clip->toXML();
384 int ClipItem::clipType() const {
388 QString ClipItem::clipName() const {
392 const QString &ClipItem::clipProducer() const {
396 void ClipItem::flashClip() {
397 if (m_timeLine == 0) {
398 m_timeLine = new QTimeLine(750, this);
399 m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
400 connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
405 void ClipItem::animate(qreal value) {
406 QRectF r = boundingRect();
412 void ClipItem::paint(QPainter *painter,
413 const QStyleOptionGraphicsItem *option,
415 painter->setOpacity(m_opacity);
416 QBrush paintColor = brush();
417 if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
419 QRectF exposed = option->exposedRect;
420 QRectF mapped = painter->matrix().mapRect(br);
422 const double itemWidth = br.width();
423 const double itemHeight = br.height();
424 const double scale = option->matrix.m11();
428 //painter->setRenderHints(QPainter::Antialiasing);
430 //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
431 painter->setClipRect(exposed);
433 // build path around clip
434 //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
435 //painter->fillPath(resultClipPath, paintColor);
436 painter->fillRect(br, paintColor);
438 //painter->setClipPath(resultClipPath, Qt::IntersectClip);
441 painter->setMatrixEnabled(false);
443 if (KdenliveSettings::videothumbnails()) {
444 QPen pen = painter->pen();
445 pen.setStyle(Qt::DotLine);
446 pen.setColor(Qt::white);
447 painter->setPen(pen);
448 if (m_clipType == IMAGE && !m_startPix.isNull()) {
449 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
450 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
451 painter->drawPixmap(p1, m_startPix);
453 painter->drawLine(l);
454 } else if (!m_endPix.isNull()) {
455 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
456 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
457 painter->drawPixmap(p1, m_endPix);
459 painter->drawLine(l);
461 if (!m_startPix.isNull()) {
462 QPointF p1 = painter->matrix().map(QPointF(0, 0));
463 QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
464 painter->drawPixmap(p1, m_startPix);
465 QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
466 painter->drawLine(l2);
468 painter->setPen(Qt::black);
471 // draw audio thumbnails
472 if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && exposed.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
474 double startpixel = exposed.left();
477 double endpixel = exposed.right();
480 //kDebug()<<"/// REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
482 /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
484 if (m_clipType == AV) {
486 re.setTop(re.y() + re.height() / 2);
487 mappedRect = painter->matrix().mapRect(re);
488 //painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
489 } else mappedRect = mapped;
491 int channels = baseClip()->getProperty("channels").toInt();
492 if (scale != framePixelWidth)
493 audioThumbCachePic.clear();
494 double cropLeft = m_cropStart.frames(m_fps);
495 const int clipStart = mappedRect.x();
496 const int mappedStartPixel = painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
497 const int mappedEndPixel = painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
498 cropLeft = cropLeft * scale;
500 emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
502 for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
503 if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
504 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(), audioThumbCachePic[startCache]);
509 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
510 QList < CommentedTime >::Iterator it = markers.begin();
513 const int markerwidth = 4;
515 markerBrush = QBrush(QColor(120, 120, 0, 140));
516 QPen pen = painter->pen();
517 pen.setColor(QColor(255, 255, 255, 200));
518 pen.setStyle(Qt::DotLine);
519 painter->setPen(pen);
520 for (; it != markers.end(); ++it) {
521 pos = (*it).time() - cropStart();
522 if (pos > GenTime()) {
523 if (pos > duration()) break;
524 QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
525 QLineF l2 = painter->matrix().map(l);
526 //framepos = scale * pos.frames(m_fps);
527 //QLineF l(framepos, 5, framepos, itemHeight - 5);
528 painter->drawLine(l2);
529 if (KdenliveSettings::showmarkers()) {
530 framepos = br.x() + pos.frames(m_fps);
531 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
532 const QRectF r2 = painter->matrix().mapRect(r1);
533 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
536 path.addRoundedRect(txtBounding, 3, 3);
537 painter->fillPath(path, markerBrush);
538 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
540 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
543 pen.setColor(Qt::black);
544 pen.setStyle(Qt::SolidLine);
545 painter->setPen(pen);
547 // draw start / end fades
550 fades = QBrush(QColor(200, 50, 50, 150));
551 } else fades = QBrush(QColor(200, 200, 200, 200));
553 if (m_startFade != 0) {
554 QPainterPath fadeInPath;
555 fadeInPath.moveTo(0, 0);
556 fadeInPath.lineTo(0, itemHeight);
557 fadeInPath.lineTo(m_startFade, 0);
558 fadeInPath.closeSubpath();
559 QPainterPath f1 = painter->matrix().map(fadeInPath);
560 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
561 /*if (isSelected()) {
562 QLineF l(m_startFade * scale, 0, 0, itemHeight);
563 painter->drawLine(l);
566 if (m_endFade != 0) {
567 QPainterPath fadeOutPath;
568 fadeOutPath.moveTo(itemWidth, 0);
569 fadeOutPath.lineTo(itemWidth, itemHeight);
570 fadeOutPath.lineTo(itemWidth - m_endFade, 0);
571 fadeOutPath.closeSubpath();
572 QPainterPath f1 = painter->matrix().map(fadeOutPath);
573 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
574 /*if (isSelected()) {
575 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
576 painter->drawLine(l);
580 // Draw effects names
581 if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
582 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
583 txtBounding.setRight(txtBounding.right() + 15);
584 painter->setPen(Qt::white);
585 QBrush markerBrush(Qt::SolidPattern);
586 if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
587 qreal value = m_timeLine->currentValue();
588 txtBounding.setWidth(txtBounding.width() * value);
589 markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
590 } else markerBrush.setColor(QColor(50, 50, 50, 150));
592 path.addRoundedRect(txtBounding, 4, 4);
593 painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
594 painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
595 painter->setPen(Qt::black);
600 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
601 //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
602 painter->setPen(QColor(0, 0, 0, 180));
603 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
604 txtBounding.translate(QPointF(1, 1));
605 painter->setPen(QColor(255, 255, 255, 255));
606 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
609 // draw transition handles on hover
610 if (m_hover && itemWidth * scale > 40) {
611 QPainterPath transitionHandle;
612 const int handle_size = 4;
613 QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
614 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
615 p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(10 + handle_size * 3, 0);
616 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
620 // draw frame around clip
622 pen.setColor(Qt::red);
625 pen.setColor(Qt::black);
629 // draw effect or transition keyframes
630 if (itemWidth > 20) drawKeyFrames(painter, exposed);
632 painter->setMatrixEnabled(true);
636 //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
638 exposed.setRight(exposed.right() + 1);
639 exposed.setBottom(exposed.bottom() + 1);
640 painter->setClipRect(exposed);
641 //painter->setClipping(false);
642 //painter->fillRect(exposed, Qt::blue);
643 painter->setPen(pen);
644 painter->drawRect(br);
648 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
650 m_editedKeyframe = mouseOverKeyFrames(pos);
651 if (m_editedKeyframe != -1) return KEYFRAME;
653 QRectF rect = sceneBoundingRect();
654 const double scale = projectScene()->scale();
655 double maximumOffset;
656 if (scale > 3) maximumOffset = 25 / scale;
657 else maximumOffset = 6 / scale;
659 matrix.scale(scale, 0);
660 //kDebug()<<"// Item rect: "<<rect.x()<<". pos. "<<pos.x()<<", scale: "<<scale<<", ratio: "<<qAbs((int)(pos.x() - rect.x())) / scale;
662 if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
663 if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
664 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
666 } else if (pos.x() - rect.x() < maximumOffset) {
667 setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
669 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
670 if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
671 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
673 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
674 setToolTip(i18n("Clip duration: %1s", duration().seconds()));
676 } else if (qAbs((int)(pos.x() - (rect.x() + 16))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
677 setToolTip(i18n("Add transition"));
678 return TRANSITIONSTART;
679 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
680 setToolTip(i18n("Add transition"));
681 return TRANSITIONEND;
683 setToolTip(QString());
687 QList <GenTime> ClipItem::snapMarkers() const {
688 QList < GenTime > snaps;
689 QList < GenTime > markers = baseClip()->snapMarkers();
693 for (int i = 0; i < markers.size(); i++) {
694 pos = markers.at(i) - cropStart();
695 if (pos > GenTime()) {
696 if (pos > duration()) break;
697 else snaps.append(pos + startPos());
703 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
704 QList < CommentedTime > snaps;
705 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
709 for (int i = 0; i < markers.size(); i++) {
710 pos = markers.at(i).time() - cropStart();
711 if (pos > GenTime()) {
712 if (pos > duration()) break;
713 else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
719 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
721 QRectF re = sceneBoundingRect();
722 if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
724 //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
725 //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
727 for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
728 //kDebug() << "creating " << startCache;
729 //if (framePixelWidth!=pixelForOneFrame ||
730 if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
732 if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
733 audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
734 audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
736 bool fullAreaDraw = pixelForOneFrame < 10;
737 QMap<int, QPainterPath > positiveChannelPaths;
738 QMap<int, QPainterPath > negativeChannelPaths;
739 QPainter pixpainter(&audioThumbCachePic[startCache]);
741 audiopen.setWidth(0);
742 pixpainter.setPen(audiopen);
743 //pixpainter.setRenderHint(QPainter::Antialiasing,true);
744 //pixpainter.drawLine(0,0,100,re.height());
745 int channelHeight = audioThumbCachePic[startCache].height() / channels;
747 for (int i = 0;i < channels;i++) {
749 positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
750 negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
753 for (int samples = 0;samples <= 100;samples++) {
754 double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
755 int sample = (int)((frame - (int)(frame)) * 20); // AUDIO_FRAME_SIZE
756 if (frame < 0 || sample < 0 || sample > 19)
758 QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
760 for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
762 int y = channelHeight * channel + channelHeight / 2;
763 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2) * channelHeight / 64;
765 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
766 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
768 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
769 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
772 for (int channel = 0;channel < channels ;channel++)
773 if (fullAreaDraw && samples == 100) {
774 positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
775 negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
776 positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
777 negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
781 if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
783 pixpainter.setPen(QPen(QColor(0, 0, 0)));
784 pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
786 for (int i = 0;i < channels;i++) {
788 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
789 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
791 pixpainter.drawPath(positiveChannelPaths[i]);
794 //audioThumbWasDrawn=true;
795 framePixelWidth = pixelForOneFrame;
800 uint ClipItem::fadeIn() const {
804 uint ClipItem::fadeOut() const {
809 void ClipItem::setFadeIn(int pos) {
810 int oldIn = m_startFade;
811 if (pos < 0) pos = 0;
812 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
814 QRectF rect = boundingRect();
815 update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
818 void ClipItem::setFadeOut(int pos) {
819 int oldOut = m_endFade;
820 if (pos < 0) pos = 0;
821 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
823 QRectF rect = boundingRect();
824 update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
829 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
830 /*m_resizeMode = operationMode(event->pos());
831 if (m_resizeMode == MOVE) {
832 m_maxTrack = scene()->sceneRect().height();
833 m_grabPoint = (int) (event->pos().x() - rect().x());
835 QGraphicsRectItem::mousePressEvent(event);
839 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
841 QGraphicsRectItem::mouseReleaseEvent(event);
845 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
846 //if (e->pos().x() < 20) m_hover = true;
848 QRectF r = boundingRect();
849 double width = 35 / projectScene()->scale();
850 double height = r.height() / 2;
851 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
852 update(r.x(), r.y() + height, width, height);
853 update(r.right() - width, r.y() + height, width, height);
857 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
859 QRectF r = boundingRect();
860 double width = 35 / projectScene()->scale();
861 double height = r.height() / 2;
862 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
863 update(r.x(), r.y() + height, width, height);
864 update(r.right() - width, r.y() + height, width, height);
867 void ClipItem::resizeStart(int posx) {
868 const int min = (startPos() - cropStart()).frames(m_fps);
869 if (posx < min) posx = min;
870 if (posx == startPos().frames(m_fps)) return;
871 const int previous = cropStart().frames(m_fps);
872 AbstractClipItem::resizeStart(posx);
873 checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
874 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
875 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
876 startThumbTimer->start(100);
880 void ClipItem::resizeEnd(int posx) {
881 const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
882 if (posx > max) posx = max;
883 if (posx == endPos().frames(m_fps)) return;
884 const int previous = (cropStart() + duration()).frames(m_fps);
885 AbstractClipItem::resizeEnd(posx);
886 checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
887 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
888 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
889 endThumbTimer->start(100);
894 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
895 for (int i = 0; i < m_effectList.size(); i++) {
896 QDomElement effect = m_effectList.at(i);
897 QDomNodeList params = effect.elementsByTagName("parameter");
898 for (int j = 0; j < params.count(); j++) {
899 QDomElement e = params.item(i).toElement();
900 if (e.attribute("type") == "keyframe") {
901 // parse keyframes and adjust values
902 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
903 QMap <int, double> kfr;
904 foreach(const QString str, keyframes) {
905 int pos = str.section(":", 0, 0).toInt();
906 double val = str.section(":", 1, 1).toDouble();
907 if (pos == previous) kfr[current] = val;
909 if (fromStart && pos >= current) kfr[pos] = val;
910 else if (!fromStart && pos <= current) kfr[pos] = val;
914 QMap<int, double>::const_iterator k = kfr.constBegin();
915 while (k != kfr.constEnd()) {
916 newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
919 e.setAttribute("keyframes", newkfr);
924 if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
929 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
930 if (change == ItemPositionChange && scene()) {
931 // calculate new position.
932 if (group() != 0) return pos();
933 QPointF newPos = value.toPointF();
934 //kDebug() << "/// MOVING CLIP ITEM.------------";
935 int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
936 xpos = qMax(xpos, 0);
938 int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
939 newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
940 newTrack = qMax(newTrack, 0);
941 newPos.setY((int)(newTrack * KdenliveSettings::trackheight() + 1));
942 // Only one clip is moving
943 QRectF sceneShape = rect();
944 sceneShape.translate(newPos);
945 QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
946 items.removeAll(this);
948 if (!items.isEmpty()) {
949 for (int i = 0; i < items.count(); i++) {
950 if (items.at(i)->type() == type()) {
952 QPointF otherPos = items.at(i)->pos();
953 if ((int) otherPos.y() != (int) pos().y()) return pos();
954 if (pos().x() < otherPos.x()) {
955 // move clip just before colliding clip
956 int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
957 // check we don't run into another clip
960 sceneShape.translate(newPos);
961 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
962 items.removeAll(this);
963 for (int j = 0; j < subitems.count(); j++) {
964 if (subitems.at(j)->type() == type()) return pos();
967 // get pos just after colliding clip
968 int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
969 // check we don't run into another clip
972 sceneShape.translate(newPos);
973 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
974 items.removeAll(this);
975 for (int j = 0; j < subitems.count(); j++) {
976 if (subitems.at(j)->type() == type()) return pos();
980 m_startPos = GenTime((int) newPos.x(), m_fps);
986 m_startPos = GenTime((int) newPos.x(), m_fps);
987 //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
990 return QGraphicsItem::itemChange(change, value);
994 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
997 int ClipItem::effectsCounter() {
998 return m_effectsCounter++;
1001 int ClipItem::effectsCount() {
1002 return m_effectList.size();
1005 QStringList ClipItem::effectNames() {
1006 return m_effectList.effectNames();
1009 QDomElement ClipItem::effectAt(int ix) {
1010 if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1011 return m_effectList.at(ix);
1014 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1015 kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1016 m_effectList.insert(ix, effect);
1017 m_effectList.removeAt(ix + 1);
1018 m_effectNames = m_effectList.effectNames().join(" / ");
1019 if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1021 QRectF r = boundingRect();
1027 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1028 QHash <QString, QString> effectParams;
1029 bool needRepaint = false;
1031 doc.appendChild(doc.importNode(effect, true));
1032 kDebug() << "/////// CLIP ADD EFFECT: "<< doc.toString();*/
1033 m_effectList.append(effect);
1034 effectParams["tag"] = effect.attribute("tag");
1035 QString effectId = effect.attribute("id");
1036 if (effectId.isEmpty()) effectId = effect.attribute("tag");
1037 effectParams["id"] = effectId;
1038 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1039 QString state = effect.attribute("disabled");
1040 if (!state.isEmpty()) effectParams["disabled"] = state;
1041 QDomNodeList params = effect.elementsByTagName("parameter");
1043 for (int i = 0; i < params.count(); i++) {
1044 QDomElement e = params.item(i).toElement();
1046 if (e.attribute("type") == "keyframe") {
1047 effectParams["keyframes"] = e.attribute("keyframes");
1048 effectParams["min"] = e.attribute("min");
1049 effectParams["max"] = e.attribute("max");
1050 effectParams["factor"] = e.attribute("factor", "1");
1051 effectParams["starttag"] = e.attribute("starttag", "start");
1052 effectParams["endtag"] = e.attribute("endtag", "end");
1055 double f = e.attribute("factor", "1").toDouble();
1058 effectParams[e.attribute("name")] = e.attribute("value");
1059 // check if it is a fade effect
1060 if (effectId == "fadein") {
1062 if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1063 else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1064 } else if (effectId == "fadeout") {
1066 if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1067 else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1070 effectParams[e.attribute("name")] = QString::number(effectParams[e.attribute("name")].toDouble() / f);
1074 m_effectNames = m_effectList.effectNames().join(" / ");
1075 if (fade > 0) m_startFade = fade;
1076 else if (fade < 0) m_endFade = -fade;
1077 if (needRepaint) update(boundingRect());
1080 } else if (!needRepaint) {
1081 QRectF r = boundingRect();
1085 if (m_selectedEffect == -1) {
1086 m_selectedEffect = 0;
1087 setSelectedEffect(m_selectedEffect);
1089 return effectParams;
1092 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1093 QHash <QString, QString> effectParams;
1094 effectParams["tag"] = effect.attribute("tag");
1095 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1096 effectParams["id"] = effect.attribute("id");
1097 QString state = effect.attribute("disabled");
1098 if (!state.isEmpty()) effectParams["disabled"] = state;
1099 QDomNodeList params = effect.elementsByTagName("parameter");
1100 for (int i = 0; i < params.count(); i++) {
1101 QDomElement e = params.item(i).toElement();
1102 //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1103 if (e.attribute("type") == "keyframe") {
1104 kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1105 effectParams["keyframes"] = e.attribute("keyframes");
1106 effectParams["max"] = e.attribute("max");
1107 effectParams["min"] = e.attribute("min");
1108 effectParams["factor"] = e.attribute("factor", "1");
1109 effectParams["starttag"] = e.attribute("starttag", "start");
1110 effectParams["endtag"] = e.attribute("endtag", "end");
1111 } else if (e.attribute("namedesc").contains(";")) {
1112 QString format = e.attribute("format");
1113 QStringList separators = format.split("%d", QString::SkipEmptyParts);
1114 QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1116 QTextStream txtNeu(&neu);
1117 if (values.size() > 0)
1118 txtNeu << (int)values[0].toDouble();
1119 for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1120 txtNeu << separators[i];
1121 txtNeu << (int)(values[i+1].toDouble());
1123 effectParams["start"] = neu;
1125 if (e.attribute("factor", "1") != "1")
1126 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1127 else effectParams[e.attribute("name")] = e.attribute("value");
1130 return effectParams;
1133 void ClipItem::deleteEffect(QString index) {
1134 bool needRepaint = false;
1135 for (int i = 0; i < m_effectList.size(); ++i) {
1136 if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
1137 if (m_effectList.at(i).attribute("id") == "fadein") {
1140 } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1144 m_effectList.removeAt(i);
1148 m_effectNames = m_effectList.effectNames().join(" / ");
1149 if (needRepaint) update(boundingRect());
1153 double ClipItem::speed() const {
1157 void ClipItem::setSpeed(const double speed) {
1159 if (m_speed == 1.0) m_clipName = baseClip()->name();
1160 else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1164 GenTime ClipItem::maxDuration() const {
1165 return m_maxDuration / m_speed;
1169 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1170 QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1172 doc.setContent(effects, true);
1173 QDomElement e = doc.documentElement();
1174 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1175 if (view) view->slotAddEffect(e, m_startPos, track());
1179 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1180 event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1183 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1186 void ClipItem::addTransition(Transition* t) {
1187 m_transitionsList.append(t);
1188 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1190 QDomElement e = doc.documentElement();
1191 //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1195 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1197 int pos = event->x();
1198 if (event->modifiers() == Qt::ControlModifier)
1199 setDragMode(QGraphicsView::ScrollHandDrag);
1200 else if (event->modifiers() == Qt::ShiftModifier)
1201 setDragMode(QGraphicsView::RubberBandDrag);
1203 QGraphicsItem * item = itemAt(event->pos());
1206 else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1209 QGraphicsView::mousePressEvent(event);
1212 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1214 QGraphicsView::mouseReleaseEvent(event);
1215 setDragMode(QGraphicsView::NoDrag);
1219 #include "clipitem.moc"