Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / docs / design / part-latency.txt
1 Latency
2 -------
3
4 The latency is the time it takes for a sample captured at timestamp 0 to reach the
5 sink. This time is measured against the clock in the pipeline. For pipelines
6 where the only elements that synchronize against the clock are the sinks, the
7 latency is always 0 since no other element is delaying the buffer.
8
9 For pipelines with live sources, a latency is introduced, mostly because of the
10 way a live source works. Consider an audio source, it will start capturing the
11 first sample at time 0. If the source pushes buffers with 44100 samples at a
12 time at 44100Hz it will have collected the buffer at second 1.
13 Since the timestamp of the buffer is 0 and the time of the clock is now >= 1
14 second, the sink will drop this buffer because it is too late.
15 Without any latency compensation in the sink, all buffers will be dropped.
16
17 The situation becomes more complex in the presence of:
18
19  - 2 live sources connected to 2 live sinks with different latencies
20     * audio/video capture with synchronized live preview.
21     * added latencies due to effects (delays, resamplers...)
22  - 1 live source connected to 2 live sinks
23     * firewire DV
24     * RTP, with added latencies because of jitter buffers.
25  - mixed live source and non-live source scenarios.
26     * synchronized audio capture with non-live playback. (overdubs,..)
27  - clock slaving in the sinks due to the live sources providing their own
28    clocks.
29
30 To perform the needed latency corrections in the above scenarios, we must
31 develop an algorithm to calculate a global latency for the pipeline. The
32 algorithm must be extensible so that it can optimize the latency at runtime. 
33 It must also be possible to disable or tune the algorithm based on specific
34 application needs (required minimal latency).
35
36
37 Pipelines without latency compensation
38 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
39
40 We show some examples to demonstrate the problem of latency in typical
41 capture pipelines.
42
43 - Example 1
44
45   An audio capture/playback pipeline.
46
47    asrc: audio source, provides a clock
48    asink audio sink, provides a clock
49
50    .--------------------------.
51    | pipeline                 |
52    | .------.      .-------.  |
53    | | asrc |      | asink |  |
54    | |     src -> sink     |  |
55    | '------'      '-------'  |
56    '--------------------------'
57
58  NULL->READY:
59   asink: NULL->READY: probes device, returns SUCCESS 
60   asrc: NULL->READY:  probes device, returns SUCCESS
61
62  READY->PAUSED:
63   asink: READY:->PAUSED open device, returns ASYNC 
64   asrc: READY->PAUSED:  open device, returns NO_PREROLL
65
66   * Since the source is a live source, it will only produce data in the
67     PLAYING state. To note this fact, it returns NO_PREROLL from the state change
68     function.
69   * This sink returns ASYNC because it can only complete the state change to
70     PAUSED when it receives the first buffer.
71
72   At this point the pipeline is not processing data and the clock is not
73   running. Unless a new action is performed on the pipeline, this situation will
74   never change.
75
76  PAUSED->PLAYING:
77   asrc clock selected because it is the most upstream clock provider. asink can
78   only provide a clock when it received the first buffer and configured the
79   device with the samplerate in the caps.
80
81   asink: PAUSED:->PLAYING, sets pending state to PLAYING, returns ASYNC becaus
82                          it is not prerolled. The sink will commit state to
83                          PLAYING when it prerolls.
84   asrc: PAUSED->PLAYING: starts pushing buffers.
85
86   * since the sink is still performing a state change from READY -> PAUSED, it
87     remains ASYNC. The pending state will be set to PLAYING.
88   * The clock starts running as soon as all the elements have been set to
89     PLAYING.
90   * the source is a live source with a latency. Since it is synchronized with
91     the clock, it will produce a buffer with timestamp 0 and duration D after
92     time D, ie. it will only be able to produce the last sample of the buffer
93     (with timestamp D) at time D. This latency depends on the size of the
94     buffer.
95   * the sink will receive the buffer with timestamp 0 at time >= D. At this
96     point the buffer is too late already and might be dropped. This state of
97     constantly dropping data will not change unless a constant latency
98     correction is added to the incoming buffer timestamps.
99
100   The problem is due to the fact that the sink is set to (pending) PLAYING
101   without being prerolled, which only happens in live pipelines. 
102
103 - Example 2
104
105   An audio/video capture/playback pipeline. We capture both audio and video and
106   have them played back synchronized again.
107
108    asrc: audio source, provides a clock
109    asink audio sink, provides a clock
110    vsrc: video source
111    vsink video sink
112
113    .--------------------------.
114    | pipeline                 |
115    | .------.      .-------.  |
116    | | asrc |      | asink |  |
117    | |     src -> sink     |  |
118    | '------'      '-------'  |
119    | .------.      .-------.  |
120    | | vsrc |      | vsink |  |
121    | |     src -> sink     |  |
122    | '------'      '-------'  |
123    '--------------------------'
124
125   The state changes happen in the same way as example 1. Both sinks end up with
126   pending state of PLAYING and a return value of ASYNC until they receive the
127   first buffer.
128
129   For audio and video to be played in sync, both sinks must compensate for the
130   latency of its source but must also use exactly the same latency correction.  
131
132   Suppose asrc has a latency of 20ms and vsrc a latency of 33ms, the total
133   latency in the pipeline has to be at least 33ms. This also means that the
134   pipeline must have at least a 33 - 20 = 13ms buffering on the audio stream or
135   else the audio src will underrun while the audiosink waits for the previous
136   sample to play.
137
138 - Example 3
139
140   An example of the combination of a non-live (file) and a live source (vsrc) 
141   connected to live sinks (vsink, sink). 
142
143    .--------------------------.
144    | pipeline                 |
145    | .------.      .-------.  |
146    | | file |      | sink  |  |
147    | |     src -> sink     |  |
148    | '------'      '-------'  |
149    | .------.      .-------.  |
150    | | vsrc |      | vsink |  |
151    | |     src -> sink     |  |
152    | '------'      '-------'  |
153    '--------------------------'
154
155   The state changes happen in the same way as example 1. Except sink will be
156   able to preroll (commit its state to PAUSED).
157
158   In this case sink will have no latency but vsink will. The total latency
159   should be that of vsink.
160
161   Note that because of the presence of a live source (vsrc), the pipeline can be
162   set to playing before sink is able to preroll. Without compensation for the
163   live source, this might lead to synchronisation problems because the latency
164   should be configured in the element before it can go to PLAYING.
165
166
167 - Example 4
168
169   An example of the combination of a non-live and a live source. The non-live
170   source is connected to a live sink and the live source to a non-live sink.
171
172    .--------------------------.
173    | pipeline                 |
174    | .------.      .-------.  |
175    | | file |      | sink  |  |
176    | |     src -> sink     |  |
177    | '------'      '-------'  |
178    | .------.      .-------.  |
179    | | vsrc |      | files |  |
180    | |     src -> sink     |  |
181    | '------'      '-------'  |
182    '--------------------------'
183
184   The state changes happen in the same way as example 3. Sink will be
185   able to preroll (commit its state to PAUSED). files will not be able to
186   preroll.
187
188   sink will have no latency since it is not connected to a live source. files
189   does not do synchronisation so it does not care about latency.
190
191   The total latency in the pipeline is 0. The vsrc captures in sync with the
192   playback in sink.
193
194   As in example 3, sink can only be set to PLAYING after it successfully
195   prerolled.
196
197
198 State Changes
199 ~~~~~~~~~~~~~
200
201 A Sink is never set to PLAYING before it is prerolled. In order to do this, the
202 pipeline (at the GstBin level) keeps track of all
203 elements that require preroll (the ones that return ASYNC from the state
204 change). These elements posted a ASYNC_START message without a matching
205 ASYNC_DONE message.
206
207 The pipeline will not change the state of the elements that are still doing an
208 ASYNC state change.
209
210 When an ASYNC element prerolls, it commits its state to PAUSED and posts an
211 ASYNC_DONE message. The pipeline notices this ASYNC_DONE message and matches it
212 with the ASYNC_START message it cached for the corresponding element. 
213
214 When all ASYNC_START messages are matched with an ASYNC_DONE message, the
215 pipeline proceeds with setting the elements to the final state again.
216
217 The base time of the element was already set by the pipeline when it changed the
218 NO_PREROLL element to PLAYING. This operation has to be performed in the
219 separate async state change thread (like the one currently used for going from
220 PAUSED->PLAYING in a non-live pipeline).
221
222
223 Query
224 ~~~~~
225
226 The pipeline latency is queried with the LATENCY query.
227
228  (out) "live", G_TYPE_BOOLEAN (default FALSE)
229         - if a live element is found upstream
230
231  (out) "min-latency", G_TYPE_UINT64 (default 0)
232         - the minimum latency in the pipeline
233
234  (out) "max-latency", G_TYPE_UINT64 (default 0)
235         - the maximum latency in the pipeline
236
237
238 Event
239 ~~~~~
240
241 The latency in the pipeline is configured with the LATENCY event, which contains
242 the following fields:
243
244       "latency", G_TYPE_UINT64
245         - the configured latency in the pipeline
246
247
248 Latency compensation
249 ~~~~~~~~~~~~~~~~~~~~
250
251 Latency calculation and compensation is performed before the pipeline proceeds to
252 the PLAYING state. 
253
254 When the pipeline collected all ASYNC_DONE messages it can calculate the global
255 latency as follows:
256
257   - perform a latency query on all sinks.
258   - latency = MAX (all min latencies) 
259   - if MIN (all max latencies) < latency we have an impossible situation and we
260     must generate an error indicating that this pipeline cannot be played. This
261     usually means that there is not enough buffering in some chain of the
262     pipeline. A queue can be added to those chains.
263
264 The sinks gather this information with a LATENCY query upstream. Intermediate
265 elements pass the query upstream and add the amount of latency they add to the
266 result.
267
268 ex1:
269   sink1: [20 - 20]
270   sink2: [33 - 40]
271
272   MAX (20, 33) = 33
273   MIN (20, 40) = 20 < 33 -> impossible
274
275 ex2:
276   sink1: [20 - 50]
277   sink2: [33 - 40]
278
279   MAX (20, 33) = 33
280   MIN (50, 40) = 40 >= 33 -> latency = 33
281
282 The latency is set on the pipeline by sending a LATENCY event to the sinks
283 in the pipeline. This event configures the total latency on the sinks. The
284 sink forwards this LATENCY event upstream so that intermediate elements can
285 configure themselves as well.
286
287 After this step, the pipeline continues setting the pending state on its
288 elements.
289
290 A sink adds the latency value, received in the LATENCY event, to
291 the times used for synchronizing against the clock. This will effectively
292 delay the rendering of the buffer with the required latency. Since this delay is
293 the same for all sinks, all sinks will render data relatively synchronised.
294
295
296 Flushing a playing pipeline
297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
298
299 We can implement resynchronisation after an uncontrolled FLUSH in (part of) a
300 pipeline in the same way. Indeed, when a flush is performed on
301 a PLAYING live element, a new base time must be distributed to this element.
302
303 A flush in a pipeline can happen in the following cases:
304
305  - flushing seek in the pipeline
306     - performed by the application on the pipeline
307     - performed by the application on an element
308  - flush preformed by an element
309     - after receiving a navigation event (DVD, ...)
310
311 When a playing sink is flushed by a FLUSH_START event, an ASYNC_START  message is
312 posted by the element. As part of the message, the fact that the element got
313 flushed is included. The element also goes to a pending PAUSED state and has to
314 be set to the PLAYING state again later.
315
316 The ASYNC_START message is kept by the parent bin. When the element prerolls,
317 it posts an ASYNC_DONE message. 
318
319 When all ASYNC_START messages are matched with an ASYNC_DONE message, the bin
320 will capture a new base_time from the clock and will bring all the sinks back to
321 PLAYING after setting the new base time on them. It's also possible
322 to perform additional latency calculations and adjustments before doing this. 
323
324
325 Dynamically adjusting latency
326 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
327
328 An element that want to change the latency in the pipeline can do this by
329 posting a LATENCY message on the bus. This message instructs the pipeline to:
330
331  - query the latency in the pipeline (which might now have changed) with a
332    LATENCY query.
333  - redistribute a new global latency to all elements with a LATENCY event.
334
335 A use case where the latency in a pipeline can change could be a network element
336 that observes an increased inter packet arrival jitter or excessive packet loss
337 and decides to increase its internal buffering (and thus the latency). The
338 element must post a LATENCY message and perform the additional latency
339 adjustments when it receives the LATENCY event from the downstream peer element.
340
341 In a similar way can the latency be decreased when network conditions are
342 improving again.
343
344 Latency adjustments will introduce glitches in playback in the sinks and must
345 only be performed in special conditions.