]> git.sesse.net Git - vlc/blob - modules/packetizer/dirac.c
Used BLOCK_FLAG_PRIVATE_SHIFT for creating private masks.
[vlc] / modules / packetizer / dirac.c
1 /*****************************************************************************
2  * dirac.c
3  *****************************************************************************
4  * Copyright (C) 2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: David Flynn <davidf@rd.bbc.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /* Dirac packetizer, formed of three parts:
25  *  1) Bitstream synchroniser (dirac_DoSync)
26  *      - Given an arbitary sequence of bytes, extract whole Dirac Data Units
27  *      - Maps timestamps in supplied block_t's to the extracted Data Unit
28  *        A time stamp applies to the next Data Unit to commence at, or after
29  *        the first byte of the block_t with the timestamp.
30  *  2) Encapsulation Unit generation (dirac_BuildEncapsulationUnit)
31  *      - Takes multiple well formed Dirac Data Units and forms them into a
32  *        single encapsulation unit, suitable for muxing.
33  *      - Sorts out any time stamps so that they only apply to pictures.
34  *  3) Timestamp generator (dirac_TimeGenPush)
35  *      - Many streams will not be correctly timestamped, ie, DTS&PTS for
36  *        every encapsulation unit.  Timestamp generator syncs to avaliable
37  *        timestamps and produces DTS&PTS for each encapsulation unit.
38  *      - For 'Occasional' missing PTS|DTS:
39  *          Missing timestamp is generated using interpolation from last
40  *          known good values.
41  *      - for All PTS missing:
42  *          It is assumed that DTS values are fake, and are actually
43  *          in the sequence of the PTS values at the output of a decoder.
44  *          Fill in PTS by copying from DTS (accounting for reordering,
45  *          by simulating reorder buffer); adjust DTS to provide correct
46  *          value.  This is how demuxers like AVI work.
47  *      - for All DTS missing:
48  *          (Ie, PTS is present), reorder buffer is simulated to determine
49  *          PTS for each encapsulation unit.
50  *      - NB, doesn't handle all pts missing with real dts. (no way to
51  *        distinguish from the fake dts case.)
52  *
53  *  DIRAC_NON_DATED is used to show a block should not have a time stamp
54  *  associated (ie, don't interpolate a counter).  At the ouput, these
55  *  blocks get dated with the last used timestamp (or are merged with
56  *  another encapsulation unit).
57  */
58
59 /*****************************************************************************
60  * Preamble
61  *****************************************************************************/
62
63 #ifdef HAVE_CONFIG_H
64 # include "config.h"
65 #endif
66
67 #include <assert.h>
68 #include <vlc_common.h>
69 #include <vlc_plugin.h>
70 #include <vlc_codec.h>
71 #include <vlc_block.h>
72
73 #include "vlc_bits.h"
74 #include "vlc_block_helper.h"
75
76 #define SANITIZE_PREV_PARSE_OFFSET 1
77
78 /*****************************************************************************
79  * Module descriptor
80  *****************************************************************************/
81 static int  Open ( vlc_object_t * );
82 static void Close( vlc_object_t * );
83
84 vlc_module_begin()
85     set_category( CAT_SOUT )
86     set_subcategory( SUBCAT_SOUT_PACKETIZER )
87     set_description( N_("Dirac packetizer") )
88     set_capability( "packetizer", 50 )
89     set_callbacks( Open, Close )
90 vlc_module_end()
91
92 /*****************************************************************************
93  * Local prototypes
94  *****************************************************************************/
95 struct decoder_sys_t
96 {
97     /* sync state */
98     block_bytestream_t bytestream;
99     int i_state;
100     size_t i_offset;
101     uint32_t u_last_npo;
102     /* recovered timestamp from bytesteram for use
103      * by synchroniser: should only get reset by the
104      * synchronizer upon a discontinuity sentinel */
105     mtime_t i_sync_pts;
106     mtime_t i_sync_dts;
107
108     /* build encapsulation unit state */
109     block_t *p_eu; /*< Current encapsulation unit being built */
110     block_t **pp_eu_last;
111     uint32_t u_eu_last_npo; /* last next_parse_offset at input to encapsulation */
112     mtime_t i_eu_pts;
113     mtime_t i_eu_dts;
114
115     /* timestamp generator state */
116     date_t dts; /*< timegen decode clock, increments at picture rate */
117     bool b_dts; /*< timegen decode clock valid */
118
119     bool b_pts; /*< timegen presentation time valid */
120     mtime_t i_pts; /*< timegen presentation time of picture u_pts_picnum */
121     uint32_t u_pts_picnum; /*< picture number of timegen presentation time */
122
123     mtime_t i_pts_offset; /*< maximum time between pts and dts */
124
125     /* p_outqueue is the list of encapsulation units that have been
126      * fed to the timegenerator.  the timegenerator stamps them in
127      * the order it solves the time.  the main packetizer loop removes
128      * completed encapsulation units from the front */
129     block_t *p_outqueue;
130     block_t **pp_outqueue_last;
131     /* p_out_dts points to an element in p_outqueue.  It is used for VLC's
132      * fake pts hidden in DTS hack, as used by AVI */
133     block_t *p_out_dts;
134
135     uint32_t u_tg_last_picnum; /*< most recent picturenumber output from RoB */
136     bool b_tg_last_picnum; /*< u_tg_last_picnum valid */
137
138     struct dirac_reorder_buffer {
139         int u_size_max;
140         int u_size;
141         struct dirac_reorder_entry {
142             struct dirac_reorder_entry *p_next;
143             block_t *p_eu;
144             uint32_t u_picnum;
145         } p_entries[32], *p_head, *p_empty;
146     } reorder_buf; /*< reorder buffer, used by timegenerator */
147
148     /* packetizer state */
149     mtime_t i_pts_last_out; /*< last output [from packetizer] pts */
150     mtime_t i_dts_last_out; /*< last output [from packetizer] dts */
151
152     struct seq_hdr_t {
153         uint32_t u_width;
154         uint32_t u_height;
155         uint32_t u_fps_num;
156         uint32_t u_fps_den;
157         enum picture_coding_mode_t {
158             DIRAC_FRAME_CODING=0,
159             DIRAC_FIELD_CODING=1,
160         } u_picture_coding_mode;
161     } seq_hdr; /*< sequence header */
162     bool b_seen_seq_hdr; /* sequence header valid */
163     bool b_seen_eos; /* last data unit to be handled was an EOS */
164 };
165
166 typedef struct {
167     uint32_t u_next_offset;
168     uint32_t u_prev_offset;
169     int i_parse_code;
170 } parse_info_t;
171
172 typedef struct {
173     block_free_t pf_blk_release;
174     /*> next_parse_offset of the final data unit in associated block_t */
175     uint32_t u_last_next_offset;
176     /*> picture number is invalid if block has flags DIRAC_NON_DATED */
177     uint32_t u_picture_number;
178 } dirac_block_encap_t;
179
180 enum {
181     NOT_SYNCED=0,
182     TRY_SYNC,
183     SYNCED,
184     SYNCED_INCOMPLETEDU,
185 };
186
187 enum {
188     DIRAC_NON_DATED = (1 << BLOCK_FLAG_PRIVATE_SHIFT),
189     DIRAC_DISCARD   = (2 << BLOCK_FLAG_PRIVATE_SHIFT),
190 };
191
192 enum {
193     DIRAC_DU_IN_EU,
194     DIRAC_DU_ENDS_EU,
195 };
196
197 /***
198  * Block encapsulation functions.
199  * Things are greately simplified by associating some metadata
200  * with a block as it passes through the packetizer (saves having
201  * to determine it again)
202  *
203  * unfortunately p_block doesn't have a p_priv, so some fakage
204  * needs to happen:
205  *   - Create a dummy block that has some extra storage, set up
206  *     members to be identical to the actual block
207  *   - Store private data there and pointer to orig block
208  *   - modify block pointer to point to fake block
209  *
210  * NB, the add/new functions must not be used to blocks
211  * that are referenced in lists, etc., [in this code, this is ok]
212  * NB, don't call add on the same block multiple times (will leak)
213  *
214  * davidf has a patch that reverts this to use a p_priv in block_t.
215  */
216 typedef struct {
217     block_t fake;
218     block_t *p_orig;
219     void *p_priv;
220 } fake_block_t;
221
222 static dirac_block_encap_t *dirac_RemoveBlockEncap( block_t *p_block )
223 {
224     fake_block_t *p_fake = (fake_block_t *)p_block;
225     dirac_block_encap_t *dbe = p_fake->p_priv;
226     if( !dbe ) return NULL;
227     p_fake->p_priv = NULL;
228     dbe->pf_blk_release = NULL;
229     return dbe;
230 }
231
232 static void dirac_ReleaseBlockAndEncap( block_t *p_block )
233 {
234     fake_block_t *p_fake = (fake_block_t *)p_block;
235     free( dirac_RemoveBlockEncap( p_block ) );
236     p_fake->p_orig->pf_release( p_fake->p_orig );
237     free( p_fake );
238 }
239
240 static void dirac_AddBlockEncap( block_t **pp_block, dirac_block_encap_t *p_dbe )
241 {
242     fake_block_t *p_fake = calloc( 1, sizeof( *p_fake ) );
243     assert( p_fake ); /* must not fail, fixby: adding a p_priv to block_t */
244     p_fake->p_orig = *pp_block;
245     memcpy( &p_fake->fake, *pp_block, sizeof( block_t ) );
246     *pp_block = &p_fake->fake;
247
248     p_fake->p_priv = p_dbe;
249     p_dbe->pf_blk_release = p_fake->p_orig->pf_release;
250     p_fake->fake.pf_release = dirac_ReleaseBlockAndEncap;
251 }
252
253 static dirac_block_encap_t *dirac_NewBlockEncap( block_t **pp_block )
254 {
255     dirac_block_encap_t *dbe = calloc( 1, sizeof( *dbe ) );
256     if( dbe ) dirac_AddBlockEncap( pp_block, dbe );
257     return dbe;
258 }
259
260 static dirac_block_encap_t *dirac_GetBlockEncap( block_t *p_block )
261 {
262     return (dirac_block_encap_t*) ((fake_block_t *)p_block)->p_priv;
263 }
264
265 /***
266  * General utility funcions
267  */
268
269 /* decrement a date. opposite to date_Increment */
270 static mtime_t date_Decrement( date_t *p_date, uint32_t i_nb_samples )
271 {
272     mtime_t i_dividend = (mtime_t)i_nb_samples * 1000000 * p_date->i_divider_den;
273     p_date->date -= i_dividend / p_date->i_divider_num;
274     unsigned u_rem_adjust = i_dividend % p_date->i_divider_num;
275
276     if( p_date->i_remainder < u_rem_adjust )
277     {
278         /* This is Bresenham algorithm. */
279         assert( p_date->i_remainder > -p_date->i_divider_num);
280         p_date->date -= 1;
281         p_date->i_remainder += p_date->i_divider_num;
282     }
283
284     p_date->i_remainder -= u_rem_adjust;
285
286     return p_date->date;
287 }
288
289 /**
290  * given a chain of block_t, allocate and return an array containing
291  * pointers to all the blocks. (Acts as a replacement for the old p_prev
292  * member of block_t) */
293 static int block_ChainToArray( block_t *p_block, block_t ***ppp_array)
294 {
295     if( !ppp_array )
296         return 0;
297
298     int num_blocks;
299     block_ChainProperties( p_block, &num_blocks, NULL, NULL );
300
301     *ppp_array = malloc( sizeof( block_t* ) * num_blocks );
302     if( !ppp_array ) return 0;
303
304     for( int i = 0; i < num_blocks; i++ )
305     {
306         (*ppp_array)[i] = p_block;
307         p_block = p_block->p_next;
308     }
309
310     return num_blocks;
311 }
312
313 /**
314  * Destructively find and recover the earliest timestamp from start of
315  * bytestream, upto i_length.
316  */
317 static void dirac_RecoverTimestamps ( decoder_t *p_dec, size_t i_length )
318 {
319     decoder_sys_t *p_sys = p_dec->p_sys;
320     block_t *p_block = p_sys->bytestream.p_block;
321
322     /* Find the block with first non-flushed data */
323     size_t i_offset = p_sys->bytestream.i_offset;
324     for(; p_block != NULL; p_block = p_block->p_next )
325     {
326         if( i_offset < p_block->i_buffer )
327             break;
328         i_offset -= p_block->i_buffer;
329     }
330
331     i_offset += i_length;
332     for(; p_block != NULL; p_block = p_block->p_next )
333     {
334         if( p_sys->i_sync_pts <= VLC_TS_INVALID && p_sys->i_sync_dts <= VLC_TS_INVALID )
335         {
336             /* oldest timestamp wins */
337             p_sys->i_sync_pts = p_block->i_pts;
338             p_sys->i_sync_dts = p_block->i_dts;
339         }
340         /* clear timestamps -- more than one data unit can come from a block */
341         p_block->i_flags = 0;
342         p_block->i_pts = p_block->i_dts = VLC_TS_INVALID;
343         if( i_offset < p_block->i_buffer )
344             break;
345         i_offset -= p_block->i_buffer;
346     }
347 }
348
349 /* backdate the list [p_block .. p_block->p_next where p_next == p_last] */
350 static void dirac_BackdateDTS( block_t *p_block, block_t *p_last, date_t *p_dts )
351 {
352     /* Transverse p_last backwards.  (no p_prev anymore) */
353     block_t **pp_array = NULL;
354     int n = block_ChainToArray( p_block, &pp_array );
355     while( n ) if( pp_array[--n] == p_last ) break;
356     /* want to start at p_last->p_prev */
357     while( n-- )
358     {
359         if( pp_array[n]->i_flags & DIRAC_NON_DATED )
360             continue;
361         if( pp_array[n]->i_dts <= VLC_TS_INVALID )
362             pp_array[n]->i_dts = date_Decrement( p_dts, 1 );
363     }
364     free( pp_array );
365 }
366
367 /* backdate the list [p_block .. p_block->p_next where p_next == p_last] */
368 static void dirac_BackdatePTS( block_t *p_block, block_t *p_last, date_t *p_pts, uint32_t u_pts_picnum )
369 {
370     /* Transverse p_last backwards.  (no p_prev anymore) */
371     block_t **pp_array = NULL;
372     int n = block_ChainToArray( p_block, &pp_array );
373     while( n ) if( pp_array[--n] == p_last ) break;
374     /* want to start at p_last->p_prev */
375     while( n-- )
376     {
377         if( pp_array[n]->i_flags & DIRAC_NON_DATED )
378             continue;
379         if( pp_array[n]->i_dts > VLC_TS_INVALID )
380             continue;
381         dirac_block_encap_t *dbe = dirac_GetBlockEncap( pp_array[n] );
382         int32_t u_pic_num = dbe ? dbe->u_picture_number : 0;
383         int32_t i_dist = u_pic_num - u_pts_picnum;
384         date_t pts = *p_pts;
385         if( i_dist >= 0 )
386             pp_array[n]->i_pts = date_Increment( &pts, i_dist );
387         else
388             pp_array[n]->i_pts = date_Decrement( &pts, -i_dist );
389     }
390     free( pp_array );
391 }
392
393 /***
394  * Dirac spec defined relations
395  */
396
397 static bool dirac_isEOS( uint8_t u_parse_code ) { return 0x10 == u_parse_code; }
398 static bool dirac_isSeqHdr( uint8_t u_parse_code ) { return 0 == u_parse_code; }
399 static bool dirac_isPicture( uint8_t u_parse_code ) { return 0x08 & u_parse_code; }
400 static int dirac_numRefs( uint8_t u_parse_code ) { return 0x3 & u_parse_code; }
401
402 static inline bool dirac_PictureNbeforeM( uint32_t u_n, uint32_t u_m )
403 {
404     /* specified as: u_n occurs before u_m if:
405      *   (u_m - u_n) mod (1<<32) < D */
406     return (uint32_t)(u_m - u_n) < (1u<<31);
407 }
408
409 /***
410  * Reorder buffer model
411  */
412
413 static void dirac_ReorderInit( struct dirac_reorder_buffer *p_rb )
414 {
415     memset( p_rb, 0, sizeof(*p_rb) );
416     p_rb->u_size_max = 2;
417     p_rb->p_empty = p_rb->p_entries;
418     p_rb->p_entries[31].p_next = NULL;
419
420     for( int i = 0; i < 31; i++ ) {
421         p_rb->p_entries[i].p_next = &p_rb->p_entries[i+1];
422     }
423 }
424
425 /* simulate the dirac picture reorder buffer */
426 static block_t *dirac_Reorder( decoder_t *p_dec, block_t *p_block_in, uint32_t u_picnum )
427 {
428     decoder_sys_t *p_sys = p_dec->p_sys;
429
430     if( !p_sys->reorder_buf.u_size_max )
431         /* reorder buffer disabled */
432         return p_block_in;
433
434     /* Modeling the reorder buffer:
435      * 1. If the reorder buffer is not full, insert picture for reordering.
436      *    No picture is output by the system this picture period
437      * 2. If the reorder buffer is full:
438      *    a. The picture decoded this period (u_picnum) bypasses the reorder
439      *       buffer if it has a lower picture number than any entry in the
440      *       reorder buffer. This picture is output by the system.
441      *    b. Otherwise, the lowest picture number in the reorder buffer is
442      *       removed from the buffer and output by the system.  The current
443      *       decoded picture (u_picnum) is inserted into the reorder buffer
444      */
445
446     block_t *p_block = NULL;
447     /* Determine if the picture needs to be inserted */
448     if( p_sys->reorder_buf.u_size == p_sys->reorder_buf.u_size_max )
449     {
450         /* (2) reorder buffer is full */
451         if( !p_sys->reorder_buf.u_size_max ||
452             dirac_PictureNbeforeM( u_picnum, p_sys->reorder_buf.p_head->u_picnum ) )
453         {
454             /* (2a) current picture is first in order */
455             return p_block_in;
456         }
457
458         /* (2b) extract the youngest picture in the buffer */
459         p_block = p_sys->reorder_buf.p_head->p_eu;
460
461         struct dirac_reorder_entry *p_tmp = p_sys->reorder_buf.p_head;
462         p_sys->reorder_buf.p_head = p_tmp->p_next;
463         p_tmp->p_next = p_sys->reorder_buf.p_empty;
464         p_sys->reorder_buf.p_empty = p_tmp;
465
466         p_sys->reorder_buf.u_size--;
467     }
468
469     /* (1) and (2b) both require u_picnum to be inserted */
470     struct dirac_reorder_entry *p_current = p_sys->reorder_buf.p_empty;
471     p_sys->reorder_buf.p_empty = p_current->p_next;
472     p_sys->reorder_buf.u_size++;
473
474     /* insertion sort to keep p_head always sorted, earliest first */
475     struct dirac_reorder_entry **pp_at = &p_sys->reorder_buf.p_head;
476     for( ; *pp_at; pp_at = &(*pp_at)->p_next )
477         if( dirac_PictureNbeforeM( u_picnum, (*pp_at)->u_picnum ) )
478             break;
479
480     p_current->u_picnum = u_picnum;
481     p_current->p_eu = p_block_in;
482     p_current->p_next = *pp_at;
483     *pp_at = p_current;
484
485     return p_block;
486 }
487
488 /***
489  * bytestream parsing and unmarshalling functions
490  */
491
492 static bool dirac_UnpackParseInfo( parse_info_t *p_pi, block_bytestream_t *p_bs,
493                                    size_t u_offset )
494 {
495     uint8_t p_d[13];
496     if( VLC_SUCCESS != block_PeekOffsetBytes( p_bs, u_offset, p_d, 13 ) )
497         return false;
498
499     if( p_d[0] != 'B' || p_d[1] != 'B' || p_d[2] != 'C' || p_d[3] != 'D' )
500         return false;
501
502     p_pi->i_parse_code = p_d[4];
503     p_pi->u_next_offset = p_d[5] << 24 | p_d[6] << 16 | p_d[7] << 8 | p_d[8];
504     p_pi->u_prev_offset = p_d[9] << 24 | p_d[10] << 16 | p_d[11] << 8 | p_d[12];
505     return true;
506 }
507
508 static uint32_t dirac_uint( bs_t *p_bs )
509 {
510   uint32_t count = 0, value = 0;
511   while( !bs_eof( p_bs ) && !bs_read( p_bs, 1 ) )
512   {
513     count++;
514     value <<= 1;
515     value |= bs_read( p_bs, 1 );
516   }
517
518   return (1 << count) - 1 + value;
519 }
520
521 static int dirac_bool( bs_t *p_bs )
522 {
523     return bs_read( p_bs, 1 );
524 }
525
526 /* read in useful bits from sequence header */
527 static bool dirac_UnpackSeqHdr( struct seq_hdr_t *p_sh, block_t *p_block )
528 {
529     bs_t bs;
530     bs_init( &bs, p_block->p_buffer, p_block->i_buffer );
531     bs_skip( &bs, 13*8 ); /* parse_info_header */
532     dirac_uint( &bs ); /* major_version */
533     dirac_uint( &bs ); /* minor_version */
534     dirac_uint( &bs ); /* profile */
535     dirac_uint( &bs ); /* level */
536
537     uint32_t u_video_format = dirac_uint( &bs ); /* index */
538     if( u_video_format > 20 )
539     {
540         /* dont know how to parse this header */
541         return false;
542     }
543
544     static const struct {
545         uint32_t u_w, u_h;
546     } dirac_size_tbl[] = {
547         {640,480}, {176,120}, {176,144}, {352,240}, {352,288}, {704,480},
548         {704,576}, {720,480}, {720,576}, {1280,720}, {1280,720}, {1920,1080},
549         {1920,1080}, {1920,1080}, {1920,1080}, {2048,1080}, {4096,2160},
550         {3840,2160}, {3840,2160}, {7680,4320}, {7680,4320},
551     };
552
553     p_sh->u_width = dirac_size_tbl[u_video_format].u_w;
554     p_sh->u_height = dirac_size_tbl[u_video_format].u_h;
555     if( dirac_bool( &bs ) )
556     {
557         p_sh->u_width = dirac_uint( &bs ); /* frame_width */
558         p_sh->u_height = dirac_uint( &bs ); /* frame_height */
559     }
560
561     if( dirac_bool( &bs ) )
562     {
563         dirac_uint( &bs ); /* chroma_format */
564     }
565
566     if( dirac_bool( &bs ) )
567     {
568         dirac_uint( &bs ); /* scan_format */
569     }
570
571     static const struct {
572         uint32_t u_n /* numerator */, u_d /* denominator */;
573     } dirac_frate_tbl[] = { /* table 10.3 */
574         {1, 1}, /* this value is not used */
575         {24000,1001}, {24,1}, {25,1}, {30000,1001}, {30,1},
576         {50,1}, {60000,1001}, {60,1}, {15000,1001}, {25,2},
577     };
578
579     const unsigned dirac_frate_tbl_size =
580         sizeof( dirac_frate_tbl ) / sizeof( *dirac_frate_tbl );
581
582     static const uint32_t dirac_vidfmt_frate[] = { /* table C.1 */
583         1, 9, 10, 9, 10, 9, 10, 4, 3, 7, 6, 4, 3, 7, 6, 2, 2, 7, 6, 7, 6,
584     };
585
586     p_sh->u_fps_num = dirac_frate_tbl[dirac_vidfmt_frate[u_video_format]].u_n;
587     p_sh->u_fps_den = dirac_frate_tbl[dirac_vidfmt_frate[u_video_format]].u_d;
588     if( dirac_bool( &bs ) )
589     {
590         uint32_t frame_rate_index = dirac_uint( &bs );
591         p_sh->u_fps_num = dirac_frate_tbl[frame_rate_index].u_n;
592         p_sh->u_fps_den = dirac_frate_tbl[frame_rate_index].u_d;
593         if( frame_rate_index >= dirac_frate_tbl_size )
594         {
595             /* invalid header */
596             return false;
597         }
598         if( frame_rate_index == 0 )
599         {
600             p_sh->u_fps_num = dirac_uint( &bs ); /* frame_rate_numerator */
601             p_sh->u_fps_den = dirac_uint( &bs ); /* frame_rate_denominator */
602         }
603     }
604
605     /* must have a valid framerate */
606     if( !p_sh->u_fps_num || !p_sh->u_fps_den )
607         return false;
608
609     if( dirac_bool( &bs ) )
610     {
611         uint32_t par_index = dirac_uint( &bs );
612         if( !par_index )
613         {
614             dirac_uint( &bs ); /* par_num */
615             dirac_uint( &bs ); /* par_den */
616         }
617     }
618
619     if( dirac_bool( &bs ) )
620     {
621         dirac_uint( &bs ); /* clean_width */
622         dirac_uint( &bs ); /* clean_height */
623         dirac_uint( &bs ); /* clean_left_offset */
624         dirac_uint( &bs ); /* clean_top_offset */
625     }
626
627     if( dirac_bool( &bs ) )
628     {
629         uint32_t signal_range_index = dirac_uint( &bs );
630         if( !signal_range_index )
631         {
632             dirac_uint( &bs ); /* luma_offset */
633             dirac_uint( &bs ); /* luma_excursion */
634             dirac_uint( &bs ); /* chroma_offset */
635             dirac_uint( &bs ); /* chroma_excursion */
636         }
637     }
638
639     if( dirac_bool( &bs ) )
640     {
641         uint32_t colour_spec_index = dirac_uint( &bs );
642         if( !colour_spec_index )
643         {
644             if( dirac_bool( &bs ) )
645             {
646                 dirac_uint( &bs ); /* colour_primaries_index */
647             }
648             if( dirac_bool( &bs ) )
649             {
650                 dirac_uint( &bs ); /* colour_matrix_index */
651             }
652             if( dirac_bool( &bs ) )
653             {
654                 dirac_uint( &bs ); /* transfer_function_index */
655             }
656         }
657     }
658
659     p_sh->u_picture_coding_mode = dirac_uint( &bs );
660
661     return true;
662 }
663
664 /***
665  * Data Unit marshalling functions
666  */
667
668 static block_t *dirac_EmitEOS( decoder_t *p_dec, uint32_t i_prev_parse_offset )
669 {
670     const uint8_t eos[] = { 'B','B','C','D',0x10,0,0,0,13,0,0,0,0 };
671     block_t *p_block = block_New( p_dec, 13 );
672     if( !p_block )
673         return NULL;
674     memcpy( p_block->p_buffer, eos, 13 );
675
676     SetDWBE( p_block->p_buffer + 9, i_prev_parse_offset );
677
678     p_block->i_flags = DIRAC_NON_DATED;
679
680     return p_block;
681
682     (void) p_dec;
683 }
684
685 /***
686  * Bytestream synchronizer
687  * maps [Bytes] -> DataUnit
688  */
689 static block_t *dirac_DoSync( decoder_t *p_dec )
690 {
691     decoder_sys_t *p_sys = p_dec->p_sys;
692     parse_info_t pu;
693
694     static const uint8_t p_parsecode[4] = {'B','B','C','D'};
695     do {
696         switch( p_sys->i_state )
697         {
698         case NOT_SYNCED: {
699             if( VLC_SUCCESS !=
700                 block_FindStartcodeFromOffset( &p_sys->bytestream, &p_sys->i_offset, p_parsecode, 4 ) )
701             {
702                 /* p_sys->i_offset will have been set to:
703                  *   end of bytestream - amount of prefix found
704                  * can resume search from this point when more data arrives */
705                 return NULL;
706             }
707             /* candidate parse_code_prefix has been found at p_sys->i_offset */
708             if( VLC_SUCCESS != block_PeekOffsetBytes( &p_sys->bytestream, p_sys->i_offset + 12, NULL, 0 ) )
709             {
710                 /* insufficient data has been accumulated to fully extract
711                  * a parse_info header. exit for now in the hope of more
712                  * data later to retry at exactly the same point */
713                 return NULL;
714             }
715             p_sys->i_state = TRY_SYNC;
716             break; /* candidate found, try to sync */
717         }
718         case SYNCED: /* -> TRY_SYNC | NOT_SYNCED */
719             /* sanity: can only reach this after having extracted a DU,
720              * which causes data to be consumed and local i_offset to be reset */
721             assert( p_sys->i_offset == 0 );
722             if( VLC_SUCCESS != block_PeekOffsetBytes( &p_sys->bytestream, 12, NULL, 0 ) )
723             {
724                 /* insufficient data has been accumulated to fully extract
725                  * a parse_info header, retry later */
726                 return NULL;
727             }
728             if( !dirac_UnpackParseInfo( &pu, &p_sys->bytestream, 0 )
729              || !pu.u_next_offset || (p_sys->u_last_npo != pu.u_prev_offset) )
730             {
731                 /* !a: not a valid parse info.
732                  * !pu.u_next_offset: don't know the length of the data unit
733                  *                    search for the next one that points back
734                  *                    to this one to determine length.
735                  * (p_sys->u_last_npo != pu.u_prev_offset): some desync
736                  */
737                 p_sys->i_state = NOT_SYNCED;
738                 break;
739             }
740             if( pu.u_next_offset > 1024*1024 )
741             {
742                 /* sanity check for erronious hugs next_parse_offsets
743                  * (eg, 2^32-1) that would cause a very long wait
744                  * and large space consumption: fall back to try sync */
745                 p_sys->i_state = TRY_SYNC;
746                 break;
747             }
748             /* check that the start of the next data unit is avaliable */
749             if( VLC_SUCCESS !=
750                 block_PeekOffsetBytes( &p_sys->bytestream, pu.u_next_offset + 12, NULL, 0 ) )
751             {
752                 return NULL; /* retry later */
753             }
754             /* attempt to syncronise backwards from pu.u_next_offset */
755             p_sys->i_offset = pu.u_next_offset;
756             /* fall through */
757         case TRY_SYNC: { /* -> SYNCED | NOT_SYNCED */
758             if( !p_sys->i_offset ) {
759                 goto sync_fail; /* if a is at start of bytestream, b can't be in buffer */
760             }
761
762             parse_info_t pu_a;
763             bool a = dirac_UnpackParseInfo( &pu_a, &p_sys->bytestream, p_sys->i_offset );
764             if( !a || (pu_a.u_prev_offset > p_sys->i_offset) ) {
765                 goto sync_fail; /* b lies beyond start of bytestream: can't sync */
766             }
767
768             if( !pu_a.u_prev_offset ) {
769                 if( p_sys->i_state == TRY_SYNC )
770                 {
771                     goto sync_fail; /* can't find different pu_b from pu_a */
772                 }
773                 /* state == SYNCED: already know where pu_b is.
774                  * pu_a has probably been inserted by something that doesn't
775                  * know what the last next_parse_offset was */
776                 pu_a.u_prev_offset = pu.u_next_offset;
777             }
778
779             parse_info_t *pu_b = &pu;
780             bool b = dirac_UnpackParseInfo( pu_b, &p_sys->bytestream, p_sys->i_offset - pu_a.u_prev_offset );
781             if( !b || (pu_b->u_next_offset && pu_a.u_prev_offset != pu_b->u_next_offset) ) {
782                 /* if pu_b->u_next_offset = 0, have to assume we've synced, ie,
783                  * just rely on finding a valid pu_b from pu_a. */
784                 goto sync_fail;
785             }
786             p_sys->u_last_npo = pu_b->u_next_offset;
787             if( !pu_b->u_next_offset ) pu_b->u_next_offset = pu_a.u_prev_offset;
788             /* offset was pointing at pu_a, rewind to point at pu_b */
789             p_sys->i_offset -= pu_a.u_prev_offset;
790             p_sys->i_state = SYNCED;
791             break;
792         }
793 sync_fail:
794             if( p_sys->i_state == SYNCED ) p_sys->i_offset = 0;
795             p_sys->i_offset++;
796             p_sys->i_state = NOT_SYNCED;
797             break; /* find somewhere else to try again */
798         default:;
799         }
800     } while( SYNCED != p_sys->i_state );
801
802     /*
803      * synced, attempt to extract a data unit
804      */
805
806     /* recover any timestamps from the data that is about to be flushed */
807     dirac_RecoverTimestamps( p_dec, p_sys->i_offset );
808
809     /* flush everything upto the start of the DU */
810     block_SkipBytes( &p_sys->bytestream, p_sys->i_offset );
811     block_BytestreamFlush( &p_sys->bytestream );
812     p_sys->i_offset = 0;
813
814     /* setup the data unit buffer */
815     block_t *p_block = block_New( p_dec, pu.u_next_offset );
816     if( !p_block )
817         return NULL;
818
819     p_block->i_pts = p_sys->i_sync_pts;
820     p_block->i_dts = p_sys->i_sync_dts;
821     p_sys->i_sync_pts = p_sys->i_sync_dts = VLC_TS_INVALID;
822
823     /* recover any new timestamps from the data that is about to be consumed */
824     dirac_RecoverTimestamps( p_dec, p_sys->i_offset );
825
826     block_GetBytes( &p_sys->bytestream, p_block->p_buffer, p_block->i_buffer );
827
828     /* save parse offset in private area for later use */
829     dirac_block_encap_t *dbe = dirac_NewBlockEncap( &p_block );
830     if( dbe ) dbe->u_last_next_offset = pu.u_next_offset;
831
832     return p_block;
833 }
834
835 /***
836  * Packet (Data Unit) inspection, learns parameters from sequence
837  * headers, sets up flags, drops unwanted data units, sets
838  * encapsulation unit termination policy
839  */
840 static int dirac_InspectDataUnit( decoder_t *p_dec, block_t **pp_block, block_t *p_eu )
841 {
842     decoder_sys_t *p_sys = p_dec->p_sys;
843     block_t *p_block = *pp_block;
844     uint8_t u_parse_code = p_block->p_buffer[4];
845
846     if( dirac_isEOS( u_parse_code ) )
847     {
848         if( p_sys->b_seen_eos )
849         {
850             /* remove duplicate EOS packets */
851             block_Release( p_block );
852             *pp_block = NULL;
853             return DIRAC_DU_IN_EU;
854         }
855         /* p_block is an EOS packet */
856         p_eu->i_flags |= BLOCK_FLAG_END_OF_SEQUENCE;
857         /* for the moment, let this end an encapsulation unit */
858         /* seeing an eos packet requires a flush of the packetizer
859          * this is detected by the caller of this function */
860         p_sys->b_seen_seq_hdr = false;
861         p_sys->b_seen_eos = true;
862         return DIRAC_DU_ENDS_EU;
863 #if 0
864         /* let anything down streem know too */
865         /*
866         Actually, this is a bad idea:
867          - It sets the discontinuity for every dirac EOS packet
868            which doesnt imply a time discontinuity.
869          - When the syncronizer detects a real discontinuity, it
870            should copy the flags through.
871         p_eu->i_flags |= BLOCK_FLAG_DISCONTINUITY;
872         */
873 #endif
874     }
875     p_sys->b_seen_eos = false;
876
877     if( dirac_isPicture( u_parse_code ) )
878     {
879         /* timestamps apply to pictures only */
880         p_eu->i_dts = p_sys->i_eu_dts;
881         p_eu->i_pts = p_sys->i_eu_pts;
882         p_sys->i_eu_dts = p_sys->i_eu_pts = VLC_TS_INVALID;
883
884         if( !p_sys->b_seen_seq_hdr )
885         {
886             /* can't timestamp in this case, discard later
887              * so that the timestamps aren't lost */
888             p_eu->i_flags |= DIRAC_DISCARD;
889         }
890         /* p_block is a picture -- it ends the 'encapsulation unit' */
891         if( dirac_numRefs( u_parse_code ) )
892         {
893             /* if this picture is not an I frame, ensure that the
894              * random access point flags are not set */
895             p_eu->i_flags &= ~BLOCK_FLAG_TYPE_I;
896         }
897         dirac_block_encap_t *dbe = dirac_GetBlockEncap( p_block );
898         if( dbe && p_block->i_buffer > 13+4 )
899         {
900             /* record the picture number to save the time gen functions
901              * from having to inspect the data for it */
902             dbe->u_picture_number = GetDWBE( p_block->p_buffer + 13 );
903         }
904         return DIRAC_DU_ENDS_EU;
905     }
906
907     if( dirac_isSeqHdr( u_parse_code ) )
908     {
909         if( !dirac_UnpackSeqHdr( &p_sys->seq_hdr, p_block ) )
910         {
911             /* couldn't parse the sequence header, just ignore it */
912             return DIRAC_DU_IN_EU;
913         }
914         p_sys->b_seen_seq_hdr = true;
915
916        /* a sequence header followed by an I frame is a random
917         * access point; assume that this is the case */
918         p_eu->i_flags |= BLOCK_FLAG_TYPE_I;
919
920         es_format_t *p_es = &p_dec->fmt_out;
921
922         p_es->video.i_width  = p_sys->seq_hdr.u_width;
923         p_es->video.i_height = p_sys->seq_hdr.u_height;
924
925         vlc_ureduce( &p_es->video.i_frame_rate, &p_es->video.i_frame_rate_base
926                    , p_sys->seq_hdr.u_fps_num, p_sys->seq_hdr.u_fps_den, 0 );
927
928         /* when field coding, dts needs to be incremented in terms of field periods */
929         int u_pics_per_sec = p_sys->seq_hdr.u_fps_num;
930         if (p_sys->seq_hdr.u_picture_coding_mode == DIRAC_FIELD_CODING)
931         {
932             u_pics_per_sec *= 2;
933         }
934         date_Change( &p_sys->dts, u_pics_per_sec, p_sys->seq_hdr.u_fps_den );
935
936         /* TODO: set p_sys->reorder_buf.u_size_max */
937         p_sys->i_pts_offset = p_sys->reorder_buf.u_size_max
938                             * 1000000
939                             * p_es->video.i_frame_rate_base / p_es->video.i_frame_rate + 1;
940
941         /* stash a copy of the seqhdr
942          *  - required for ogg muxing
943          *  - useful for error checking
944          *  - it isn't allowed to change until an eos */
945         if( p_es->p_extra )
946             free( p_es->p_extra );
947         p_es->p_extra = calloc( 1, p_block->i_buffer + 13 );
948         if( !p_es->p_extra )
949         {
950             p_es->i_extra = 0;
951             return DIRAC_DU_IN_EU;
952         }
953         p_es->i_extra = p_block->i_buffer;
954         memcpy( p_es->p_extra, p_block->p_buffer, p_block->i_buffer );
955         /* append EOS as per Ogg guidelines */
956         p_block = dirac_EmitEOS( p_dec, p_block->i_buffer );
957         if( p_block )
958         {
959             memcpy( (uint8_t*)p_es->p_extra + p_es->i_extra, p_block->p_buffer, 13 );
960             p_es->i_extra += 13;
961         }
962
963         return DIRAC_DU_IN_EU;
964     }
965
966     /* doesn't end an encapsulation unit */
967     return DIRAC_DU_IN_EU;
968 }
969
970 /***
971  * Encapsulation (packetization) suitable for all muxing standards
972  * maps [DataUnit] -> EncapsulationUnit
973  */
974 static block_t *dirac_BuildEncapsulationUnit( decoder_t *p_dec, block_t *p_block )
975 {
976     decoder_sys_t *p_sys = p_dec->p_sys;
977
978     assert(p_block->i_buffer >= 13 && 0x42424344 == GetDWBE( p_block->p_buffer ));
979
980     if( p_sys->i_eu_pts <= VLC_TS_INVALID && p_sys->i_eu_dts <= VLC_TS_INVALID )
981     {
982         /* earliest block with pts/dts gets to set the pts/dts for the dated
983          * encapsulation unit as a whole */
984         /* NB, the 'earliest block' criteria is aribtary */
985         if( p_block->i_pts > VLC_TS_INVALID || p_block->i_dts > VLC_TS_INVALID )
986         {
987             p_sys->i_eu_pts = p_block->i_pts;
988             p_sys->i_eu_dts = p_block->i_dts;
989         }
990     }
991
992     /* inpectdataunit also updates flags for the EU.
993      *  - if this is the first block in the EU, then it hasn't been added
994      *    to the chain yet (so, p_block will become the front of the chain
995      *  - otherwise, use the flags of the chain (first block) */
996     block_t *p_eu = p_sys->p_eu ? p_sys->p_eu : p_block;
997     int i_block = dirac_InspectDataUnit( p_dec, &p_block, p_eu);
998
999     if( !p_block )
1000     {
1001         /* block has been discarded during inspection */
1002         /* becareful, don't discard anything that is dated,
1003          * as this needs to go into the timegen loop.  set
1004          * the DIRAC_DISCARD block flag, and it'll be dropped
1005          * at output time */
1006         return NULL;
1007     }
1008
1009     block_ChainLastAppend( &p_sys->pp_eu_last, p_block );
1010
1011     dirac_block_encap_t *dbe = dirac_GetBlockEncap( p_block );
1012 #ifdef SANITIZE_PREV_PARSE_OFFSET
1013     /* fixup prev_parse_offset to point to the last data unit
1014      * to arrive */
1015     if( dbe )
1016     {
1017         SetDWBE( p_block->p_buffer + 9, p_sys->u_eu_last_npo );
1018         p_sys->u_eu_last_npo = dbe->u_last_next_offset;
1019     }
1020 #endif
1021
1022     if( i_block != DIRAC_DU_ENDS_EU )
1023     {
1024         /* encapsulation unit not ended */
1025         return NULL;
1026     }
1027
1028     /* gather up encapsulation unit, reassociating the final
1029      * private state with the gathered block */
1030     block_t *p_eu_last = (block_t*) p_sys->pp_eu_last - offsetof( block_t, p_next );
1031     dbe = dirac_RemoveBlockEncap( p_eu_last );
1032
1033     uint8_t u_parse_code = p_block->p_buffer[4];
1034
1035     /* gather up the encapsulation unit */
1036     p_block = block_ChainGather( p_sys->p_eu );
1037     assert( p_block ); /* block_ChainGather doesn't define when it frees chain */
1038
1039     p_block->i_flags |= DIRAC_NON_DATED;
1040     if( dbe )
1041     {
1042         dirac_AddBlockEncap( &p_block, dbe );
1043         if( dirac_isPicture( u_parse_code ) ) p_block->i_flags &= ~DIRAC_NON_DATED;
1044     }
1045     p_sys->p_eu = NULL;
1046     p_sys->pp_eu_last = &p_sys->p_eu;
1047     return p_block;
1048 }
1049
1050 /**
1051  * dirac_TimeGenPush:
1052  * @p_dec: vlc object
1053  * @p_block_in: whole encapsulation unit to generate timestamps for
1054  *
1055  * Returns:
1056  *  0: everything ok
1057  *  1: EOS occured, please flush and reset
1058  *  2: picture number discontinuity, please flush and reset
1059  */
1060 static int dirac_TimeGenPush( decoder_t *p_dec, block_t *p_block_in )
1061 {
1062     decoder_sys_t *p_sys = p_dec->p_sys;
1063     dirac_block_encap_t *dbe;
1064
1065     if( p_block_in->i_flags & BLOCK_FLAG_END_OF_SEQUENCE )
1066     {
1067         /* NB, this test occurs after the timegen push, so as to
1068          * push the block into the output queue */
1069         return 1;
1070     }
1071
1072     if( p_block_in->i_flags & DIRAC_NON_DATED )
1073     {
1074         /* no picture found, which means p_block_in is a non-dated EU,
1075          * do not try and put a date on it */
1076         return 0;
1077     }
1078
1079     dbe = dirac_GetBlockEncap( p_block_in );
1080     uint32_t u_picnum = dbe ? dbe->u_picture_number : 0;
1081     /*
1082      * Simple DTS regeneration:
1083      *  - DTS values linearly increase in stream order.
1084      *  - Every time a DTS occurs at the input, sync to it
1085      *    - If this is the first DTS seen, backdate all the previous ones that are undated
1086      *  - If a DTS is missing, guess that it increases by one picture period
1087      *  - If never seen DTS, don't do anything
1088      */
1089     /*
1090      * Simple PTS regeneration
1091      *  - PTS values do not linearly increase in stream order.
1092      *  - Every time a PTS occurs at the input, sync to it and record picture number
1093      *  - If a PTS is missing, guess that it differs by the product of picture
1094      *    period and difference between picture number of sync point and current picture
1095      *  - If this is the first PTS seen, backdate all previous ones that are undated
1096      *  - If never seen PTS, don't do anything
1097      */
1098     /*
1099      * Stage 1, sync to input timestamps, backdate timestamps for old
1100      * EUs that are in the outqueue with missing dates
1101      */
1102     if( p_block_in->i_dts > VLC_TS_INVALID )
1103     do {
1104         /* if timestamps exist, sync to them */
1105         if( p_sys->b_dts )
1106             break;
1107         /* first dts seen, backdate any packets in outqueue */
1108         p_sys->b_dts = true;
1109         date_t dts = p_sys->dts;
1110         dirac_BackdateDTS( p_sys->p_outqueue, p_block_in, &dts );
1111     } while( 0 );
1112
1113     if( p_block_in->i_pts > VLC_TS_INVALID )
1114     do {
1115         /* if timestamps exist, sync to them */
1116         p_sys->u_pts_picnum = u_picnum;
1117         p_sys->i_pts = p_block_in->i_pts;
1118         if( p_sys->b_pts )
1119             break;
1120         /* first pts seen, backdate any packets in outqueue */
1121         p_sys->b_pts = true;
1122         date_t pts = p_sys->dts;
1123         date_Set( &pts, p_sys->i_pts );
1124         dirac_BackdatePTS( p_sys->p_outqueue, p_block_in, &pts, p_sys->u_pts_picnum );
1125     } while( 0 );
1126
1127     /*
1128      * Stage 2, don't attempt to forwards interpolate timestamps for
1129      * blocks if the picture rates aren't known
1130      */
1131     if( !p_sys->b_seen_seq_hdr )
1132     {
1133         return 0;
1134     }
1135
1136     /*
1137      * Stage 3, for block_in, interpolate any missing timestamps
1138      */
1139     if( p_sys->b_dts && p_block_in->i_dts <= VLC_TS_INVALID )
1140     {
1141         /* dts has previously been seen, but not this time, interpolate */
1142         p_block_in->i_dts = date_Increment( &p_sys->dts, 1 );
1143     }
1144
1145     if( p_sys->b_pts && p_block_in->i_pts <= VLC_TS_INVALID )
1146     {
1147         /* pts has previously been seen, but not this time, interpolate */
1148         date_t pts = p_sys->dts;
1149         date_Set( &pts, p_sys->i_pts );
1150         int32_t i_dist = u_picnum - p_sys->u_pts_picnum;
1151         if( i_dist >= 0 )
1152             p_block_in->i_pts = date_Increment( &pts, i_dist );
1153         else
1154             p_block_in->i_pts = date_Decrement( &pts, -i_dist );
1155     }
1156
1157     /* If pts and dts have been seen, there is no need to simulate operation
1158      * of the decoder reorder buffer */
1159     /* If neither have been seen, there is little point in simulating */
1160     if( p_sys->b_dts == p_sys->b_pts )
1161         return 0;
1162
1163     if( !p_sys->p_out_dts )
1164         p_sys->p_out_dts = p_sys->p_outqueue;
1165
1166     /* model the reorder buffer */
1167     block_t *p_block = dirac_Reorder( p_dec, p_block_in, u_picnum );
1168     if( !p_block )
1169         return 0;
1170
1171     /* A future ehancement is to stop modeling the reorder buffer as soon as
1172      * the first packet is output -- interpolate the past and freewheel for
1173      * the future */
1174
1175     dbe = dirac_GetBlockEncap( p_block );
1176     u_picnum = dbe ? dbe->u_picture_number : 0;
1177     if( p_sys->b_tg_last_picnum )
1178     {
1179         if( dirac_PictureNbeforeM( u_picnum, p_sys->u_tg_last_picnum ) )
1180         {
1181             msg_Warn( p_dec, "stream jumped? %d < %d: resetting"
1182                     , u_picnum, p_sys->u_tg_last_picnum );
1183             /* pictures only emerge from the reorder buffer in sequence
1184              * if a stream suddenly jumped backwards without a signaling
1185              * a discontinuity, some pictures will get stuck in the RoB.
1186              * flush the RoB. */
1187             /* this could be a bit less indiscriminate */
1188             dbe = dirac_GetBlockEncap( p_sys->p_outqueue );
1189             uint32_t u_prev_parse_offset = dbe ? dbe->u_last_next_offset : 0;
1190             block_ChainRelease( p_sys->p_outqueue );
1191             p_sys->p_outqueue = dirac_EmitEOS( p_dec, u_prev_parse_offset );
1192             if( p_sys->p_outqueue )
1193                 p_sys->p_outqueue->i_flags = BLOCK_FLAG_DISCONTINUITY | DIRAC_NON_DATED;
1194             /* return 2, so as not to reset the b_dts flags -- needed if
1195              * using the rawdirac demuxer with broken stream */
1196             return 2;
1197         }
1198     }
1199     p_sys->b_tg_last_picnum = true;
1200     p_sys->u_tg_last_picnum = u_picnum;
1201
1202     if( !p_sys->b_pts )
1203     {
1204         /* some demuxers (eg, AVI) will provide a series of fake dts values,
1205          * which are actually inorder pts values (ie, what should be seen at
1206          * the output of a decoder.  A main reason for simulating the reorder
1207          * buffer is to turn the inorder fakedts into an out-of-order pts */
1208         p_block->i_pts = p_sys->p_out_dts->i_dts;
1209         p_sys->p_out_dts->i_dts = VLC_TS_INVALID;
1210     }
1211
1212     /* If pts was copied from dts, the dts needs to be corrected to account for reordering*/
1213     /* If dts has never been seen, the same needs to happen */
1214     p_sys->p_out_dts->i_dts = p_block->i_pts - p_sys->i_pts_offset;
1215
1216     /* move dts pointer */
1217     if( p_sys->p_out_dts )
1218         p_sys->p_out_dts = p_sys->p_out_dts->p_next;
1219
1220     return 0;
1221 }
1222
1223 /*****************************************************************************
1224  * Packetize: form dated encapsulation units from anything
1225  *****************************************************************************/
1226 static block_t *Packetize( decoder_t *p_dec, block_t **pp_block )
1227 {
1228     decoder_sys_t *p_sys = p_dec->p_sys;
1229     block_t *p_block = NULL;
1230     int i_flushing = 0;
1231
1232     if( pp_block && *pp_block )
1233     {
1234         p_block = *pp_block;
1235         *pp_block = NULL;
1236
1237         if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY )
1238         {
1239             /* pre-emptively insert an EOS at a discontinuity, protects
1240              * any decoders from any sudden changes */
1241             block_Release( p_block );
1242             p_block = dirac_EmitEOS( p_dec, 0 );
1243             if( p_block )
1244             {
1245                 p_block->p_next = dirac_EmitEOS( p_dec, 13 );
1246                 /* need two EOS to ensure it gets detected by syncro
1247                  * duplicates get discarded in forming encapsulation unit */
1248             }
1249         }
1250         else if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
1251         {
1252             /* silently discard corruption sentinels,
1253              * synchronizer will then discard affected data units.
1254              * do not produce an EOS data unit as this is very
1255              * disruptive to the stream (and may make a larger error). */
1256             block_Release( p_block );
1257             p_block = NULL;
1258         }
1259         if( p_block )
1260             block_BytestreamPush( &p_sys->bytestream, p_block );
1261     }
1262
1263     /* form as many encapsulation units as possible, give up
1264      * when the syncronizer runs out of input data */
1265     while( ( p_block = dirac_DoSync( p_dec ) ) )
1266     {
1267         p_block = dirac_BuildEncapsulationUnit( p_dec, p_block );
1268         if( !p_block )
1269             continue;
1270         /* add to tail of output queue (ie, not reordered) */
1271         block_ChainLastAppend( &p_sys->pp_outqueue_last, p_block );
1272         /* insert encapsulation unit into timestamp generator
1273          * which then calculates some timestamps if required */
1274         i_flushing = dirac_TimeGenPush( p_dec, p_block );
1275         if( i_flushing )
1276             break;
1277     }
1278
1279     block_t *p_output = NULL;
1280     block_t **pp_output = &p_output;
1281
1282     /* extract all the dated packets from the head of the ouput queue */
1283     /* explicitly nondated packets repeat the previous timestamps to
1284      * stop vlc discarding them */
1285     while( (p_block = p_sys->p_outqueue) )
1286     {
1287         if( p_block->i_flags & DIRAC_DISCARD )
1288         {
1289             p_sys->p_outqueue = p_block->p_next;
1290             p_block->p_next = NULL;
1291             block_Release( p_block );
1292             continue;
1293         }
1294
1295         if( i_flushing || p_block->i_flags & DIRAC_NON_DATED )
1296         {
1297             p_block->i_dts = p_sys->i_dts_last_out;
1298             p_block->i_pts = p_sys->i_pts_last_out;
1299         }
1300         else if( p_block->i_pts <= VLC_TS_INVALID ) break;
1301         else if( p_block->i_dts <= VLC_TS_INVALID ) break;
1302
1303         p_sys->i_dts_last_out = p_block->i_dts;
1304         p_sys->i_pts_last_out = p_block->i_pts;
1305
1306         p_sys->p_outqueue = p_block->p_next;
1307         p_block->p_next = NULL;
1308         /* clear any flags we set */
1309         p_block->i_flags &= ~BLOCK_FLAG_PRIVATE_MASK;
1310         block_ChainLastAppend( &pp_output, p_block );
1311
1312         mtime_t i_delay = p_block->i_pts - p_block->i_dts;
1313         if( i_delay < 0 )
1314             msg_Err( p_dec, "pts - dts is negative(%"PRId64"): incorrect RoB size", i_delay );
1315     }
1316
1317     if( i_flushing )
1318     {
1319         p_sys->i_eu_dts = p_sys->i_eu_pts = VLC_TS_INVALID;
1320
1321         /* reset timegen state (except synchronizer) */
1322         p_sys->b_seen_seq_hdr = false;
1323         if( i_flushing < 2 )
1324         {
1325             /* this state isn't safe to loose if there was
1326              * an unsignalled discontinuity */
1327             p_sys->b_pts = p_sys->b_dts = false;
1328         }
1329         p_sys->b_tg_last_picnum = false;
1330         dirac_ReorderInit( &p_sys->reorder_buf );
1331
1332         assert( p_sys->p_outqueue == NULL );
1333         p_sys->p_out_dts = NULL;
1334     }
1335
1336     /* perform sanity check:
1337      *  if there were a block at the front of outqueue that never
1338      *  satisfied the extraction criteria, but all blocks after did,
1339      *  the output queue would grow bounded by the stream length.
1340      * If there are 10 data units in the output queue, assume this
1341      * has happened and purge all blocks that fail extraction criteria */
1342     unsigned count = 0;
1343     for( p_block = p_sys->p_outqueue; p_block; p_block = p_block->p_next )
1344     {
1345         count++;
1346     }
1347     if( count > 9 )
1348     {
1349         p_block = p_sys->p_outqueue;
1350         while( p_block )
1351         {
1352             block_t *p_block_next = p_block->p_next;
1353             if( p_block->i_pts > VLC_TS_INVALID && p_block->i_dts > VLC_TS_INVALID )
1354                 break;
1355             block_Release( p_block );
1356             p_sys->p_outqueue = p_block = p_block_next;
1357         }
1358     }
1359
1360     if( !p_sys->p_outqueue )
1361     {
1362         p_sys->pp_outqueue_last = &p_sys->p_outqueue;
1363     }
1364     return p_output;
1365 }
1366
1367 /*****************************************************************************
1368  * Open: probe the packetizer and return score
1369  *****************************************************************************/
1370 static int Open( vlc_object_t *p_this )
1371 {
1372     decoder_t     *p_dec = (decoder_t*)p_this;
1373     decoder_sys_t *p_sys;
1374
1375     if( p_dec->fmt_in.i_codec !=  VLC_FOURCC( 'd','r','a','c' ) )
1376         return VLC_EGENERIC;
1377
1378     p_dec->pf_packetize = Packetize;
1379
1380     /* Create the output format */
1381     es_format_Copy( &p_dec->fmt_out, &p_dec->fmt_in );
1382     p_dec->p_sys = p_sys = calloc( 1, sizeof( decoder_sys_t ) );
1383
1384     if( !p_sys )
1385         return VLC_ENOMEM;
1386
1387     p_sys->i_eu_pts = p_sys->i_eu_dts = VLC_TS_INVALID;
1388     p_sys->i_sync_pts = p_sys->i_sync_dts = VLC_TS_INVALID;
1389     p_sys->i_dts_last_out = p_sys->i_pts_last_out = VLC_TS_INVALID;
1390
1391     p_sys->i_state = NOT_SYNCED;
1392     p_sys->bytestream = block_BytestreamInit();
1393
1394     p_sys->pp_outqueue_last = &p_sys->p_outqueue;
1395     p_sys->pp_eu_last = &p_sys->p_eu;
1396
1397     date_Init( &p_sys->dts, 1, 1 );
1398     dirac_ReorderInit( &p_sys->reorder_buf );
1399
1400     if( p_dec->fmt_in.i_extra > 0 )
1401     {
1402         /* handle hacky systems like ogg that dump some headers
1403          * in p_extra. and packetizers that expect it to be filled
1404          * in before real startup */
1405         block_t *p_init = block_New( p_dec, p_dec->fmt_in.i_extra );
1406         if( !p_init )
1407         {
1408             /* memory might be avaliable soon.  it isn't the end of
1409              * the world that fmt_in.i_extra isn't handled */
1410             return VLC_SUCCESS;
1411         }
1412         memcpy( p_init->p_buffer, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
1413         /* in theory p_extra should contain just a seqhdr&EOS.  if just a
1414          * seqhdr, ensure it is extracted by appending an EOS with
1415          * prev_offset = seqhdr length, ie i_extra.  If all were actually
1416          * ok, this won't do anything bad */
1417         if( ( p_init->p_next = dirac_EmitEOS( p_dec, p_dec->fmt_in.i_extra ) ) )
1418         {
1419             /* to ensure that one of these two EOS dataunits gets extracted,
1420              * send a second one */
1421             p_init->p_next->p_next = dirac_EmitEOS( p_dec, 13 );
1422         }
1423
1424         block_t *p_block;
1425         while( ( p_block = Packetize( p_dec, &p_init ) ) )
1426             block_Release( p_block );
1427     }
1428
1429     return VLC_SUCCESS;
1430 }
1431
1432 /*****************************************************************************
1433  * Close:
1434  *****************************************************************************/
1435 static void Close( vlc_object_t *p_this )
1436 {
1437     decoder_t     *p_dec = (decoder_t*)p_this;
1438     decoder_sys_t *p_sys = p_dec->p_sys;
1439
1440     block_BytestreamRelease( &p_sys->bytestream );
1441     if( p_sys->p_outqueue )
1442         block_ChainRelease( p_sys->p_outqueue );
1443     if( p_sys->p_eu )
1444         block_ChainRelease( p_sys->p_eu );
1445     free( p_sys );
1446 }
1447