]> git.sesse.net Git - kdenlive/blob - src/renderer.h
Fix jittering issues when sending GL textures cross-thread.
[kdenlive] / src / renderer.h
1 /***************************************************************************
2                          krender.h  -  description
3                             -------------------
4    begin                : Fri Nov 22 2002
5    copyright            : (C) 2002 by Jason Wood (jasonwood@blueyonder.co.uk)
6    copyright            : (C) 2010 by Jean-Baptiste Mardelle (jb@kdenlive.org)
7
8 ***************************************************************************/
9
10 /***************************************************************************
11  *                                                                         *
12  *   This program is free software; you can redistribute it and/or modify  *
13  *   it under the terms of the GNU General Public License as published by  *
14  *   the Free Software Foundation; either version 2 of the License, or     *
15  *   (at your option) any later version.                                   *
16  *                                                                         *
17  ***************************************************************************/
18
19 /**
20  * @class Render
21  * @brief Client side of the interface to a renderer.
22  *
23  * From Kdenlive's point of view, you treat the Render object as the renderer,
24  * and simply use it as if it was local. Calls are asynchronous - you send a
25  * call out, and then receive the return value through the relevant signal that
26  * get's emitted once the call completes.
27  */
28
29 #ifndef RENDERER_H
30 #define RENDERER_H
31
32 #include "gentime.h"
33 #include "definitions.h"
34 #include "widgets/abstractmonitor.h"
35
36 #include <GL/gl.h>
37 #include <mlt/framework/mlt_types.h>
38
39 #include <kurl.h>
40
41 #include <QtXml/qdom.h>
42 #include <QString>
43 #include <QMap>
44 #include <QList>
45 #include <QEvent>
46 #include <QMutex>
47 #include <QFuture>
48 #include <QSemaphore>
49 #include <QTimer>
50
51 class QGLWidget;
52 class QPixmap;
53
54 class KComboBox;
55
56 namespace Mlt
57 {
58 class Consumer;
59 class Playlist;
60 class Properties;
61 class Tractor;
62 class Transition;
63 class Frame;
64 class Field;
65 class Producer;
66 class Filter;
67 class Profile;
68 class Service;
69 class Event;
70 }
71
72 struct requestClipInfo {
73     QDomElement xml;
74     QString clipId;
75     int imageHeight;
76     bool replaceProducer;
77
78     bool operator==(const requestClipInfo &a)
79     {
80         return clipId == a.clipId;
81     }
82 };
83
84 class MltErrorEvent : public QEvent
85 {
86 public:
87     MltErrorEvent(const QString &message)
88         : QEvent(QEvent::User),
89           m_message(message)
90     {
91
92     }
93
94     QString message() const {
95         return m_message;
96     }
97
98 private:
99     QString m_message;
100 };
101
102
103 class Render: public AbstractRender
104 {
105     Q_OBJECT public:
106
107     enum FailStates { OK = 0,
108                       APP_NOEXIST
109                     };
110     /** @brief Build a MLT Renderer
111      *  @param rendererName A unique identifier for this renderer
112      *  @param winid The parent widget identifier (required for SDL display). Set to 0 for OpenGL rendering
113      *  @param profile The MLT profile used for the renderer (default one will be used if empty). */
114     Render(Kdenlive::MonitorId rendererName, int winid, QString profile = QString(), QWidget *parent = 0, QGLWidget *mainGLContext = 0);
115
116     /** @brief Destroy the MLT Renderer. */
117     virtual ~Render();
118
119     /** @brief Seeks the renderer clip to the given time. */
120     void seek(const GenTime &time);
121     void seek(int time);
122     void seekToFrameDiff(int diff);
123
124     QPixmap getImageThumbnail(const KUrl &url, int width, int height);
125
126     /** @brief Sets the current MLT producer playlist.
127      * @param list The xml describing the playlist
128      * @param position (optional) time to seek to */
129     int setSceneList(const QDomDocument &list, int position = 0);
130
131     /** @brief Sets the current MLT producer playlist.
132      * @param list new playlist
133      * @param position (optional) time to seek to
134      * @return 0 when it has success, different from 0 otherwise
135      *
136      * Creates the producer from the text playlist. */
137     int setSceneList(QString playlist, int position = 0);
138     int setProducer(Mlt::Producer *producer, int position);
139
140     /** @brief Get the current MLT producer playlist.
141      * @return A string describing the playlist */
142     const QString sceneList();
143     bool saveSceneList(QString path, QDomElement kdenliveData = QDomElement());
144
145     /** @brief Tells the renderer to play the scene at the specified speed,
146      * @param speed speed to play the scene to
147      *
148      * The speed is relative to normal playback, e.g. 1.0 is normal speed, 0.0
149      * is paused, -1.0 means play backwards. It does not specify start/stop */
150     void play(double speed);
151     void switchPlay(bool play);
152     void pause();
153
154     /** @brief Stops playing.
155      * @param startTime time to seek to */
156     void stop(const GenTime &startTime);
157     int volume() const;
158
159     QImage extractFrame(int frame_position, const QString &path = QString(), int width = -1, int height = -1);
160
161     /** @brief Plays the scene starting from a specific time.
162      * @param startTime time to start playing the scene from */
163     void play(const GenTime & startTime);
164     void playZone(const GenTime & startTime, const GenTime & stopTime);
165     void loopZone(const GenTime & startTime, const GenTime & stopTime);
166
167     void saveZone(KUrl url, QString desc, QPoint zone);
168     
169     /** @brief Save a clip in timeline to an xml playlist. */
170     bool saveClip(int track, const GenTime &position, const KUrl &url, const QString &desc = QString());
171
172     /** @brief Return true if we are currently playing */
173     bool isPlaying() const;
174
175     /** @brief Returns the speed at which the renderer is currently playing.
176      *
177      * It returns 0.0 when the renderer is not playing anything. */
178     double playSpeed() const;
179
180     /** @brief Returns the current seek position of the renderer. */
181     GenTime seekPosition() const;
182     int seekFramePosition() const;
183
184     void emitFrameUpdated(Mlt::Frame&);
185     void emitFrameNumber();
186     void emitConsumerStopped(bool forcePause = false);
187
188     /** @brief Returns the aspect ratio of the consumer. */
189     double consumerRatio() const;
190
191     /** @brief Saves current producer frame as an image. */
192     void exportCurrentFrame(const KUrl &url, bool notify);
193
194     /** @brief Change the Mlt PROFILE
195      * @param profileName The MLT profile name
196      * @param dropSceneList If true, the current playlist will be deleted
197      * @return true if the profile was changed
198      * . */
199     int resetProfile(const QString& profileName, bool dropSceneList = false);
200     /** @brief Returns true if the render uses profileName as current profile. */
201     bool hasProfile(const QString& profileName) const;
202     double fps() const;
203
204     /** @brief Returns the width of a frame for this profile. */
205     int frameRenderWidth() const;
206     /** @brief Returns the display width of a frame for this profile. */
207     int renderWidth() const;
208     /** @brief Returns the height of a frame for this profile. */
209     int renderHeight() const;
210
211     /** @brief Returns display aspect ratio. */
212     double dar() const;
213     /** @brief Returns sample aspect ratio. */
214     double sar() const;
215     /** @brief If monitor is active, refresh it. */
216     void refreshIfActive();
217     /** @brief Start the MLT monitor consumer. */
218     void startConsumer();
219
220     /*
221      * Playlist manipulation.
222      */
223     Mlt::Producer *checkSlowMotionProducer(Mlt::Producer *prod, QDomElement element);
224     int mltInsertClip(ItemInfo info, QDomElement element, Mlt::Producer *prod, bool overwrite = false, bool push = false);
225     bool mltUpdateClip(Mlt::Tractor *tractor, ItemInfo info, QDomElement element, Mlt::Producer *prod);
226     bool mltCutClip(int track, const GenTime &position);
227     void mltInsertSpace(QMap <int, int> trackClipStartList, QMap <int, int> trackTransitionStartList, int track, const GenTime &duration, const GenTime &timeOffset);
228     int mltGetSpaceLength(const GenTime &pos, int track, bool fromBlankStart);
229
230     /** @brief Returns the duration/length of @param track as reported by the track producer. */
231     int mltTrackDuration(int track);
232
233     bool mltResizeClipEnd(ItemInfo info, GenTime clipDuration, bool refresh = true);
234     bool mltResizeClipStart(ItemInfo info, GenTime diff);
235     bool mltResizeClipCrop(ItemInfo info, GenTime newCropStart);
236     bool mltMoveClip(int startTrack, int endTrack, GenTime pos, GenTime moveStart, Mlt::Producer *prod, bool overwrite = false, bool insert = false);
237     bool mltMoveClip(int startTrack, int endTrack, int pos, int moveStart, Mlt::Producer *prod, bool overwrite = false, bool insert = false);
238     bool mltRemoveClip(int track, GenTime position);
239
240     /** @brief Deletes an effect from a clip in MLT's playlist. */
241     bool mltRemoveEffect(int track, GenTime position, int index, bool updateIndex, bool doRefresh = true);
242     bool mltRemoveTrackEffect(int track, int index, bool updateIndex);
243
244     /** @brief Adds an effect to a clip in MLT's playlist. */
245     bool mltAddEffect(int track, GenTime position, EffectsParameterList params, bool doRefresh = true);
246     bool addFilterToService(Mlt::Service service, EffectsParameterList params, int duration);
247     bool mltAddEffect(Mlt::Service service, EffectsParameterList params, int duration, bool doRefresh);
248     bool mltAddTrackEffect(int track, EffectsParameterList params);
249     
250     /** @brief Enable / disable clip effects.
251      * @param track The track where the clip is
252      * @param position The start position of the clip
253      * @param effectIndexes The list of effect indexes to enable / disable
254      * @param disable True if effects should be disabled, false otherwise */
255     bool mltEnableEffects(int track, const GenTime &position, const QList<int> &effectIndexes, bool disable);
256     /** @brief Enable / disable track effects.
257      * @param track The track where the effect is
258      * @param effectIndexes The list of effect indexes to enable / disable
259      * @param disable True if effects should be disabled, false otherwise */
260     bool mltEnableTrackEffects(int track, const QList<int> &effectIndexes, bool disable);
261
262     /** @brief Edits an effect parameters in MLT's playlist. */
263     bool mltEditEffect(int track, const GenTime &position, EffectsParameterList params);
264     bool mltEditTrackEffect(int track, EffectsParameterList params);
265
266     /** @brief Updates the "kdenlive_ix" (index) value of an effect. */
267     void mltUpdateEffectPosition(int track, const GenTime &position, int oldPos, int newPos);
268
269     /** @brief Changes the order of effects in MLT's playlist.
270      *
271      * It switches effects from oldPos and newPos, updating the "kdenlive_ix"
272      * (index) value. */
273     void mltMoveEffect(int track, const GenTime &position, int oldPos, int newPos);
274     void mltMoveTrackEffect(int track, int oldPos, int newPos);
275
276     /** @brief Enables/disables audio/video in a track. */
277     void mltChangeTrackState(int track, bool mute, bool blind);
278     bool mltMoveTransition(QString type, int startTrack,  int newTrack, int newTransitionTrack, GenTime oldIn, GenTime oldOut, GenTime newIn, GenTime newOut);
279     bool mltAddTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool refresh = true);
280     void mltDeleteTransition(QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool refresh = true);
281     void mltUpdateTransition(QString oldTag, QString tag, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml, bool force = false);
282     void mltUpdateTransitionParams(QString type, int a_track, int b_track, GenTime in, GenTime out, QDomElement xml);
283     void mltAddClipTransparency(ItemInfo info, int transitiontrack, int id);
284     void mltMoveTransparency(int startTime, int endTime, int startTrack, int endTrack, int id);
285     void mltDeleteTransparency(int pos, int track, int id);
286     void mltResizeTransparency(int oldStart, int newStart, int newEnd, int track, int id);
287     QList <TransitionInfo> mltInsertTrack(int ix, bool videoTrack);
288     void mltDeleteTrack(int ix);
289     bool mltUpdateClipProducer(Mlt::Tractor *tractor, int track, int pos, Mlt::Producer *prod);
290     void mltPlantTransition(Mlt::Field *field, Mlt::Transition &tr, int a_track, int b_track);
291     Mlt::Producer *invalidProducer(const QString &id);
292
293     /** @brief Changes the speed of a clip in MLT's playlist.
294      *
295      * It creates a new "framebuffer" producer, which must have its "resource"
296      * property set to "video.mpg?0.6", where "video.mpg" is the path to the
297      * clip and "0.6" is the speed in percentage. The newly created producer
298      * will have its "id" property set to "slowmotion:parentid:speed", where
299      * "parentid" is the id of the original clip in the ClipManager list and
300      * "speed" is the current speed. */
301     int mltChangeClipSpeed(ItemInfo info, ItemInfo speedIndependantInfo, double speed, double oldspeed, int strobe, Mlt::Producer *prod);
302
303     const QList <Mlt::Producer *> producersList();
304     void updatePreviewSettings();
305     void setDropFrames(bool show);
306     /** @brief Sets an MLT consumer property. */
307     void setConsumerProperty(const QString &name, const QString &value);
308     QString updateSceneListFps(double current_fps, double new_fps, const QString &scene);
309
310     void showAudio(Mlt::Frame&);
311     
312     QList <int> checkTrackSequence(int);
313     void sendFrameUpdate();
314
315     /** @brief Returns a pointer to the main producer. */
316     Mlt::Producer *getProducer();
317     /** @brief Returns the number of clips to process (When requesting clip info). */
318     int processingItems();
319     /** @brief Processing of this clip is over, producer was set on clip, remove from list. */
320     void processingDone(const QString &id);
321     /** @brief Force processing of clip with selected id. */
322     void forceProcessing(const QString &id);
323     /** @brief Are we currently processing clip with selected id. */
324     bool isProcessing(const QString &id);
325
326     /** @brief Requests the file properties for the specified URL (will be put in a queue list)
327         @param xml The xml parameters for the clip
328         @param clipId The clip Id string
329         @param imageHeight The height (in pixels) of the returned thumbnail (height of a treewidgetitem in projectlist)
330         @param replaceProducer If true, the MLT producer will be recreated */
331     void getFileProperties(const QDomElement &xml, const QString &clipId, int imageHeight, bool replaceProducer = true);
332
333     /** @brief Lock the MLT service */
334     Mlt::Tractor *lockService();
335     /** @brief Unlock the MLT service */
336     void unlockService(Mlt::Tractor *tractor);
337     const QString activeClipId();
338     /** @brief Fill a combobox with the found blackmagic devices */
339     static bool getBlackMagicDeviceList(KComboBox *devicelist, bool force = false);
340     static bool getBlackMagicOutputDeviceList(KComboBox *devicelist, bool force = false);
341     /** @brief Frame rendering is handeled by Kdenlive, don't show video through SDL display */
342     void disablePreview(bool disable);
343     /** @brief Get current seek pos requested of SEEK_INACTIVE if we are not currently seeking */
344     int requestedSeekPosition;
345     /** @brief Get current seek pos requested of current producer pos if not seeking */
346     int getCurrentSeekPosition() const;
347     /** @brief Create a producer from url and load it in the monitor  */
348     void loadUrl(const QString &url);
349     /** @brief Check if the installed FFmpeg / Libav supports x11grab */
350     static bool checkX11Grab();
351     
352     /** @brief Ask to set this monitor as active */
353     void setActiveMonitor();
354     
355     QSemaphore showFrameSemaphore;
356     bool externalConsumer;
357
358 protected:
359     static void consumer_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr);
360     static void consumer_gl_frame_show(mlt_consumer, Render * self, mlt_frame frame_ptr);
361     static void consumer_thread_started(mlt_consumer, Render * self, mlt_frame frame_ptr);
362     static void consumer_thread_stopped(mlt_consumer, Render * self, mlt_frame frame_ptr);
363     
364 private:
365
366     /** @brief The name of this renderer.
367      *
368      * Useful to identify the renderers by what they do - e.g. background
369      * rendering, workspace monitor, etc. */
370     Kdenlive::MonitorId m_name;
371     Mlt::Consumer * m_mltConsumer;
372     Mlt::Producer * m_mltProducer;
373     Mlt::Profile *m_mltProfile;
374     Mlt::Event *m_showFrameEvent;
375     Mlt::Event *m_consumerThreadStartedEvent;
376     Mlt::Event *m_consumerThreadStoppedEvent;
377     Mlt::Event *m_pauseEvent;
378     double m_fps;
379
380     /** @brief True if we are playing a zone.
381      *
382      * It's determined by the "in" and "out" properties being temporarily
383      * changed. */
384     bool m_isZoneMode;
385     bool m_isLoopMode;
386     GenTime m_loopStart;
387
388     /** @brief True when the monitor is in split view. */
389     bool m_isSplitView;
390
391     Mlt::Producer *m_blackClip;
392     QString m_activeProfile;
393
394     QTimer *m_osdTimer;
395     QTimer m_refreshTimer;
396     QMutex m_mutex;
397     QMutex m_infoMutex;
398
399     /** @brief A human-readable description of this renderer. */
400     int m_winid;
401
402     QLocale m_locale;
403     QFuture <void> m_infoThread;
404     QList <requestClipInfo> m_requestList;
405     bool m_paused;
406     /** @brief True if this monitor is active. */
407     bool m_isActive;
408     QGLWidget *m_mainGLContext;
409     QGLWidget *m_GLContext;
410     QMap<pthread_t, QGLWidget *> m_renderThreadGLContexts;
411     Mlt::Filter* m_glslManager;
412
413     void closeMlt();
414     void mltCheckLength(Mlt::Tractor *tractor);
415     void mltPasteEffects(Mlt::Producer *source, Mlt::Producer *dest);
416     QMap<QString, QString> mltGetTransitionParamsFromXml(const QDomElement &xml);
417     QMap<QString, Mlt::Producer *> m_slowmotionProducers;
418     /** @brief The ids of the clips that are currently being loaded for info query */
419     QStringList m_processingClipId;
420
421     /** @brief Build the MLT Consumer object with initial settings.
422      *  @param profileName The MLT profile to use for the consumer */
423     void buildConsumer(const QString& profileName);
424     void resetZoneMode();
425     void fillSlowMotionProducers();
426     /** @brief Get the track number of the lowest audible (non muted) audio track
427      *  @param return The track number */
428     int getLowestNonMutedAudioTrack(Mlt::Tractor tractor);
429
430     /** @brief Make sure our audio mixing transitions are applied to the lowest track */
431     void fixAudioMixing(Mlt::Tractor tractor);
432     /** @brief Make sure we inform MLT if we need a lot of threads for avformat producer */
433     void checkMaxThreads();
434     /** @brief Clone serialisable properties only */
435     void cloneProperties(Mlt::Properties &dest, Mlt::Properties &source);
436
437 private slots:
438
439     /** @brief Refreshes the monitor display. */
440     void refresh();
441     void slotOsdTimeout();
442     /** @brief Process the clip info requests (in a separate thread). */
443     void processFileProperties();
444     /** @brief A clip with multiple video streams was found, ask what to do. */
445     void slotMultiStreamProducerFound(const QString &path, QList<int> audio_list, QList<int> video_list, stringMap data);
446     void showFrame(Mlt::Frame *);
447     void slotCheckSeeking();
448
449 signals:
450
451     /** @brief The renderer received a reply to a getFileProperties request. */
452     void replyGetFileProperties(const QString &clipId, Mlt::Producer*, const stringMap &, const stringMap &, bool replaceProducer);
453
454     /** @brief The renderer received a reply to a getImage request. */
455     void replyGetImage(const QString &, const QString &, int, int);
456     void replyGetImage(const QString &, const QImage &);
457
458     /** @brief The renderer stopped, either playing or rendering. */
459     void stopped();
460
461     /** @brief The renderer started playing. */
462     void playing(double);
463
464     /** @brief The renderer started rendering. */
465     void rendering(const GenTime &);
466
467     /** @brief An error occurred within this renderer. */
468     void error(const QString &, const QString &);
469     void durationChanged(int);
470     void rendererPosition(int);
471     void rendererStopped(int);
472     /** @brief The clip is not valid, should be removed from project. */
473     void removeInvalidClip(const QString &, bool replaceProducer);
474     /** @brief The proxy is not valid, should be deleted.
475      *  @param id The original clip's id
476      *  @param durationError Should be set to true if the proxy failed because it has not same length as original clip
477      */
478     void removeInvalidProxy(const QString &id, bool durationError);
479     void refreshDocumentProducers(bool displayRatioChanged, bool fpsChanged);
480     /** @brief A proxy clip is missing, ask for creation. */
481     void requestProxy(QString);
482     /** @brief A multiple stream clip was found. */
483     void multiStreamFound(const QString &,QList<int>,QList<int>,stringMap data);
484
485
486     /** @brief A frame's image has to be shown.
487      *
488      * Used in Mac OS X. */
489     void showImageSignal(QImage);
490     void showImageSignal(Mlt::Frame*, GLuint);
491     void showAudioSignal(const QVector<double> &);
492     void addClip(const KUrl &, stringMap);
493     void checkSeeking();
494     /** @brief Activate current monitor. */
495     void activateMonitor(Kdenlive::MonitorId);
496     void mltFrameReceived(Mlt::Frame *);
497
498 public slots:
499
500     /** @brief Starts the consumer. */
501     void start();
502
503     /** @brief Stops the consumer. */
504     void stop();
505     int getLength();
506
507     /** @brief Checks if the file is readable by MLT. */
508     bool isValid(const KUrl &url);
509
510     void exportFileToFirewire(QString srcFileName, int port, GenTime startTime, GenTime endTime);
511     void mltSavePlaylist();
512     void slotSplitView(bool doit);
513     void slotSwitchFullscreen();
514     void slotSetVolume(int volume);
515     void seekToFrame(int pos);
516     /** @brief Starts a timer to query for a refresh. */
517     void doRefresh();
518 };
519
520 #endif