]> git.sesse.net Git - kdenlive/blob - src/abstractscopewidget.cpp
Audio Scopes:
[kdenlive] / src / abstractscopewidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
3  *   This file is part of kdenlive. See www.kdenlive.org.                  *
4  *                                                                         *
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  ***************************************************************************/
10
11 #include "qtconcurrentrun.h"
12
13 #include "abstractscopewidget.h"
14 #include "renderer.h"
15 #include "monitor.h"
16
17 #include <QFuture>
18 #include <QColor>
19 #include <QMenu>
20 #include <QMouseEvent>
21 #include <QPainter>
22
23 // Uncomment for Scope debugging.
24 //#define DEBUG_ASW
25
26 #ifdef DEBUG_ASW
27 #include <QDebug>
28 #endif
29
30 const int REALTIME_FPS = 30;
31
32 const QColor light(250, 238, 226, 255);
33 const QColor dark(40,  40,  39, 255);
34 const QColor dark2(25,  25,  23, 255);
35
36 const QPen AbstractScopeWidget::penThick(QBrush(QColor(250, 250, 250)),          2, Qt::SolidLine);
37 const QPen AbstractScopeWidget::penThin(QBrush(QColor(250, 250, 250)),           1, Qt::SolidLine);
38 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)),     1, Qt::SolidLine);
39 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
40 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)),   1, Qt::SolidLine);
41 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)),           1, Qt::SolidLine);
42 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)),       1, Qt::DotLine);
43 const QPen AbstractScopeWidget::penBackground(QBrush(dark2),                     1, Qt::SolidLine);
44
45 const QString AbstractScopeWidget::directions[] =  {"North", "Northeast", "East", "Southeast"};
46
47 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
48         QWidget(parent),
49         m_mousePos(0, 0),
50         m_mouseWithinWidget(false),
51         offset(5),
52         m_accelFactorHUD(1),
53         m_accelFactorScope(1),
54         m_accelFactorBackground(1),
55         m_semaphoreHUD(1),
56         m_semaphoreScope(1),
57         m_semaphoreBackground(1),
58         initialDimensionUpdateDone(false),
59         m_requestForcedUpdate(false),
60         m_rescaleMinDist(4),
61         m_rescaleVerticalThreshold(2.0f)
62
63 {
64     m_scopePalette = QPalette();
65     m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
66     m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
67     m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
68     m_scopePalette.setBrush(QPalette::Text, QBrush(light));
69     m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
70     m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
71     this->setPalette(m_scopePalette);
72     this->setAutoFillBackground(true);
73
74     m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
75     m_aAutoRefresh->setCheckable(true);
76     m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
77     m_aRealtime->setCheckable(true);
78
79     m_menu = new QMenu(this);
80     m_menu->setPalette(m_scopePalette);
81     m_menu->addAction(m_aAutoRefresh);
82     m_menu->addAction(m_aRealtime);
83
84     this->setContextMenuPolicy(Qt::CustomContextMenu);
85
86     bool b = true;
87     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
88
89     b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
90     b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
91     b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
92     b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
93     b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
94     Q_ASSERT(b);
95
96     // Enable mouse tracking if desired.
97     // Causes the mouseMoved signal to be emitted when the mouse moves inside the
98     // widget, even when no mouse button is pressed.
99     this->setMouseTracking(trackMouse);
100 }
101
102 AbstractScopeWidget::~AbstractScopeWidget()
103 {
104     writeConfig();
105
106     delete m_menu;
107     delete m_aAutoRefresh;
108     delete m_aRealtime;
109 }
110
111 void AbstractScopeWidget::init()
112 {
113     m_widgetName = widgetName();
114     readConfig();
115 }
116
117 void AbstractScopeWidget::readConfig()
118 {
119     KSharedConfigPtr config = KGlobal::config();
120     KConfigGroup scopeConfig(config, configName());
121     m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
122     m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
123     scopeConfig.sync();
124 }
125
126 void AbstractScopeWidget::writeConfig()
127 {
128     KSharedConfigPtr config = KGlobal::config();
129     KConfigGroup scopeConfig(config, configName());
130     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
131     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
132     scopeConfig.sync();
133 }
134
135 QString AbstractScopeWidget::configName()
136 {
137     return "Scope_" + m_widgetName;
138 }
139
140 void AbstractScopeWidget::prodHUDThread()
141 {
142     if (this->visibleRegion().isEmpty()) {
143 #ifdef DEBUG_ASW
144         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
145 #endif
146     } else {
147         if (m_semaphoreHUD.tryAcquire(1)) {
148             Q_ASSERT(!m_threadHUD.isRunning());
149
150             m_newHUDFrames.fetchAndStoreRelaxed(0);
151             m_newHUDUpdates.fetchAndStoreRelaxed(0);
152             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
153 #ifdef DEBUG_ASW
154             qDebug() << "HUD thread started in " << m_widgetName;
155 #endif
156
157         }
158 #ifdef DEBUG_ASW
159         else {
160             qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
161         }
162 #endif
163     }
164 }
165
166 void AbstractScopeWidget::prodScopeThread()
167 {
168     // Only start a new thread if the scope is actually visible
169     // and not hidden by another widget on the stack and if user want the scope to update.
170     if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
171 #ifdef DEBUG_ASW
172         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
173 #endif
174     } else {
175         // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
176         // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
177         // If acquiring the semaphore fails, the thread is still running.
178         if (m_semaphoreScope.tryAcquire(1)) {
179             Q_ASSERT(!m_threadScope.isRunning());
180
181             m_newScopeFrames.fetchAndStoreRelaxed(0);
182             m_newScopeUpdates.fetchAndStoreRelaxed(0);
183
184             Q_ASSERT(m_accelFactorScope > 0);
185
186             // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
187             // running member functions in a thread
188             m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
189             m_requestForcedUpdate = false;
190
191 #ifdef DEBUG_ASW
192             qDebug() << "Scope thread started in " << m_widgetName;
193 #endif
194
195         } else {
196 #ifdef DEBUG_ASW
197             qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
198 #endif
199         }
200     }
201 }
202 void AbstractScopeWidget::prodBackgroundThread()
203 {
204     if (this->visibleRegion().isEmpty()) {
205 #ifdef DEBUG_ASW
206         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
207 #endif
208     } else {
209         if (m_semaphoreBackground.tryAcquire(1)) {
210             Q_ASSERT(!m_threadBackground.isRunning());
211
212             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
213             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
214             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
215
216 #ifdef DEBUG_ASW
217             qDebug() << "Background thread started in " << m_widgetName;
218 #endif
219
220         } else {
221 #ifdef DEBUG_ASW
222             qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
223 #endif
224         }
225     }
226 }
227
228 void AbstractScopeWidget::forceUpdate(bool doUpdate)
229 {
230 #ifdef DEBUG_ASW
231     qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
232 #endif
233
234     if (!doUpdate) {
235         return;
236     }
237     m_requestForcedUpdate = true;
238     m_newHUDUpdates.fetchAndAddRelaxed(1);
239     m_newScopeUpdates.fetchAndAddRelaxed(1);
240     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
241     prodHUDThread();
242     prodScopeThread();
243     prodBackgroundThread();
244 }
245 void AbstractScopeWidget::forceUpdateHUD()
246 {
247     m_newHUDUpdates.fetchAndAddRelaxed(1);
248     prodHUDThread();
249
250 }
251 void AbstractScopeWidget::forceUpdateScope()
252 {
253     m_newScopeUpdates.fetchAndAddRelaxed(1);
254     m_requestForcedUpdate = true;
255     prodScopeThread();
256
257 }
258 void AbstractScopeWidget::forceUpdateBackground()
259 {
260     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
261     prodBackgroundThread();
262
263 }
264
265
266 ///// Events /////
267
268
269 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
270 {
271     // Update the dimension of the available rect for painting
272     m_scopeRect = scopeRect();
273     forceUpdate();
274
275     QWidget::resizeEvent(event);
276 }
277
278 void AbstractScopeWidget::showEvent(QShowEvent *event)
279 {
280     QWidget::showEvent(event);
281     m_scopeRect = scopeRect();
282 }
283
284 void AbstractScopeWidget::paintEvent(QPaintEvent *)
285 {
286     QPainter davinci(this);
287     davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
288     davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
289     davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
290 }
291
292 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
293 {
294     if (event->button() == Qt::LeftButton) {
295         // Rescaling mode starts
296         m_rescaleActive = true;
297         m_rescalePropertiesLocked = false;
298         m_rescaleFirstRescaleDone = false;
299         m_rescaleStartPoint = event->pos();
300         m_rescaleModifiers = event->modifiers();
301     }
302 }
303 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
304 {
305     m_rescaleActive = false;
306     m_rescalePropertiesLocked = false;
307
308     if (!m_aAutoRefresh->isChecked()) {
309         m_requestForcedUpdate = true;
310     }
311     prodHUDThread();
312     prodScopeThread();
313     prodBackgroundThread();
314     QWidget::mouseReleaseEvent(event);
315 }
316 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
317 {
318     m_mousePos = event->pos();
319     m_mouseWithinWidget = true;
320     emit signalMousePositionChanged();
321
322     QPoint movement = event->pos()-m_rescaleStartPoint;
323
324     if (m_rescaleActive) {
325         if (m_rescalePropertiesLocked) {
326             // Direction is known, now adjust parameters
327
328             // Reset the starting point to make the next moveEvent relative to the current one
329             m_rescaleStartPoint = event->pos();
330
331
332             if (!m_rescaleFirstRescaleDone) {
333                 // We have just learned the desired direction; Normalize the movement to one pixel
334                 // to avoid a jump by m_rescaleMinDist
335
336                 if (movement.x() != 0) {
337                     movement.setX(movement.x() / abs(movement.x()));
338                 }
339                 if (movement.y() != 0) {
340                     movement.setY(movement.y() / abs(movement.y()));
341                 }
342
343                 m_rescaleFirstRescaleDone = true;
344             }
345
346             handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
347
348
349
350         } else {
351             // Detect the movement direction here.
352             // This algorithm relies on the aspect ratio of dy/dx (size and signum).
353             if (movement.manhattanLength() > m_rescaleMinDist) {
354                 float diff = ((float) movement.y())/movement.x();
355
356                 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
357                     m_rescaleDirection = North;
358                 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
359                     m_rescaleDirection = East;
360                 } else if (diff < 0) {
361                     m_rescaleDirection = Northeast;
362                 } else {
363                     m_rescaleDirection = Southeast;
364                 }
365 #ifdef DEBUG_ASW
366                 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
367 #endif
368                 m_rescalePropertiesLocked = true;
369             }
370         }
371     }
372 }
373
374 void AbstractScopeWidget::leaveEvent(QEvent *)
375 {
376     m_mouseWithinWidget = false;
377     emit signalMousePositionChanged();
378 }
379
380 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
381 {
382     m_menu->exec(this->mapToGlobal(pos));
383 }
384
385 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
386 {
387     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
388 }
389 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
390 {
391     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
392 }
393 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
394 {
395     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
396 }
397
398
399 ///// Slots /////
400
401 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
402 {
403 #ifdef DEBUG_ASW
404     qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
405 #endif
406     m_threadHUD.waitForFinished();
407     m_imgHUD = m_threadHUD.result();
408
409     m_semaphoreHUD.release(1);
410     this->update();
411
412     int accel;
413     if (m_aRealtime->isChecked()) {
414         accel = calculateAccelFactorHUD(mseconds, oldFactor);
415         if (m_accelFactorHUD < 1) {
416             accel = 1;
417         }
418         m_accelFactorHUD = accel;
419     }
420
421     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
422 #ifdef DEBUG_ASW
423         qDebug() << "Trying to start a new HUD thread for " << m_widgetName
424                 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
425 #endif
426         prodHUDThread();;
427     }
428 }
429
430 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
431 {
432     // The signal can be received before the thread has really finished. So we
433     // need to wait until it has really finished before starting a new thread.
434 #ifdef DEBUG_ASW
435     qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
436 #endif
437     m_threadScope.waitForFinished();
438     m_imgScope = m_threadScope.result();
439
440     // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
441     // See prodScopeThread where the semaphore is acquired again.
442     m_semaphoreScope.release(1);
443     this->update();
444
445     // Calculate the acceleration factor hint to get «realtime» updates.
446     int accel;
447     if (m_aRealtime->isChecked()) {
448         accel = calculateAccelFactorScope(mseconds, oldFactor);
449         if (accel < 1) {
450             // If mseconds happens to be 0.
451             accel = 1;
452         }
453         // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
454         // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
455         // then :) Therefore use a local variable.
456         m_accelFactorScope = accel;
457     }
458
459     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
460 #ifdef DEBUG_ASW
461         qDebug() << "Trying to start a new scope thread for " << m_widgetName
462                 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
463 #endif
464         prodScopeThread();
465     }
466 }
467
468 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
469 {
470 #ifdef DEBUG_ASW
471     qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
472 #endif
473     m_threadBackground.waitForFinished();
474     m_imgBackground = m_threadBackground.result();
475
476     m_semaphoreBackground.release(1);
477     this->update();
478
479     int accel;
480     if (m_aRealtime->isChecked()) {
481         accel = calculateAccelFactorBackground(mseconds, oldFactor);
482         if (m_accelFactorBackground < 1) {
483             accel = 1;
484         }
485         m_accelFactorBackground = accel;
486     }
487
488     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
489 #ifdef DEBUG_ASW
490         qDebug() << "Trying to start a new background thread for " << m_widgetName
491                 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
492 #endif
493         prodBackgroundThread();;
494     }
495 }
496
497 void AbstractScopeWidget::slotRenderZoneUpdated()
498 {
499     m_newHUDFrames.fetchAndAddRelaxed(1);
500     m_newScopeFrames.fetchAndAddRelaxed(1);
501     m_newBackgroundFrames.fetchAndAddRelaxed(1);
502
503 #ifdef DEBUG_ASW
504     qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
505             << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
506 #endif
507
508     if (this->visibleRegion().isEmpty()) {
509 #ifdef DEBUG_ASW
510         qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
511 #endif
512     } else {
513         if (m_aAutoRefresh->isChecked()) {
514             prodHUDThread();
515             prodScopeThread();
516             prodBackgroundThread();
517         }
518     }
519 }
520
521 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
522 {
523     if (!realtimeChecked) {
524         m_accelFactorHUD = 1;
525         m_accelFactorScope = 1;
526         m_accelFactorBackground = 1;
527     }
528 }
529
530 bool AbstractScopeWidget::autoRefreshEnabled()
531 {
532     return m_aAutoRefresh->isChecked();
533 }
534
535 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
536 {
537 #ifdef DEBUG_ASW
538     qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
539             << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
540 #endif
541     if (isVisible()) {
542         // Notify listeners whether we accept new frames now
543         emit requestAutoRefresh(autoRefresh);
544     }
545     // TODO only if depends on input
546     if (autoRefresh) {
547         //forceUpdate();
548         m_requestForcedUpdate = true;
549     }
550 }
551
552 void AbstractScopeWidget::handleMouseDrag(const QPoint, const RescaleDirection, const Qt::KeyboardModifiers) { }
553
554
555 #ifdef DEBUG_ASW
556 #undef DEBUG_ASW
557 #endif