1 /***************************************************************************
2 * Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com) *
3 * This file is part of kdenlive. See www.kdenlive.org. *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 ***************************************************************************/
15 The basis matrix for converting RGB to YUV is:
19 0.29900 0.58700 0.11400 1.00000
20 -0.14741 -0.28939 0.43680 x 0.00000
21 0.61478 -0.51480 -0.09998 0.00000
23 The resulting YUV value is then drawn on the circle
24 using U and V as coordinate values.
26 The maximum length of such an UV vector is reached
27 for the colors Red and Cyan: 0.632.
28 To make optimal use of space in the circle, this value
29 can be used for scaling.
31 As we are dealing with RGB values in a range of {0,...,255}
32 and the conversion values are made for [0,1], we already
33 divide the conversion values by 255 previously, e.g. in
37 http://de.wikipedia.org/wiki/Vektorskop
38 http://www.elektroniktutor.de/techno/vektskop.html
43 #include <QMouseEvent>
48 #include <qtconcurrentrun.h>
52 #include "vectorscope.h"
54 const float SCALING = 1/.7; // See class docs
55 const float P75 = .75;
56 const unsigned char DEFAULT_Y = 255;
57 const unsigned int REALTIME_FPS = 15; // in fps.
59 const QPointF YUV_R(-.147, .615);
60 const QPointF YUV_G(-.289, -.515);
61 const QPointF YUV_B(.437, -.100);
62 const QPointF YUV_Cy(.147, -.615);
63 const QPointF YUV_Mg(.289, .515);
64 const QPointF YUV_Yl(-.437, .100);
66 const QPen penThick(QBrush(QColor(250,250,250)), 2, Qt::SolidLine);
67 const QPen penThin(QBrush(QColor(250,250,250)), 1, Qt::SolidLine);
68 const QPen penLight(QBrush(QColor(200,200,250,150)), 1, Qt::SolidLine);
69 const QPen penDark(QBrush(QColor(0,0,20,250)), 1, Qt::SolidLine);
72 Vectorscope::Vectorscope(Monitor *projMonitor, Monitor *clipMonitor, QWidget *parent) :
74 m_projMonitor(projMonitor),
75 m_clipMonitor(clipMonitor),
76 m_activeRender(clipMonitor->render),
80 initialDimensionUpdateDone(false),
85 m_colorTools = new ColorTools();
86 m_colorPlaneExport = new ColorPlaneExport(this);
88 paintMode->addItem(i18n("Green"), QVariant(PAINT_GREEN));
89 paintMode->addItem(i18n("Green 2"), QVariant(PAINT_GREEN2));
90 paintMode->addItem(i18n("Black"), QVariant(PAINT_BLACK));
91 paintMode->addItem(i18n("Modified YUV (Chroma)"), QVariant(PAINT_CHROMA));
92 paintMode->addItem(i18n("YUV"), QVariant(PAINT_YUV));
93 paintMode->addItem(i18n("Original Color"), QVariant(PAINT_ORIG));
95 backgroundMode->addItem(i18n("None"), QVariant(BG_NONE));
96 backgroundMode->addItem(i18n("YUV"), QVariant(BG_YUV));
97 backgroundMode->addItem(i18n("Modified YUV (Chroma)"), QVariant(BG_CHROMA));
99 cbAutoRefresh->setChecked(true);
101 connect(backgroundMode, SIGNAL(currentIndexChanged(int)), this, SLOT(slotBackgroundChanged()));
102 connect(cbMagnify, SIGNAL(stateChanged(int)), this, SLOT(slotMagnifyChanged()));
103 connect(this, SIGNAL(signalScopeCalculationFinished(uint,uint)), this, SLOT(slotScopeCalculationFinished(uint,uint)));
104 connect(m_colorTools, SIGNAL(signalWheelCalculationFinished()), this, SLOT(slotWheelCalculationFinished()));
105 connect(paintMode, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateScope()));
106 connect(cbAutoRefresh, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateScope()));
108 newFrames.fetchAndStoreRelaxed(0);
109 newChanges.fetchAndStoreRelaxed(0);
110 newWheelChanges.fetchAndStoreRelaxed(0);
113 ///// Build context menu /////
114 setContextMenuPolicy(Qt::ActionsContextMenu);
116 m_aExportBackground = new QAction(i18n("Export background"), this);
117 addAction(m_aExportBackground);
118 connect(m_aExportBackground, SIGNAL(triggered()), this, SLOT(slotExportBackground()));
120 m_a75PBox = new QAction(i18n("75% box"), this);
121 m_a75PBox->setCheckable(true);
122 m_a75PBox->setChecked(false);
123 addAction(m_a75PBox);
124 connect(m_a75PBox, SIGNAL(changed()), this, SLOT(update()));
126 m_aAxisEnabled = new QAction(i18n("Draw axis"), this);
127 m_aAxisEnabled->setCheckable(true);
128 m_aAxisEnabled->setChecked(false);
129 addAction(m_aAxisEnabled);
130 connect(m_aAxisEnabled, SIGNAL(changed()), this, SLOT(update()));
132 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
133 m_aRealtime->setCheckable(true);
134 m_aRealtime->setChecked(false);
135 addAction(m_aRealtime);
138 this->setMouseTracking(true);
143 Vectorscope::~Vectorscope()
145 delete m_colorPlaneExport;
150 Input point is on [-1,1]², 0 being at the center,
151 and positive directions are top/right.
153 Maps to a QRect «inside» which is using the
154 0 point in the top left corner. The coordinates of
155 the rect «inside» are relative to «parent». The
156 coordinates returned can be used in the parent.
160 +-------------------+
164 | | --0++ | | < point
168 +-------------------+
171 QPoint Vectorscope::mapToCanvas(QRect inside, QPointF point)
173 return QPoint(point.x()/2*inside.width() + inside.width()/2 + inside.x(),
174 -point.y()/2*inside.height() + inside.height()/2 + inside.y());
177 bool Vectorscope::prodCalcThread()
180 if (m_scopeCalcThread.isRunning()) {
181 qDebug() << "Calc thread still running.";
185 // Acquire the semaphore. Don't release it anymore until the QFuture m_scopeCalcThread
186 // tells us that the thread has finished.
187 ok = semaphore.tryAcquire(1);
189 qDebug() << "Calc thread not running anymore, finished: " << m_scopeCalcThread.isFinished() << ", Starting new thread";
191 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
192 // running member functions in a thread
193 m_scopeCalcThread = QtConcurrent::run(this, &Vectorscope::calculateScope);
195 newFrames.fetchAndStoreRelease(0); // Reset number of new frames, as we just got the newest
196 newChanges.fetchAndStoreRelease(0); // Do the same with the external changes counter
198 qDebug() << "Could not acquire semaphore. Deadlock avoided? Not starting new thread.";
204 bool Vectorscope::prodWheelThread()
206 if (m_wheelCalcThread.isRunning()) {
207 qDebug() << "Wheel thread still running.";
210 switch (backgroundMode->itemData(backgroundMode->currentIndex()).toInt()) {
212 qDebug() << "No background.";
217 qDebug() << "YUV background.";
218 m_wheelCalcThread = QtConcurrent::run(m_colorTools, &ColorTools::yuvColorWheel, m_scopeRect.size(), (unsigned char) 128, 1/SCALING, false, true);
221 m_wheelCalcThread = QtConcurrent::run(m_colorTools, &ColorTools::yuvColorWheel, m_scopeRect.size(), (unsigned char) 255, 1/SCALING, true, true);
224 newWheelChanges.fetchAndStoreRelaxed(0);
231 void Vectorscope::calculateScope()
233 qDebug() << "..Scope rendering starts now.";
234 QTime start = QTime::currentTime();
235 unsigned int skipPixels = 1;
236 if (m_aRealtime->isChecked()) {
237 skipPixels = m_skipPixels;
239 const int stepsize = 4*skipPixels;
241 // Prepare the vectorscope data
242 QImage scope(cw, cw, QImage::Format_ARGB32);
243 scope.fill(qRgba(0,0,0,0));
245 QImage img(m_activeRender->extractFrame(m_activeRender->seekFramePosition()));
246 const uchar *bits = img.bits();
249 double dy, dr, dg, db, dmax;
254 // Just an average for the number of image pixels per scope pixel.
255 double avgPxPerPx = (double) 4*img.byteCount()/scope.size().width()/scope.size().height()/skipPixels;
256 qDebug() << "Expecting " << avgPxPerPx << " pixels per pixel.";
258 const QRect scopeRect(QPoint(0,0), scope.size());
260 for (int i = 0; i < img.byteCount(); i+= stepsize) {
261 QRgb *col = (QRgb *) bits;
267 y = (double) 0.001173 * r +0.002302 * g +0.0004471* b;
268 u = (double) -0.0005781* r -0.001135 * g +0.001713 * b;
269 v = (double) 0.002411 * r -0.002019 * g -0.0003921* b;
271 pt = mapToCanvas(scopeRect, QPointF(SCALING*m_scaling*u, SCALING*m_scaling*v));
273 if (!(pt.x() <= scopeRect.width() && pt.x() >= 0
274 && pt.y() <= scopeRect.height() && pt.y() >= 0)) {
275 // Point lies outside (because of scaling), don't plot it
279 // Draw the pixel using the chosen draw mode.
280 switch (paintMode->itemData(paintMode->currentIndex()).toInt()) {
283 dy = 128; // Default Y value. Lower = darker.
285 // Calculate the RGB values from YUV
287 dg = dy - 100.6*u - 148*v;
293 if (dr > 255) dr = 255;
294 if (dg > 255) dg = 255;
295 if (db > 255) db = 255;
297 scope.setPixel(pt, qRgba(dr, dg, db, 255));
301 dy = 200; // Default Y value. Lower = darker.
303 // Calculate the RGB values from YUV
305 dg = dy - 100.6*u - 148*v;
308 // Scale the RGB values back to max 255
310 if (dg > dmax) dmax = dg;
311 if (db > dmax) dmax = db;
318 scope.setPixel(pt, qRgba(dr, dg, db, 255));
321 scope.setPixel(pt, *col);
324 px = scope.pixel(pt);
325 scope.setPixel(pt, qRgba(qRed(px)+(255-qRed(px))/(3*avgPxPerPx), qGreen(px)+20*(255-qGreen(px))/(avgPxPerPx),
326 qBlue(px)+(255-qBlue(px))/(avgPxPerPx), qAlpha(px)+(255-qAlpha(px))/(avgPxPerPx)));
329 px = scope.pixel(pt);
330 scope.setPixel(pt, qRgba(qRed(px)+ceil((255-(float)qRed(px))/(4*avgPxPerPx)), 255,
331 qBlue(px)+ceil((255-(float)qBlue(px))/(avgPxPerPx)), qAlpha(px)+ceil((255-(float)qAlpha(px))/(avgPxPerPx))));
334 px = scope.pixel(pt);
335 scope.setPixel(pt, qRgba(0,0,0, qAlpha(px)+(255-qAlpha(px))/20));
345 unsigned int mseconds = start.msecsTo(QTime::currentTime());
346 qDebug() << "Scope rendered in " << mseconds << " ms. Sending finished signal.";
347 emit signalScopeCalculationFinished(mseconds, skipPixels);
348 qDebug() << "xxScope: Signal finished sent.";
351 void Vectorscope::updateDimensions()
353 // Widget width/height
354 int ww = this->size().width();
355 int wh = this->size().height();
357 // Distance from top/left/right
360 // controlsArea contains the controls at the top;
361 // We want to paint below
362 QPoint topleft(offset, controlsArea->geometry().height()+offset);
364 // Circle Width: min of width and height
365 cw = wh - topleft.y();
366 if (ww < cw) { cw = ww; }
368 m_scopeRect = QRect(topleft, QPoint(cw, cw) + topleft);
370 centerPoint = mapToCanvas(m_scopeRect, QPointF(0,0));
371 pR75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_R);
372 pG75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_G);
373 pB75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_B);
374 pCy75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_Cy);
375 pMg75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_Mg);
376 pYl75 = mapToCanvas(m_scopeRect, P75*SCALING*YUV_Yl);
379 void Vectorscope::paintEvent(QPaintEvent *)
382 if (!initialDimensionUpdateDone) {
383 // This is a workaround.
384 // When updating the dimensions in the constructor, the size
385 // of the control items at the top are simply ignored! So do
388 initialDimensionUpdateDone = true;
391 // Draw the vectorscope circle
392 QPainter davinci(this);
396 davinci.setRenderHint(QPainter::Antialiasing, true);
397 davinci.fillRect(0, 0, this->size().width(), this->size().height(), QColor(25,25,23));
399 davinci.drawImage(m_scopeRect.topLeft(), m_wheel);
401 davinci.setPen(penThick);
402 davinci.drawEllipse(m_scopeRect);
404 // Draw RGB/CMY points with 100% chroma
405 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_R);
406 davinci.drawEllipse(vinciPoint, 4,4);
407 davinci.drawText(vinciPoint-QPoint(20, -10), "R");
409 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_G);
410 davinci.drawEllipse(vinciPoint, 4,4);
411 davinci.drawText(vinciPoint-QPoint(20, 0), "G");
413 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_B);
414 davinci.drawEllipse(vinciPoint, 4,4);
415 davinci.drawText(vinciPoint+QPoint(15, 10), "B");
417 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_Cy);
418 davinci.drawEllipse(vinciPoint, 4,4);
419 davinci.drawText(vinciPoint+QPoint(15, -5), "Cy");
421 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_Mg);
422 davinci.drawEllipse(vinciPoint, 4,4);
423 davinci.drawText(vinciPoint+QPoint(15, 10), "Mg");
425 vinciPoint = mapToCanvas(m_scopeRect, SCALING*YUV_Yl);
426 davinci.drawEllipse(vinciPoint, 4,4);
427 davinci.drawText(vinciPoint-QPoint(25, 0), "Yl");
429 switch (backgroundMode->itemData(backgroundMode->currentIndex()).toInt()) {
431 davinci.setPen(penLight);
434 davinci.setPen(penDark);
439 if (m_aAxisEnabled->isChecked()) {
440 davinci.drawLine(mapToCanvas(m_scopeRect, QPointF(0,-.9)), mapToCanvas(m_scopeRect, QPointF(0,.9)));
441 davinci.drawLine(mapToCanvas(m_scopeRect, QPointF(-.9,0)), mapToCanvas(m_scopeRect, QPointF(.9,0)));
445 switch (backgroundMode->itemData(backgroundMode->currentIndex()).toInt()) {
447 davinci.setPen(penDark);
450 davinci.setPen(penThin);
453 davinci.drawEllipse(centerPoint, 5,5);
457 if (m_a75PBox->isChecked()) {
458 davinci.drawLine(pR75, pYl75);
459 davinci.drawLine(pYl75, pG75);
460 davinci.drawLine(pG75, pCy75);
461 davinci.drawLine(pCy75, pB75);
462 davinci.drawLine(pB75, pMg75);
463 davinci.drawLine(pMg75, pR75);
466 // Draw RGB/CMY points with 75% chroma (for NTSC)
467 davinci.setPen(penThin);
468 davinci.drawEllipse(pR75, 3,3);
469 davinci.drawEllipse(pG75, 3,3);
470 davinci.drawEllipse(pB75, 3,3);
471 davinci.drawEllipse(pCy75, 3,3);
472 davinci.drawEllipse(pMg75, 3,3);
473 davinci.drawEllipse(pYl75, 3,3);
477 // Draw the scope data (previously calculated in a separate thread)
478 davinci.drawImage(m_scopeRect.topLeft(), m_scope);
482 // Mouse moved: Draw a circle over the scope
484 int dx = -centerPoint.x()+mousePos.x();
485 int dy = centerPoint.y()-mousePos.y();
487 QPoint reference = mapToCanvas(m_scopeRect, QPointF(1,0));
489 float r = sqrt(dx*dx + dy*dy);
490 float percent = (float) 100*r/SCALING/m_scaling/(reference.x() - centerPoint.x());
492 switch (backgroundMode->itemData(backgroundMode->currentIndex()).toInt()) {
494 davinci.setPen(penLight);
497 davinci.setPen(penDark);
500 davinci.drawEllipse(centerPoint, (int)r, (int)r);
501 davinci.setPen(penThin);
502 davinci.drawText(m_scopeRect.bottomRight()-QPoint(40,0), i18n("%1 \%", QString::number(percent, 'f', 0)));
504 float angle = copysign(acos(dx/r)*180/M_PI, dy);
505 davinci.drawText(m_scopeRect.bottomLeft()+QPoint(10,0), i18n("%1°", QString::number(angle, 'f', 1)));
507 circleEnabled = false;
510 // Draw realtime factor (number of skipped pixels)
511 if (m_aRealtime->isChecked()) {
512 davinci.setPen(penThin);
513 davinci.drawText(m_scopeRect.bottomRight()-QPoint(40,15), QVariant(m_skipPixels).toString().append("x"));
523 void Vectorscope::slotMagnifyChanged()
525 if (cbMagnify->isChecked()) {
533 void Vectorscope::slotActiveMonitorChanged(bool isClipMonitor)
536 m_activeRender = m_clipMonitor->render;
537 disconnect(this, SLOT(slotRenderZoneUpdated()));
538 connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
540 m_activeRender = m_projMonitor->render;
541 disconnect(this, SLOT(slotRenderZoneUpdated()));
542 connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
546 void Vectorscope::slotRenderZoneUpdated()
548 qDebug() << "Monitor incoming. New frames total: " << newFrames;
549 // Monitor has shown a new frame
550 newFrames.fetchAndAddRelaxed(1);
551 if (cbAutoRefresh->isChecked()) {
556 void Vectorscope::slotScopeCalculationFinished(unsigned int mseconds, unsigned int skipPixels)
558 qDebug() << "Received finished signal.";
559 if (!m_scopeCalcThread.isFinished()) {
560 // Wait for the thread to finish. Otherwise the scope might not get updated
561 // as prodCalcThread may see it still running.
562 QTime start = QTime::currentTime();
563 qDebug() << "Scope renderer has not finished yet although finished signal received, waiting ...";
564 m_scopeCalcThread.waitForFinished();
565 qDebug() << "Waiting for finish is over. Waited for " << start.msecsTo(QTime::currentTime()) << " ms";
570 qDebug() << "Scope updated.";
572 if (m_aRealtime->isChecked()) {
573 m_skipPixels = ceil((float)REALTIME_FPS*mseconds*skipPixels/1000);
574 Q_ASSERT(m_skipPixels >= 1);
575 qDebug() << "Realtime checked. Switching from " << skipPixels << " to " << m_skipPixels;
578 qDebug() << "No realtime.";
581 // If auto-refresh is enabled and new frames are available,
582 // just start the next calculation.
583 if (newFrames > 0 && cbAutoRefresh->isChecked()) {
584 qDebug() << "Found more frames in the queue (prodding now): " << newFrames;
586 } else if (newChanges > 0) {
587 qDebug() << newChanges << " changes (e.g. resize) in the meantime.";
590 qDebug() << newFrames << " new frames, " << newChanges << " new changes. Not updating.";
594 void Vectorscope::slotWheelCalculationFinished()
596 if (!m_wheelCalcThread.isFinished()) {
597 QTime start = QTime::currentTime();
598 qDebug() << "Wheel calc has not finished yet, waiting ...";
599 m_wheelCalcThread.waitForFinished();
600 qDebug() << "Done. Waited for " << start.msecsTo(QTime::currentTime()) << " ms";
603 qDebug() << "Wheel calculated. Updating.";
604 qDebug() << m_wheelCalcThread.resultCount() << " results from the Wheel thread.";
605 if (m_wheelCalcThread.resultCount() > 0) {
606 m_wheel = m_wheelCalcThread.resultAt(0);
609 if (newWheelChanges > 0) {
614 void Vectorscope::slotUpdateScope()
619 void Vectorscope::slotUpdateWheel()
624 void Vectorscope::slotExportBackground()
626 qDebug() << "Exporting background";
627 m_colorPlaneExport->show();
631 void Vectorscope::slotBackgroundChanged()
633 // Background changed, switch to a suitable color mode now
635 switch (backgroundMode->itemData(backgroundMode->currentIndex()).toInt()) {
637 index = paintMode->findData(QVariant(PAINT_BLACK));
639 paintMode->setCurrentIndex(index);
644 if (paintMode->itemData(paintMode->currentIndex()).toInt() == PAINT_BLACK) {
645 index = paintMode->findData(QVariant(PAINT_GREEN));
646 paintMode->setCurrentIndex(index);
650 newWheelChanges.fetchAndAddAcquire(1);
658 void Vectorscope::mousePressEvent(QMouseEvent *)
660 // Update the scope on mouse press
664 void Vectorscope::mouseMoveEvent(QMouseEvent *event)
666 // Draw a circle around the center,
667 // showing percentage number of the radius length
669 circleEnabled = true;
670 mousePos = event->pos();
674 void Vectorscope::resizeEvent(QResizeEvent *event)
676 qDebug() << "Resized.";
678 newChanges.fetchAndAddAcquire(1);
681 QWidget::resizeEvent(event);