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