Debian Codegraph @

doc/internal/media_manual.rst

raw
1 Media manual
2 ^^^^^^^^^^^^
3
4 Domain knowledge
5 ================
6
7 This tutorial http://dranger.com/ffmpeg/ffmpeg.html is a good intro for
8 building some domain knowledge. Bear in mind that the tutorial is rather old,
9 and some ffmpeg functions have become deprecated - but the basics are still
10 valid.
11
12 In the FFmpeg base code there is the ffplay.c player - a very good way to see
13 how things are managed. In particular, some newer FFmpeg functions are used,
14 while current pyglet media code still uses functions that have now been
15 deprecated.
16
17 Current code architecture
18 =========================
19
20 The overview of the media code is the following:
21
22 Source
23 ------
24
25 Found in media/sources folder.
26
27 :class:`~pyglet.media.Source` s represent data containing media
28 information. They can come from disk or be created in memory. A
29 :class:`~pyglet.media.Source` 's responsibility is to read or generate audio
30 and/or video data and then provide it. Essentially, it's a *producer*.
31
32 FFmpegStreamingSource
33 ---------------------
34
35 One implementation of the :class:`~pyglet.media.StreamingSource` is the
36 ``FFmpegSource``. It implements the :class:`~pyglet.media.Source` base class
37 by calling FFmpeg functions wrapped by ctypes and found in
38 media/sources/ffmpeg_lib. They offer basic functionalities for handling media
39 streams, such as opening a file, reading stream info, reading a packet, and
40 decoding audio and video packets.
41
42 The :class:`~pyglet.media.sources.ffmpeg.FFmpegSource` maintains two queues,
43 one for audio packets and one for video packets, with a pre-determined maximum
44 size. When the source is loaded, it will read packets from the stream and will
45 fill up the queues until one of them is full. It has then to stop because we
46 never know what type of packet we will get next from the stream. It could be a
47 packet of the same type as the filled up queue, in which case we would not be
48 able to store the additional packet.
49
50 Whenever a :class:`~pyglet.media.player.Player` - a consumer of a source -
51 asks for audio data or a video frame, the
52 :class:`~pyglet.media.Source` will pop the next packet from the
53 appropriate queue, decode the data, and return the result to the Player. If
54 this results in available space in both audio and video queues, it will read
55 additional packets until one of the queues is full again.
56
57 Player
58 ------
59
60 Found in media/player.py
61
62 The :class:`~pyglet.media.player.Player` is the main object that drives the
63 source. It maintains an internal sequence of sources or iterator of sources
64 that it can play sequentially. Its responsibilities are to play, pause and seek
65 into the source.
66
67 If the source contains audio, the :class:`~pyglet.media.player.Player` will
68 instantiate an ``AudioPlayer`` by asking the ``AudioDriver`` to create an
69 appropriate ``AudioPlayer`` for the given platform. The ``AudioDriver`` is a
70 singleton created according to which drivers are available. Currently
71 supported sound drivers are: DirectSound, OpenAL, PulseAudio and XAudio2.
72 A silent audio driver that consumes, but does not play back any audio is also
73 available.
74
75 If the source contains video, the Player has a
76 :meth:`~pyglet.media.Player.get_texture` method returning the current
77 video frame.
78
79 The player has an internal `master clock` which is used to synchronize the
80 video and the audio. The audio synchronization is delegated to the
81 ``AudioPlayer``. More info found below. The video synchronization is made by
82 asking the :class:`~pyglet.media.Source` for the next video timestamp.
83 The :class:`~pyglet.media.player.Player` then schedules on pyglet event loop a
84 call to its :meth:`~pyglet.media.Player.update_texture` with a delay
85 equals to the difference between the next video timestamp and the master clock
86 current time.
87
88 When :meth:`~pyglet.media.Player.update_texture` is called, we will
89 check if the actual master clock time is not too late compared to the video
90 timestamp. This could happen if the loop was very busy and the function could
91 not be called on time. In this case, the frame would be skipped until we find
92 a frame with a suitable timestamp for the current master clock time.
93
94 AudioPlayer
95 -----------
96
97 Found in media/drivers
98
99 The ``AudioPlayer`` is responsible for playing the audio data. It reads
100 from the :class:`~pyglet.media.Source`, and can be started, stopped or cleared.
101
102 In order to accomplish this task, the audio player keeps a reference to the
103 ``AudioDriver`` singleton which provides access to the lower level functions
104 for the selected audio driver, and its ``Player``, which it synchronizes with
105 and dispatches events to.
106
107 ``AudioPlayer`` s are bound to their source's
108 :class:`~pyglet.media.AudioFormat`. Once created, they can not play audio of
109 a different format.
110
111 ``AudioPlayer`` s will attempt to keep themselves in sync with their associated
112 ``Player`` . This is achieved by the ``_get_and_compensate_audio_data`` method.
113 The last 8 differences between their estimated audio time and their player's
114 master clock will be stored for each read chunk of audio data.
115 If the average of this value exceeds a value of 30ms, the player will start to
116 correct itself by either dropping or duplicating a very small amount of
117 samples at a time, 12ms by default.
118 If any single measurement exceeds 280ms, an extreme desync that is noticeable
119 in context of the app is assumed. If the ``AudioPlayer`` is running behind the
120 master clock, all of this audio data is skipped and the measurements are reset.
121 When running *ahead* by more than 280ms, nothing is done but the standard
122 stretching of 12ms at a time.
123
124 .. _audioplayer-play:
125
126 ``play``
127 """"""""
128
129 When instructed to play, the ``AudioPlayer`` will give whatever instructions
130 are necessary to its audio backend in order to start playing itself.
131
132 To not run out of data, it will add itself into the ``PlayerWorkerThread`` of
133 its audio driver. This thread is typically responsible for asking sources for
134 audio data to prevent the main thread/event loop from locking up on I/O
135 operations. The ``PlayerWorkerThread`` will regularly call
136 :ref:`audioplayer-work` on each ``AudioPlayer``.
137
138 This method may be called when already playing, and has no effect in that case.
139
140 .. _audioplayer-stop:
141
142 ``stop``
143 """"""""
144
145 This method causes the ``AudioPlayer`` to stop playing its audio stream, or to
146 pause it. It may be restarted with :ref:`audioplayer-play` later-on, which will
147 cause it to continue from where it stopped.
148
149 The first thing this method should do is to remove itself from its driver's
150 ``PlayerWorkerThread`` to ensure :ref:`audioplayer-work` won't be called while
151 it stops.
152
153 This method may be called when already stopped, and has no effect in that case.
154
155 .. _audioplayer-prefill_audio:
156
157 ``prefill_audio``
158 """""""""""""""""
159
160 This method is called from a ``Player`` whenever the ``AudioPlayer`` is about
161 to start playing and also before :ref:`audioplayer-play` is called for the
162 first time. The first batch of data is given from here, as backends using a
163 single audio buffer may play undefined data for a short amount of time before
164 the ``PlayerWorkerThread`` would load proper audio data in.
165
166 This method prefills the ideal amount of data for an ``AudioPlayer``, available
167 in ``_buffered_data_ideal_size``. By default this is given as 900ms of audio,
168 depending on the played source's audio format.
169
170 .. _audioplayer-work:
171
172 ``work``
173 """"""""
174
175 This method is only called from a ``PlayerWorkerThread``, though it may be
176 invoked through :ref:`audioplayer-prefill_audio`. As it is called from a
177 thread, implementing it error-free is difficult.
178
179 This method is responsible for refilling audio data if needed and often for
180 dispatching the :meth:`~pyglet.media.player.Player.on_eos` event.
181
182 Implementing this method comes with a lot of pitfalls. The following are free
183 to happen in other threads while the method is running:
184
185 The player is paused or unpaused.
186 Audio backends usually accept data for non-playing streams/sources/etc.,
187 so this is not too much of a problem. Realistically, this won't happen, all
188 current implementations contain a call to
189 ``self.driver.worker.remove/add(self)`` snippet in their
190 :ref:`audioplayer-play`/:ref:`audioplayer-stop` implementations.
191 That call will return only once the ``PlayerWorkerThread`` is done with a
192 work cycle.
193
194 In order for these calls to be most reliable, ``remove`` should be the
195 first statement in a :ref:`audioplayer-stop` implementation and ``add``
196 the last one in a :ref:`audioplayer-play` implementation, to ensure that
197 :ref:`audioplayer-work` will not be run after/will not start before player
198 attributes have been changed.
199
200 The player is deleted.
201 In order to combat this, ``self.driver.worker.remove(self)`` is used in all
202 implementations, ensuring delete calls will not interfere with the
203 :ref:`audioplayer-work` method.
204
205 A native callback runs, changing the internal state of the ``AudioPlayer``.
206 See below; protecting some sections with a lock local to the
207 ``AudioPlayer``. This lock should not be held around the call to
208 ``_get_and_compensate_audio_data``, as that renders the entire step of
209 offloading the loading/decoding work into a ``PlayerWorkerThread``
210 obsolete.
211
212 In pseudocode, the general way this method is implemented is: ::
213
214 def work():
215 update_play_cursor()
216 dispatch_media_events()
217 if not source_exhausted:
218 if play_cursor_too_close_to_write_cursor():
219 get_and_submit_new_audio_data()
220 if source_exhausted:
221 update_play_cursor()
222 else:
223 return
224 else:
225 return
226 if play_cursor > write_cursor and not has_underrun:
227 has_underrun = True
228 dispatch_on_eos()
229
230 If native callbacks are involved, running in yet another thread, the flow
231 tends to be different: ::
232
233 def work():
234 update_play_cursor()
235 dispatch_media_events()
236 if not source_exhausted:
237 if play_cursor_too_close_to_write_cursor():
238 get_and_submit_new_audio_data()
239 if has_underrun:
240 if source_exhausted:
241 dispatch_eon_eos()
242 else:
243 restart_player()
244 has_underrun = False
245
246 def on_underrun():
247 if source_exhausted:
248 dispatch_on_eos()
249 else:
250 has_underrun = True
251
252 High care must be taken to protect appropriate sections (any variables and
253 buffers which get accessed by both callbacks and the work method) with a lock,
254 otherwise the method is open to extremely unlucky issues where the callback
255 is unscheduled in favor of the work method or vice versa, which may cause one
256 of the functions to assume/operate based on a now outdated state.
257
258 ``work`` won't stop being called just because it dispatched ``on_eos``. The
259 method must make sure its source did not run out of audio data before to only
260 dispatch this event once.
261
262 .. _audioplayer-clear:
263
264 ``clear``
265 """""""""
266
267 This method may *only* be called when the ``AudioPlayer`` is not playing.
268 It causes it to discard all buffered data and reset itself to a clean initial
269 state.
270
271 ``delete``
272 """"""""""
273
274 This method will cause the ``AudioPlayer`` to stop playing and delete all its
275 native resources. In contrast to :ref:`audioplayer-clear`, it may be called at
276 any time. It may be called multiple times and must make sure it won't delete
277 already deleted resources.
278
279 AudioDriver
280 -----------
281
282 Found in media/drivers
283
284 The ``AudioDriver`` is a wrapper around the low-level sound driver available
285 on the platform. It's a singleton. It can create an ``AudioPlayer``
286 appropriate for the current ``AudioDriver``.
287
288 The ``AudioDriver`` usually contains a ``PlayerWorkerThread`` responsible for
289 keeping each ``AudioPlayer`` that is playing filled with data.
290
291 The ``AudioDriver`` provides an ``AudioListener``, which is used to place
292 a listener in the same space as each ``AudioPlayer``, enabling positional
293 audio.
294
295 Normal operation of the ``Player``
296 ----------------------------------
297
298 The client code instantiates a media player this way::
299
300 player = pyglet.media.Player()
301 source = pyglet.media.load(filename)
302 player.queue(source)
303 player.play()
304
305 When the client code runs ``player.play()``:
306
307 The :class:`~pyglet.media.player.Player` will check if there is an audio track
308 on the media. If so it will instantiate an ``AudioPlayer`` appropriate for the
309 available sound driver on the platform. It will create an empty
310 :class:`~pyglet.image.Texture` if the media contains video frames and will
311 schedule its :meth:`~pyglet.media.Player.update_texture` to be called
312 immediately. Finally it will start the master clock.
313
314 The ``AudioPlayer`` will start playing
315 :ref:`as described above <audioplayer-play>`.
316
317 When the :meth:`~pyglet.media.Player.update_texture` method is called,
318 the next video timestamp will be checked with the master clock. We allow a
319 delay up to the frame duration. If the master clock is beyond that time, the
320 frame will be skipped. We will check the following frames for its timestamp
321 until we find the appropriate frame for the master clock time. We will set the
322 :attr:`~pyglet.media.player.Player.texture` to the new video frame. We will
323 check for the next video frame timestamp and we will schedule a new call to
324 :meth:`~pyglet.media.Player.update_texture` with a delay equals to the
325 difference between the next video timestamps and the master clock time.
326
327 Helpful tools
328 =============
329
330 I've found that using the binary ffprobe is a good way to explore the content
331 of a media file. Here's a couple of things which might be
332 interesting and helpful::
333
334 ffprobe samples_v1.01\SampleVideo_320x240_1mb.3gp -show_frames
335
336 This will show information about each frame in the file. You can choose only
337 audio or only video frames by using the ``v`` flag for video and ``a`` for
338 audio.::
339
340 ffprobe samples_v1.01\SampleVideo_320x240_1mb.3gp -show_frames -select_streams v
341
342
343 You can also ask to see a subset of frame information this way::
344
345 ffprobe samples_v1.01\SampleVideo_320x240_1mb.3gp -show_frames
346 -select_streams v -show_entries frame=pkt_pts,pict_type
347
348 Finally, you can get a more compact view with the additional ``compact`` flag:
349
350 ffprobe samples_v1.01\SampleVideo_320x240_1mb.3gp -show_frames
351 -select_streams v -show_entries frame=pkt_pts,pict_type -of compact
352
353 Convert video to mkv
354 ====================
355
356 ::
357
358 ffmpeg -i <original_video> -c:v libx264 -preset slow -profile:v high -crf 18
359 -coder 1 -pix_fmt yuv420p -movflags +faststart -g 30 -bf 2 -c:a aac -b:a 384k
360 -profile:a aac_low <outputfilename.mkv>