e2921509721ee0c0583e5a88f2384a5e1358aaaa
[platform/upstream/gstreamer.git] / docs / design / part-overview.txt
1 Overview
2 --------
3
4 This part gives an overview of the design of GStreamer with references to
5 the more detailed explanations of the different topics.
6
7 This document is intented for people that want to have a global overview of
8 the inner workings of GStreamer.
9
10
11 Introduction
12 ~~~~~~~~~~~~
13
14 GStreamer is a set of libraries and plugins that can be used to implement various
15 multimedia applications ranging from desktop players, audio/video recorders, 
16 multimedia servers, transcoders, etc. 
17
18 Applications are built by constructing a pipeline composed of elements. An element
19 is an object that performs some action on a multimedia stream such as:
20
21 - read a file
22 - decode or encode between formats
23 - capture from a hardware device
24 - render to a hardware device
25 - mix or multiplex multiple streams
26
27 Elements have input and output pads called sink and source pads in GStreamer. An
28 application links elements together on pads to construct a pipeline. Below is
29 an example of an ogg/vorbis playback pipeline.
30
31    +-----------------------------------------------------------+
32    |    ----------> downstream ------------------->            |
33    |                                                           |
34    | pipeline                                                  |
35    | +---------+   +----------+   +-----------+   +----------+ |
36    | | filesrc |   | oggdemux |   | vorbisdec |   | alsasink | |
37    | |        src-sink       src-sink        src-sink        | |
38    | +---------+   +----------+   +-----------+   +----------+ |
39    |                                                           |
40    |    <---------< upstream <-------------------<             |
41    +-----------------------------------------------------------+
42
43 The filesrc element reads data from a file on disk. The oggdemux element parses
44 the data and sends the compressed audio data to the vorbisdec element. The
45 vorbisdec element decodes the compressed data and sends it to the alsasink
46 element. The alsasink element sends the samples to the audio card for playback.
47
48 Downstream and upstream are the terms used to describe the direction in the
49 Pipeline. From source to sink is called "downstream" and "upstream" is 
50 from sink to source. Dataflow always happens downstream.
51
52 The task of the application is to construct a pipeline as above using existing
53 elements. This is further explained in the pipeline building topic.
54
55 The application does not have to manage any of the complexities of the
56 actual dataflow/decoding/conversions/synchronisation etc. but only calls high
57 level functions on the pipeline object such as PLAY/PAUSE/STOP.
58
59 The application also receives messages and notifications from the pipeline such
60 as metadata, warning, error and EOS messages.
61
62 If the application needs more control over the graph it is possible to directly
63 access the elements and pads in the pipeline.
64
65
66 Design overview
67 ~~~~~~~~~~~~~~~
68
69 GStreamer design goals include:
70
71 - Process large amounts of data quickly
72 - Allow fully multithreaded processing
73 - Ability to deal with multiple formats
74 - Synchronize different dataflows 
75 - Ability to deal with multiple devices
76
77 The capabilities presented to the application depends on the number of elements
78 installed on the system and their functionality.
79
80 The GStreamer core is designed to be media agnostic but provides many features
81 to elements to describe media formats.
82
83
84 Elements
85 ~~~~~~~~
86
87 The smallest building blocks in a pipeline are elements. An element provides a
88 number of pads which can be source or sinkpads. Sourcepads provide data and
89 sinkpads consume data. Below is an example of an ogg demuxer element that has
90 one pad that takes (sinks) data and two source pads that produce data.
91
92     +-----------+
93     | oggdemux  |
94     |          src0
95    sink        src1
96     +-----------+
97
98 An element can be in four different states: NULL, READY, PAUSED, PLAYING. In the
99 NULL and READY state, the element is not processing any data. In the PLAYING state
100 it is processing data. The intermediate PAUSED state is used to preroll data in
101 the pipeline. A state change can be performed with gst_element_set_state().
102
103 An element always goes through all the intermediate state changes. This means that
104 when en element is in the READY state and is put to PLAYING, it will first go
105 through the intermediate PAUSED state.
106
107 An element state change to PAUSED will activate the pads of the element. First the
108 source pads are activated, then the sinkpads. When the pads are activated, the
109 pad activate function is called. Some pads will start a thread (GstTask) or some 
110 other mechanism to start producing or consuming data.
111
112 The PAUSED state is special as it is used to preroll data in the pipeline. The purpose
113 is to fill all connected elements in the pipeline with data so that the subsequent
114 PLAYING state change happens very quickly. Some elements will therefore not complete
115 the state change to PAUSED before they have received enough data. Sink elements are
116 required to only complete the state change to PAUSED after receiving the first data.
117
118 Normally the state changes of elements are coordinated by the pipeline as explained
119 in [part-states.txt].
120
121 Different categories of elements exist:
122
123 - source elements, these are elements that do not consume data but only provide data
124     for the pipeline.
125 - sink elements, these are elements that do not produce data but renders data to
126     an output device.
127 - transform elements, these elements transform an input stream in a certain format 
128    into a stream of another format. Encoder/decoder/converters are examples.
129 - demuxer elements, these elements parse a stream and produce several output streams.
130 - mixer/muxer elements, combine several input streams into one output stream.
131
132 Other categories of elements can be constructed (see part-klass.txt).
133
134
135 Bins
136 ~~~~
137
138 A bin is an element subclass and acts as a container for other elements so that multiple 
139 elements can be combined into one element.
140
141 A bin coordinates its children's state changes as explained later. It also distributes
142 events and various other functionality to elements.
143
144 A bin can have its own source and sinkpads by ghostpadding one or more of its children's
145 pads to itself.
146
147 Below is a picture of a bin with two elements. The sinkpad of one element is ghostpadded
148 to the bin.
149
150     +---------------------------+    
151     | bin                       |
152     |    +--------+   +-------+ |
153     |    |        |   |       | |
154     |  /sink     src-sink     | |
155    sink  +--------+   +-------+ |
156     +---------------------------+
157
158
159 Pipeline
160 ~~~~~~~~
161
162 A pipeline is a special bin subclass that provides the following features to its 
163 children:
164
165  - Select and manage a global clock for all its children.
166  - Manage running_time based on the selected clock. Running_time is the elapsed
167    time the pipeline spent in the PLAYING state and is used for
168    synchronisation.
169  - Manage latency in the pipeline.
170  - Provide means for elements to comunicate with the application by the GstBus.
171  - Manage the global state of the elements such as Errors and end-of-stream.
172
173 Normally the application creates one pipeline that will manage all the elements
174 in the application.
175
176
177 Dataflow and buffers
178 ~~~~~~~~~~~~~~~~~~~~
179
180 GStreamer supports two possible types of dataflow, the push and pull model. In the
181 push model, an upstream element sends data to a downstream element by calling a
182 method on a sinkpad. In the pull model, a downstream element requests data from
183 an upstream element by calling a method on a source pad.
184
185 The most common dataflow is the push model. The pull model can be used in specific
186 circumstances by demuxer elements. The pull model can also be used by low latency
187 audio applications.
188
189 The data passed between pads is encapsulated in Buffers. The buffer contains a
190 pointer to the actual data and also metadata describing the data. This metadata
191 includes:
192  
193   - timestamp of the data, this is the time instance at which the data was captured
194       or the time at which the data should be played back.
195   - offset of the data: a media specific offset, this could be samples for audio or
196       frames for video.
197   - the duration of the data in time.
198   - the media type of the data described with caps, these are key/value pairs that
199       describe the media type in a unique way.
200   - additional flags describing special properties of the data such as 
201     discontinuities or delta units.
202
203 When an element whishes to send a buffer to another element is does this using one
204 of the pads that is linked to a pad of the other element. In the push model, a 
205 buffer is pushed to the peer pad with gst_pad_push(). In the pull model, a buffer
206 is pulled from the peer with the gst_pad_pull_range() function.
207
208 Before an element pushes out a buffer, it should make sure that the peer element
209 can understand the buffer contents.  It does this by querying the peer element
210 for the supported formats and by selecting a suitable common format. The selected
211 format is then attached to the buffer with gst_buffer_set_caps() before pushing
212 out the buffer.
213
214 When an element pad receives a buffer, if has to check if it understands the media
215 type of the buffer before starting processing it. The GStreamer core does this
216 automatically and will call the gst_pad_set_caps() function of the element before
217 sending the buffer to the element.
218
219 Both gst_pad_push() and gst_pad_pull_range() have a return value indicating whether
220 the operation succeeded. An error code means that no more data should be sent
221 to that pad. A source element that initiates the data flow in a thread typically
222 pauses the producing thread when this happens.
223
224 A buffer can be created with gst_buffer_new() or by requesting a usable buffer
225 from the peer pad using gst_pad_alloc_buffer(). Using the second method, it is
226 possible for the peer element to suggest the element to produce data in another 
227 format by attaching another media type caps to the buffer.
228
229 The process of selecting a media type and attaching it to the buffers is called
230 caps negotiation.
231
232
233 Caps
234 ~~~~
235
236 A media type (Caps) is described using a generic list of key/value pairs. The key is
237 a string and the value can be a single/list/range of int/float/string. 
238
239 Caps that have no ranges/list or other variable parts are said to be fixed and
240 can be used to put on a buffer.
241
242 Caps with variables in them are used to describe possible media types that can be
243 handled by a pad.
244
245
246 Dataflow and events
247 ~~~~~~~~~~~~~~~~~~~
248
249 Parallel to the dataflow is a flow of events. Unlike the buffers, events can pass
250 both upstream and downstream. Some events only travel upstream others only downstream.
251
252 The events are used to denote special conditions in the dataflow such as EOS or 
253 to inform plugins of special events such as flushing or seeking.
254
255 Some events must be serialized with the buffer flow, others don't. Serialized 
256 events are inserted between the buffers. Non serialized events jump in front
257 of any buffers current being processed.
258
259 An example of a serialized event is a TAG event that is inserted between buffers
260 to mark metadata for those buffers.
261
262 An example of a non serialized event is the FLUSH event.
263
264
265 Pipeline construction
266 ~~~~~~~~~~~~~~~~~~~~~
267
268 The application starts by creating a Pipeline element using gst_pipeline_new ().
269 Elements are added to and removed from the pipeline with gst_bin_add() and
270 gst_bin_remove().
271
272 After adding the elements, the pads of an element can be retrieved with
273 gst_element_get_pad(). Pads can then be linked together with gst_pad_link().
274
275 Some elements create new pads when actual dataflow is happening in the pipeline.
276 With g_signal_connect() one can receive a notification when an element has created
277 a pad. These new pads can then be linked to other unlinked pads.
278
279 Some elements cannot be linked together because they operate on different 
280 incompatible data types. The possible datatypes a pad can provide or consume can
281 be retrieved with gst_pad_get_caps().
282
283 Below is a simple mp3 playback pipeline that we constructed. We will use this
284 pipeline in further examples.
285  
286    +-------------------------------------------+
287    | pipeline                                  |
288    | +---------+   +----------+   +----------+ |
289    | | filesrc |   | mp3dec   |   | alsasink | |
290    | |        src-sink       src-sink        | |
291    | +---------+   +----------+   +----------+ |
292    +-------------------------------------------+
293
294
295 Pipeline clock
296 ~~~~~~~~~~~~~~
297
298 One of the important functions of the pipeline is to select a global clock
299 for all the elements in the pipeline.
300
301 The purpose of the clock is to provide a stricly increasing value at the rate
302 of one GST_SECOND per second. Clock values are expressed in nanoseconds.
303 Elements use the clock time to synchronize the playback of data.
304
305 Before the pipeline is set to PLAYING, the pipeline asks each element if they can
306 provide a clock. The clock is selected in the following order:
307
308 - If the application selected a clock, use that one.
309 - If a source element provides a clock, use that clock.
310 - Select a clock from any other element that provides a clock, start with the
311   sinks.
312 - If no element provides a clock a default system clock is used for the pipeline.
313
314 In a typical playback pipeline this algorithm will select the clock provided by 
315 a sink element such as an audio sink.
316
317 In capture pipelines, this will typically select the clock of the data producer, which
318 in most cases can not control the rate at which it produces data.
319
320
321 Pipeline states
322 ~~~~~~~~~~~~~~~
323
324 When all the pads are linked and signals have been connected, the pipeline can
325 be put in the PAUSED state to start dataflow. 
326
327 When a bin (and hence a pipeline) performs a state change, it will change the state
328 of all its children. The pipeline will change the state of its children from the
329 sink elements to the source elements, this to make sure that no upstream element
330 produces data to an element that is not yet ready to accept it. 
331
332 In the mp3 playback pipeline, the state of the elements is changed in the order
333 alsasink, mp3dec, filesrc.
334
335 All intermediate states are traversed for each element resulting in the following
336 chain of state changes:
337
338  alsasink to READY:  the audio device is probed
339  mp3dec to READY:    nothing happens.
340  filesrc to READY:   the file is probed
341  alsasink to PAUSED: the audio device is opened. alsasink is a sink and returns 
342                      ASYNC because it did not receive data yet.
343  mp3dec to PAUSED:   the decoding library is initialized
344  filesrc to PAUSED:  the file is opened and a thread is started to push data to 
345                      mp3dec
346
347 At this point data flows from filesrc to mp3dec and alsasink. Since mp3dec is PAUSED,
348 it accepts the data from filesrc on the sinkpad and starts decoding the compressed
349 data to raw audio samples.
350
351 The mp3 decoder figures out the samplerate, the number of channels and other audio
352 properties of the raw audio samples, puts the decoded samples into a Buffer,  
353 attaches the media type caps to the buffer and pushes this buffer to the next
354 element.
355
356 Alsasink then receives the buffer, inspects the caps and reconfigures itself to process
357 the buffer. Since it received the first buffer of samples, it completes the state change
358 to the PAUSED state. At this point the pipeline is prerolled and all elements have
359 samples. Alsasink is now also capable of providing a clock to the pipeline.
360
361 Since alsasink is now in the PAUSED state it blocks while receiving the first buffer. This
362 effectively blocks both mp3dec and filesrc in their gst_pad_push().
363
364 Since all elements now return SUCCESS from the gst_element_get_state() function,
365 the pipeline can be put in the PLAYING state.
366
367 Before going to PLAYING, the pipeline select a clock and samples the current time of 
368 the clock. This is the base_time. It then distributes this time to all elements. 
369 Elements can then synchronize against the clock using the buffer running_time +
370 base_time (See also part-synchronisation.txt). 
371
372 The following chain of state changes then takes place:
373
374  alsasink to PLAYING:  the samples are played to the audio device
375  mp3dec to PLAYING:    nothing happens
376  filesrc to PLAYING:   nothing happens
377
378
379 Pipeline status
380 ~~~~~~~~~~~~~~~
381
382 The pipeline informs the application of any special events that occur in the
383 pipeline with the bus. The bus is an object that the pipeline provides and that
384 can be retrieved with gst_pipeline_get_bus().
385
386 The bus can be polled or added to the glib mainloop.
387
388 The bus is distributed to all elements added to the pipeline. The elements use the bus
389 to post messages on. Various message types exist such as ERRORS, WARNINGS, EOS, 
390 STATE_CHANGED, etc..
391
392 The pipeline handles EOS messages received from elements in a special way. It will
393 only forward the message to the application when all sink elements have posted an
394 EOS message.
395
396 Other methods for obtaining the pipeline status include the Query functionality that
397 can be performed with gst_element_query() on the pipeline. This type of query
398 is useful for obtaining information about the current position and total time of
399 the pipeline. It can also be used to query for the supported seeking formats and
400 ranges.
401
402
403 Pipeline EOS
404 ~~~~~~~~~~~~
405
406 When the source filter encounters the end of the stream, it sends an EOS event to
407 the peer element. This event will then travel downstream to all of the connected
408 elements to inform them of the EOS. The element is not supposed to accept any more
409 data after receiving an EOS event on a sinkpad.
410
411 The element providing the streaming thread stops sending data after sending the 
412 EOS event.
413
414 The EOS event will eventually arrive in the sink element. The sink will then post
415 an EOS message on the bus to inform the pipeline that a particular stream has
416 finished. When all sinks have reported EOS, the pipeline forwards the EOS message
417 to the application. The EOS message is only forwarded to the application in the
418 PLAYING state.
419
420 When in EOS, the pipeline remains in the PLAYING state, it is the applications
421 responsability to PAUSE or READY the pipeline. The application can also issue
422 a seek, for example.
423
424
425 Pipeline READY
426 ~~~~~~~~~~~~~~
427
428 When a running pipeline is set from the PLAYING to READY state, the following 
429 actions occur in the pipeline:
430
431  alsasink to PAUSED:  alsasink blocks and completes the state change on the
432                       next sample. If the element was EOS, it does not wait for
433                       a sample to complete the state change.
434  mp3dec to PAUSED:    nothing 
435  filesrc to PAUSED:   nothing
436
437 Going to the intermediate PAUSED state will block all elements in the _push()
438 functions. This happens because the sink element blocks on the first buffer
439 it receives.
440
441 Some elements might be performing blocking operations in the PLAYING state that
442 must be unblocked when they go into the PAUSED state. This makes sure that the
443 state change happens very fast.
444
445 In the next PAUSED to READY state change the pipeline has to shut down and all
446 streaming threads must stop sending data. This happens in the following sequence:
447
448  alsasink to READY:   alsasink unblocks from the _chain() function and returns a
449                       WRONG_STATE return value to the peer element. The sinkpad is
450                       deactivated and becomes unusable for sending more data. 
451  mp3dec to READY:     the pads are deactivated and the state change completes when
452                       mp3dec leaves its _chain() function. 
453  filesrc to READY:    the pads are deactivated and the thread is paused.
454
455 The upstream elements finish their chain() function because the downstream element
456 returned an error code (WRONG_STATE) from the _push() functions. These error codes 
457 are eventually returned to the element that started the streaming thread (filesrc),
458 which pauses the thread and completes the state change.
459
460 This sequence of events ensure that all elements are unblocked and all streaming
461 threads stopped.
462
463
464 Pipeline seeking
465 ~~~~~~~~~~~~~~~~
466
467 Seeking in the pipeline requires a very specific order of operations to make
468 sure that the elements remain synchronized and that the seek is performed with
469 a minimal amount of latency.
470
471 An application issues a seek event on the pipeline using gst_element_send_event()
472 on the pipeline element. The event can be a seek event in any of the formats
473 supported by the elements.
474
475 The pipeline first pauses the pipeline to speed up the seek operations.
476
477 The pipeline then issues the seek event to all sink elements. The sink then forwards 
478 the seek event upstream until some element can perform the seek operation, which is
479 typically the source or demuxer element. All intermediate elements can transform the
480 requested seek offset to another format, this way a decoder element can transform a
481 seek to a frame number to a timestamp, for example.
482
483 When the seek event reaches an element that will perform the seek operation, that 
484 element performs the following steps.
485
486   1) send a FLUSH_START event to all downstream and upstream peer elements.
487   2) make sure the streaming thread is not running. The streaming thread will
488      always stop because of step 1).
489   3) perform the seek operation
490   4) send a FLUSH done event to all downstream and upstream peer elements.
491   5) send NEWSEGMENT event to inform all elements of the new position and to complete
492      the seek.
493
494 In step 1) all downstream elements have to return from any blocking operations
495 and have to refuse any further buffers or events different from a FLUSH done.
496
497 The first step ensures that the streaming thread eventually unblocks and that
498 step 2) can be performed. At this point, dataflow is completely stopped in the
499 pipeline. 
500
501 In step 3) the element performs the seek to the requested position. 
502
503 In step 4) all peer elements are allowed to accept data again and streaming
504 can continue from the new position. A FLUSH done event is sent to all the peer
505 elements so that they accept new data again and restart their streaming threads.
506
507 Step 5) informs all elements of the new position in the stream. After that the
508 event function returns back to the application. and the streaming threads start
509 to produce new data.
510
511 Since the pipeline is still PAUSED, this will preroll the next media sample in the
512 sinks. The application can wait for this preroll to complete by performing a 
513 _get_state() on the pipeline.
514
515 The last step in the seek operation is then to adjust the stream time of the pipeline
516 to 0 and to set the pipeline back to PLAYING.
517
518 The sequence of events in our mp3 playback example.
519
520                                       | a) seek on pipeline
521                                       | b) PAUSE pipeline
522    +----------------------------------V--------+
523    | pipeline                         | c) seek on sink
524    | +---------+   +----------+   +---V------+ |
525    | | filesrc |   | mp3dec   |   | alsasink | |
526    | |        src-sink       src-sink        | |
527    | +---------+   +----------+   +----|-----+ |
528    +-----------------------------------|-------+
529               <------------------------+
530                     d) seek travels upstream
531
532               --------------------------> 1) FLUSH event
533               | 2) stop streaming
534               | 3) perform seek
535               --------------------------> 4) FLUSH done event
536               --------------------------> 5) NEWSEGMENT event
537   
538                                       | e) update stream time to 0
539                                       | f) PLAY pipeline
540