]> git.sesse.net Git - vlc/blob - src/input/clock.c
No functionnal changes.
[vlc] / src / input / clock.c
1 /*****************************************************************************
2  * input_clock.c: Clock/System date convertions, stream management
3  *****************************************************************************
4  * Copyright (C) 1999-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Laurent Aimar < fenrir _AT_ videolan _DOT_ org >
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_input.h>
34 #include "input_clock.h"
35
36 /*
37  * DISCUSSION : SYNCHRONIZATION METHOD
38  *
39  * In some cases we can impose the pace of reading (when reading from a
40  * file or a pipe), and for the synchronization we simply sleep() until
41  * it is time to deliver the packet to the decoders. When reading from
42  * the network, we must be read at the same pace as the server writes,
43  * otherwise the kernel's buffer will trash packets. The risk is now to
44  * overflow the input buffers in case the server goes too fast, that is
45  * why we do these calculations :
46  *
47  * We compute a mean for the pcr because we want to eliminate the
48  * network jitter and keep the low frequency variations. The mean is
49  * in fact a low pass filter and the jitter is a high frequency signal
50  * that is why it is eliminated by the filter/average.
51  *
52  * The low frequency variations enable us to synchronize the client clock
53  * with the server clock because they represent the time variation between
54  * the 2 clocks. Those variations (ie the filtered pcr) are used to compute
55  * the presentation dates for the audio and video frames. With those dates
56  * we can decode (or trash) the MPEG2 stream at "exactly" the same rate
57  * as it is sent by the server and so we keep the synchronization between
58  * the server and the client.
59  *
60  * It is a very important matter if you want to avoid underflow or overflow
61  * in all the FIFOs, but it may be not enough.
62  */
63
64 /* p_input->p->i_cr_average : Maximum number of samples used to compute the
65  * dynamic average value.
66  * We use the following formula :
67  * new_average = (old_average * c_average + new_sample_value) / (c_average +1)
68  */
69
70 /*****************************************************************************
71  * Constants
72  *****************************************************************************/
73
74 /* Maximum gap allowed between two CRs. */
75 #define CR_MAX_GAP (INT64_C(2000000)*100/9)
76
77 /* Latency introduced on DVDs with CR == 0 on chapter change - this is from
78  * my dice --Meuuh */
79 #define CR_MEAN_PTS_GAP (300000)
80
81 /*****************************************************************************
82  * Structures
83  *****************************************************************************/
84
85 /**
86  * This structure holds long term average
87  */
88 typedef struct
89 {
90     mtime_t i_value;
91     int     i_residue;
92
93     int     i_count;
94     int     i_divider;
95 } average_t;
96 static void    AvgInit( average_t *, int i_divider );
97 static void    AvgClean( average_t * );
98
99 static void    AvgReset( average_t * );
100 static void    AvgUpdate( average_t *, mtime_t i_value );
101 static mtime_t AvgGet( average_t * );
102
103 /* */
104 typedef struct
105 {
106     mtime_t i_stream;
107     mtime_t i_system;
108 } clock_point_t;
109
110 static inline clock_point_t clock_point_Create( mtime_t i_stream, mtime_t i_system )
111 {
112     clock_point_t p = { .i_stream = i_stream, .i_system = i_system };
113     return p;
114 }
115
116 /* */
117 struct input_clock_t
118 {
119     /* Reference point */
120     bool          b_has_reference;
121     clock_point_t ref;
122
123     /* Last point
124      * It is used to detect unexpected stream discontinuities */
125     clock_point_t last;
126
127     /* Maximal timestamp returned by input_clock_GetTS (in system unit) */
128     mtime_t i_ts_max;
129
130     /* Clock drift */
131     mtime_t i_next_drift_update;
132     average_t drift;
133
134     /* Current modifiers */
135     bool    b_master;
136     int     i_rate;
137 };
138
139 static mtime_t ClockStreamToSystem( input_clock_t *, mtime_t i_stream );
140 static mtime_t ClockSystemToStream( input_clock_t *, mtime_t i_system );
141
142 /*****************************************************************************
143  * input_clock_New: create a new clock
144  *****************************************************************************/
145 input_clock_t *input_clock_New( bool b_master, int i_cr_average, int i_rate )
146 {
147     input_clock_t *cl = malloc( sizeof(*cl) );
148     if( !cl )
149         return NULL;
150
151     cl->b_has_reference = false;
152     cl->ref = clock_point_Create( 0, 0 );
153
154     cl->last = clock_point_Create( 0, 0 );
155
156     cl->i_ts_max = 0;
157
158     cl->i_next_drift_update = 0;
159     AvgInit( &cl->drift, i_cr_average );
160
161     cl->b_master = b_master;
162     cl->i_rate = i_rate;
163
164     return cl;
165 }
166
167 /*****************************************************************************
168  * input_clock_Delete: destroy a new clock
169  *****************************************************************************/
170 void input_clock_Delete( input_clock_t *cl )
171 {
172     AvgClean( &cl->drift );
173     free( cl );
174 }
175
176 /*****************************************************************************
177  * input_clock_Update: manages a clock reference
178  *
179  *  i_ck_stream: date in stream clock
180  *  i_ck_system: date in system clock
181  *****************************************************************************/
182 void input_clock_Update( input_clock_t *cl,
183                          vlc_object_t *p_log, bool b_can_pace_control,
184                          mtime_t i_ck_stream, mtime_t i_ck_system )
185 {
186     const bool b_synchronize = b_can_pace_control && cl->b_master;
187     bool b_reset_reference = false;
188
189     if( ( !cl->b_has_reference ) ||
190         ( i_ck_stream == 0 && cl->last.i_stream != 0 ) )
191     {
192         /* */
193         b_reset_reference= true;
194     }
195     else if( cl->last.i_stream != 0 &&
196              ( (cl->last.i_stream - i_ck_stream) > CR_MAX_GAP ||
197                (cl->last.i_stream - i_ck_stream) < -CR_MAX_GAP ) )
198     {
199         /* Stream discontinuity, for which we haven't received a
200          * warning from the stream control facilities (dd-edited
201          * stream ?). */
202         msg_Warn( p_log, "clock gap, unexpected stream discontinuity" );
203         cl->i_ts_max = 0;
204
205         /* */
206         msg_Warn( p_log, "feeding synchro with a new reference point trying to recover from clock gap" );
207         b_reset_reference= true;
208     }
209     if( b_reset_reference )
210     {
211         cl->i_next_drift_update = 0;
212         AvgReset( &cl->drift );
213
214         /* Feed synchro with a new reference point. */
215         cl->b_has_reference = true;
216         cl->ref = clock_point_Create( i_ck_stream,
217                                       __MAX( cl->i_ts_max + CR_MEAN_PTS_GAP, i_ck_system ) );
218     }
219
220     if( !b_synchronize && cl->i_next_drift_update < i_ck_system )
221     {
222         const mtime_t i_converted = ClockSystemToStream( cl, i_ck_system );
223
224         AvgUpdate( &cl->drift, i_converted - i_ck_stream );
225
226         cl->i_next_drift_update = i_ck_system + CLOCK_FREQ/5; /* FIXME why that */
227     }
228     cl->last = clock_point_Create( i_ck_stream, i_ck_system );
229 }
230
231 /*****************************************************************************
232  * input_clock_Reset:
233  *****************************************************************************/
234 void input_clock_Reset( input_clock_t *cl )
235 {
236     cl->b_has_reference = false;
237     cl->ref = clock_point_Create( 0, 0 );
238     cl->i_ts_max = 0;
239 }
240
241 /*****************************************************************************
242  * input_clock_GetTS: manages a PTS or DTS
243  *****************************************************************************/
244 mtime_t input_clock_GetTS( input_clock_t *cl,
245                            mtime_t i_pts_delay, mtime_t i_ts )
246 {
247     mtime_t i_converted_ts;
248
249     if( !cl->b_has_reference )
250         return 0;
251
252     /* */
253     i_converted_ts = ClockStreamToSystem( cl, i_ts + AvgGet( &cl->drift ) );
254     if( i_converted_ts > cl->i_ts_max )
255         cl->i_ts_max = i_converted_ts;
256
257     return i_converted_ts + i_pts_delay;
258 }
259
260 /*****************************************************************************
261  * input_clock_ChangeRate:
262  *****************************************************************************/
263 void input_clock_ChangeRate( input_clock_t *cl, int i_rate )
264 {
265     /* Move the reference point */
266     if( cl->b_has_reference )
267         cl->ref = cl->last;
268
269     cl->i_rate = i_rate;
270 }
271
272 /*****************************************************************************
273  * input_clock_ChangeMaster:
274  *****************************************************************************/
275 void input_clock_ChangeMaster( input_clock_t *cl, bool b_master )
276 {
277     cl->b_master = b_master;
278 }
279
280 /*****************************************************************************
281  * input_clock_GetWakeup
282  *****************************************************************************/
283 mtime_t input_clock_GetWakeup( input_clock_t *cl )
284 {
285     /* Not synchronized, we cannot wait */
286     if( !cl->b_has_reference )
287         return 0;
288
289     /* We must not wait if we are not the master clock */
290     if( !cl->b_master  )
291         return 0;
292
293     /* */
294     return ClockStreamToSystem( cl, cl->last.i_stream );
295 }
296
297 /*****************************************************************************
298  * ClockStreamToSystem: converts a movie clock to system date
299  *****************************************************************************/
300 static mtime_t ClockStreamToSystem( input_clock_t *cl, mtime_t i_stream )
301 {
302     if( !cl->b_has_reference )
303         return 0;
304
305     return ( i_stream - cl->ref.i_stream ) * cl->i_rate / INPUT_RATE_DEFAULT +
306            cl->ref.i_system;
307 }
308
309 /*****************************************************************************
310  * ClockSystemToStream: converts a system date to movie clock
311  *****************************************************************************
312  * Caution : a valid reference point is needed for this to operate.
313  *****************************************************************************/
314 static mtime_t ClockSystemToStream( input_clock_t *cl, mtime_t i_system )
315 {
316     assert( cl->b_has_reference );
317     return ( i_system - cl->ref.i_system ) * INPUT_RATE_DEFAULT / cl->i_rate +
318             cl->ref.i_stream;
319 }
320
321 /*****************************************************************************
322  * Long term average helpers
323  *****************************************************************************/
324 static void AvgInit( average_t *p_avg, int i_divider )
325 {
326     p_avg->i_divider = i_divider;
327     AvgReset( p_avg );
328 }
329 static void AvgClean( average_t *p_avg )
330 {
331     VLC_UNUSED(p_avg);
332 }
333 static void AvgReset( average_t *p_avg )
334 {
335     p_avg->i_value = 0;
336     p_avg->i_residue = 0;
337     p_avg->i_count = 0;
338 }
339 static void AvgUpdate( average_t *p_avg, mtime_t i_value )
340 {
341     const int i_f0 = __MIN( p_avg->i_divider - 1, p_avg->i_count );
342     const int i_f1 = p_avg->i_divider - i_f0;
343
344     const mtime_t i_tmp = i_f0 * p_avg->i_value + i_f1 * i_value + p_avg->i_residue;
345
346     p_avg->i_value   = i_tmp / p_avg->i_divider;
347     p_avg->i_residue = i_tmp % p_avg->i_divider;
348
349     p_avg->i_count++;
350 }
351 static mtime_t AvgGet( average_t *p_avg )
352 {
353     return p_avg->i_value;
354 }
355