]> git.sesse.net Git - kdenlive/blob - src/abstractscopewidget.cpp
Speedup: only convert displayed frame to QImage if necessary (for on monitor scene...
[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 const int REALTIME_FPS = 30;
24
25 const QColor light(250, 238, 226, 255);
26 const QColor dark(40,  40,  39, 255);
27 const QColor dark2(25,  25,  23, 255);
28
29 const QPen AbstractScopeWidget::penThick(QBrush(QColor(250, 250, 250)),     2, Qt::SolidLine);
30 const QPen AbstractScopeWidget::penThin(QBrush(QColor(250, 250, 250)),     1, Qt::SolidLine);
31 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
32 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)),      1, Qt::SolidLine);
33
34 AbstractScopeWidget::AbstractScopeWidget(Monitor *projMonitor, Monitor *clipMonitor, bool trackMouse, QWidget *parent) :
35         QWidget(parent),
36         m_projMonitor(projMonitor),
37         m_clipMonitor(clipMonitor),
38         m_mousePos(0, 0),
39         m_mouseWithinWidget(false),
40         offset(5),
41         m_accelFactorHUD(1),
42         m_accelFactorScope(1),
43         m_accelFactorBackground(1),
44         m_semaphoreHUD(1),
45         m_semaphoreScope(1),
46         m_semaphoreBackground(1),
47         initialDimensionUpdateDone(false)
48
49 {
50     m_scopePalette = QPalette();
51     m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
52     m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
53     m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
54     m_scopePalette.setBrush(QPalette::Text, QBrush(light));
55     m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
56     m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
57     this->setPalette(m_scopePalette);
58     this->setAutoFillBackground(true);
59
60     m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
61     m_aAutoRefresh->setCheckable(true);
62     m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
63     m_aRealtime->setCheckable(true);
64
65     m_menu = new QMenu(this);
66     m_menu->setPalette(m_scopePalette);
67     m_menu->addAction(m_aAutoRefresh);
68     m_menu->addAction(m_aRealtime);
69
70     this->setContextMenuPolicy(Qt::CustomContextMenu);
71
72     m_activeRender = (m_clipMonitor->isActive()) ? m_clipMonitor->render : m_projMonitor->render;
73
74     bool b = true;
75     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
76
77     //b &= connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
78     b &= connect(m_activeRender, SIGNAL(frameUpdated(QImage)), this, SLOT(slotRenderZoneUpdated(QImage)));
79
80     b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
81     b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
82     b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
83     b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
84     b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
85     Q_ASSERT(b);
86
87     // Enable mouse tracking if desired.
88     // Causes the mouseMoved signal to be emitted when the mouse moves inside the
89     // widget, even when no mouse button is pressed.
90     this->setMouseTracking(trackMouse);
91 }
92
93 AbstractScopeWidget::~AbstractScopeWidget()
94 {
95     writeConfig();
96
97     delete m_menu;
98     delete m_aAutoRefresh;
99     delete m_aRealtime;
100 }
101
102 void AbstractScopeWidget::init()
103 {
104     m_widgetName = widgetName();
105     readConfig();
106 }
107
108 void AbstractScopeWidget::readConfig()
109 {
110     KSharedConfigPtr config = KGlobal::config();
111     KConfigGroup scopeConfig(config, configName());
112     m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
113     m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
114     scopeConfig.sync();
115 }
116
117 void AbstractScopeWidget::writeConfig()
118 {
119     KSharedConfigPtr config = KGlobal::config();
120     KConfigGroup scopeConfig(config, configName());
121     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
122     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
123     scopeConfig.sync();
124 }
125
126 QString AbstractScopeWidget::configName()
127 {
128     return "Scope_" + m_widgetName;
129 }
130
131 void AbstractScopeWidget::prodHUDThread()
132 {
133     if (this->visibleRegion().isEmpty()) {
134 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
135     } else {
136         if (m_semaphoreHUD.tryAcquire(1)) {
137             Q_ASSERT(!m_threadHUD.isRunning());
138
139             m_newHUDFrames.fetchAndStoreRelaxed(0);
140             m_newHUDUpdates.fetchAndStoreRelaxed(0);
141             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
142 //            qDebug() << "HUD thread started in " << m_widgetName;
143
144         } else {
145 //            qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
146         }
147     }
148 }
149
150 void AbstractScopeWidget::prodScopeThread()
151 {
152     // Only start a new thread if the scope is actually visible
153     // and not hidden by another widget on the stack.
154     if (this->visibleRegion().isEmpty()) {
155 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
156     } else {
157         // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
158         // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
159         // If acquiring the semaphore fails, the thread is still running.
160         if (m_semaphoreScope.tryAcquire(1)) {
161             Q_ASSERT(!m_threadScope.isRunning());
162
163             m_newScopeFrames.fetchAndStoreRelaxed(0);
164             m_newScopeUpdates.fetchAndStoreRelaxed(0);
165
166             Q_ASSERT(m_accelFactorScope > 0);
167
168             // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
169             // running member functions in a thread
170             m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope, m_scopeImage);
171
172 //            qDebug() << "Scope thread started in " << m_widgetName;
173
174         } else {
175 //            qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
176         }
177     }
178 }
179 void AbstractScopeWidget::prodBackgroundThread()
180 {
181     if (this->visibleRegion().isEmpty()) {
182 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
183     } else {
184         if (m_semaphoreBackground.tryAcquire(1)) {
185             Q_ASSERT(!m_threadBackground.isRunning());
186
187             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
188             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
189             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
190 //            qDebug() << "Background thread started in " << m_widgetName;
191
192         } else {
193 //            qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
194         }
195     }
196 }
197
198 void AbstractScopeWidget::forceUpdate(bool doUpdate)
199 {
200 //    qDebug() << "Force update called in " << widgetName() << ". Arg: " << doUpdate;
201     if (!doUpdate) {
202         return;
203     }
204     m_newHUDUpdates.fetchAndAddRelaxed(1);
205     m_newScopeUpdates.fetchAndAddRelaxed(1);
206     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
207     prodHUDThread();
208     prodScopeThread();
209     prodBackgroundThread();
210 }
211 void AbstractScopeWidget::forceUpdateHUD()
212 {
213     m_newHUDUpdates.fetchAndAddRelaxed(1);
214     prodHUDThread();
215
216 }
217 void AbstractScopeWidget::forceUpdateScope()
218 {
219     m_newScopeUpdates.fetchAndAddRelaxed(1);
220     prodScopeThread();
221
222 }
223 void AbstractScopeWidget::forceUpdateBackground()
224 {
225     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
226     prodBackgroundThread();
227
228 }
229
230
231 ///// Events /////
232
233 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
234 {
235     if (!m_aAutoRefresh->isChecked()) m_activeRender->sendFrameUpdate();
236     prodHUDThread();
237     prodScopeThread();
238     prodBackgroundThread();
239     QWidget::mouseReleaseEvent(event);
240 }
241
242 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
243 {
244     // Update the dimension of the available rect for painting
245     m_scopeRect = scopeRect();
246
247     forceUpdate();
248
249     QWidget::resizeEvent(event);
250 }
251
252 void AbstractScopeWidget::showEvent(QShowEvent *event)
253 {
254     QWidget::showEvent(event);
255     m_scopeRect = scopeRect();
256 }
257
258 void AbstractScopeWidget::paintEvent(QPaintEvent *)
259 {
260     QPainter davinci(this);
261     davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
262     davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
263     davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
264 }
265
266 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
267 {
268     m_mousePos = event->pos();
269     m_mouseWithinWidget = true;
270     emit signalMousePositionChanged();
271 }
272 void AbstractScopeWidget::leaveEvent(QEvent *)
273 {
274     m_mouseWithinWidget = false;
275     emit signalMousePositionChanged();
276 }
277
278 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
279 {
280     m_menu->exec(this->mapToGlobal(pos));
281 }
282
283 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
284 {
285     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
286 }
287 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
288 {
289     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
290 }
291 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
292 {
293     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
294 }
295
296
297 ///// Slots /////
298
299 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
300 {
301 //    qDebug() << "HUD rendering has finished, waiting for termination in " << m_widgetName;
302     m_threadHUD.waitForFinished();
303     m_imgHUD = m_threadHUD.result();
304
305     m_semaphoreHUD.release(1);
306     this->update();
307
308     int accel;
309     if (m_aRealtime->isChecked()) {
310         accel = calculateAccelFactorHUD(mseconds, oldFactor);
311         if (m_accelFactorHUD < 1) {
312             accel = 1;
313         }
314         m_accelFactorHUD = accel;
315     }
316
317     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
318 //        qDebug() << "Trying to start a new HUD thread for " << m_widgetName
319 //                << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
320         prodHUDThread();;
321     }
322 }
323
324 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
325 {
326     // The signal can be received before the thread has really finished. So we
327     // need to wait until it has really finished before starting a new thread.
328 //    qDebug() << "Scope rendering has finished, waiting for termination in " << m_widgetName;
329     m_threadScope.waitForFinished();
330     m_imgScope = m_threadScope.result();
331
332     // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
333     // See prodScopeThread where the semaphore is acquired again.
334     m_semaphoreScope.release(1);
335     this->update();
336
337     // Calculate the acceleration factor hint to get «realtime» updates.
338     int accel;
339     if (m_aRealtime->isChecked()) {
340         accel = calculateAccelFactorScope(mseconds, oldFactor);
341         if (accel < 1) {
342             // If mseconds happens to be 0.
343             accel = 1;
344         }
345         // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
346         // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
347         // then :) Therefore use a local variable.
348         m_accelFactorScope = accel;
349     }
350
351     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
352 //        qDebug() << "Trying to start a new scope thread for " << m_widgetName
353 //                << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
354         prodScopeThread();
355     }
356 }
357
358 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
359 {
360 //    qDebug() << "Background rendering has finished, waiting for termination in " << m_widgetName;
361     m_threadBackground.waitForFinished();
362     m_imgBackground = m_threadBackground.result();
363
364     m_semaphoreBackground.release(1);
365     this->update();
366
367     int accel;
368     if (m_aRealtime->isChecked()) {
369         accel = calculateAccelFactorBackground(mseconds, oldFactor);
370         if (m_accelFactorBackground < 1) {
371             accel = 1;
372         }
373         m_accelFactorBackground = accel;
374     }
375
376     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
377 //        qDebug() << "Trying to start a new background thread for " << m_widgetName
378 //                << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
379         prodBackgroundThread();;
380     }
381 }
382
383 void AbstractScopeWidget::slotActiveMonitorChanged(bool isClipMonitor)
384 {
385 //    qDebug() << "Active monitor has changed in " << m_widgetName << ". Is the clip monitor active now? " << isClipMonitor;
386
387     bool b = m_activeRender->disconnect(this);
388     Q_ASSERT(b);
389
390     m_activeRender = (isClipMonitor) ? m_clipMonitor->render : m_projMonitor->render;
391
392     //b &= connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
393     b &= connect(m_activeRender, SIGNAL(frameUpdated(QImage)), this, SLOT(slotRenderZoneUpdated(QImage)));
394     Q_ASSERT(b);
395
396     // Update the scope for the new monitor.
397     prodHUDThread();
398     prodScopeThread();
399     prodBackgroundThread();
400 }
401
402 void AbstractScopeWidget::slotRenderZoneUpdated()
403 {
404     m_newHUDFrames.fetchAndAddRelaxed(1);
405     m_newScopeFrames.fetchAndAddRelaxed(1);
406     m_newBackgroundFrames.fetchAndAddRelaxed(1);
407
408 //    qDebug() << "Monitor incoming. New frames total HUD/Scope/Background: " << m_newHUDFrames
409 //            << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
410
411     if (this->visibleRegion().isEmpty()) {
412 //        qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
413     } else {
414         if (m_aAutoRefresh->isChecked()) {
415             prodHUDThread();
416             prodScopeThread();
417             prodBackgroundThread();
418         }
419     }
420 }
421
422 void AbstractScopeWidget::slotRenderZoneUpdated(QImage frame)
423 {
424     m_scopeImage = frame;
425     slotRenderZoneUpdated();
426 }
427
428 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
429 {
430     if (!realtimeChecked) {
431         m_accelFactorHUD = 1;
432         m_accelFactorScope = 1;
433         m_accelFactorBackground = 1;
434     }
435 }
436
437 bool AbstractScopeWidget::autoRefreshEnabled()
438 {
439     return m_aAutoRefresh->isChecked();
440 }
441
442 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
443 {
444     if (isVisible()) emit requestAutoRefresh(autoRefresh);
445     // TODO only if depends on input
446     if (autoRefresh) {
447         forceUpdate();
448     }
449 }