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