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