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