OSDN Git Service

LinGui: remove target file size option
[handbrake-jp/handbrake-jp-git.git] / libhb / decmpeg2.c
1 /* $Id: decmpeg2.c,v 1.12 2005/03/03 16:30:42 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "hb.h"
8 #include "hbffmpeg.h"
9 #include "mpeg2dec/mpeg2.h"
10
11 /* Cadence tracking */
12 #ifndef PIC_FLAG_REPEAT_FIRST_FIELD
13 #define PIC_FLAG_REPEAT_FIRST_FIELD 256
14 #endif
15 #define TOP_FIRST PIC_FLAG_TOP_FIELD_FIRST
16 #define PROGRESSIVE PIC_FLAG_PROGRESSIVE_FRAME
17 #define COMPOSITE PIC_FLAG_COMPOSITE_DISPLAY
18 #define SKIP PIC_FLAG_SKIP
19 #define TAGS PIC_FLAG_TAGS
20 #define REPEAT_FIRST PIC_FLAG_REPEAT_FIRST_FIELD
21 #define COMPOSITE_MASK PIC_MASK_COMPOSITE_DISPLAY
22 #define TB 8
23 #define BT 16
24 #define BT_PROG 32
25 #define BTB_PROG 64
26 #define TB_PROG 128
27 #define TBT_PROG 256
28
29 #define NTAGS 8
30
31 /**********************************************************************
32  * hb_libmpeg2_t
33  *********************************************************************/
34 typedef struct hb_libmpeg2_s
35 {
36     mpeg2dec_t         * libmpeg2;
37     const mpeg2_info_t * info;
38     hb_job_t           * job;
39     hb_title_t         * title;
40     int                  width;
41     int                  height;
42     int                  rate;
43     double               aspect_ratio;
44     enum PixelFormat     pixfmt;
45     int                  got_iframe;        /* set when we get our first iframe */
46     int                  look_for_iframe;   /* need an iframe to add chap break */
47     int                  look_for_break;    /* need gop start to add chap break */
48     int                  cur_tag;           /* index of current tag */
49     uint32_t             nframes;           /* number of frames we've decoded */
50     int64_t              last_pts;
51     int64_t              first_pts;
52     int cadence[12];
53     int flag;
54     hb_list_t          * list_subtitle;
55     hb_buffer_t        * last_cc1_buf;
56     struct {
57         int64_t          start;             // start time of this frame
58         hb_buffer_t    * cc_buf;            // captions for this frame
59     } tags[NTAGS];
60 } hb_libmpeg2_t;
61
62 /**********************************************************************
63  * hb_libmpeg2_init
64  **********************************************************************
65  *
66  *********************************************************************/
67 static hb_libmpeg2_t * hb_libmpeg2_init()
68 {
69     hb_libmpeg2_t * m = calloc( sizeof( hb_libmpeg2_t ), 1 );
70
71     m->libmpeg2 = mpeg2_init();
72     m->info     = mpeg2_info( m->libmpeg2 );
73     m->last_pts = -1;
74     m->first_pts = -1;
75
76     int i;
77     for ( i = 0; i < NTAGS; ++i )
78     {
79         m->tags[i].start = -1;
80     }
81
82     return m;
83 }
84
85 // send cc_buf to the CC decoder(s)
86 static void cc_send_to_decoder( hb_libmpeg2_t *m, hb_buffer_t *cc_buf )
87 {
88     hb_subtitle_t *subtitle;
89
90     // if there's more than one decoder for the captions send a copy
91     // of the buffer to all but the last. Then send the buffer to
92     // the last one (usually there's just one decoder so the 'while' is skipped).
93     int i = 0, n = hb_list_count( m->list_subtitle );
94     while ( --n > 0 )
95     {
96         // make a copy of the buf then forward it to the decoder
97         hb_buffer_t *cpy = hb_buffer_init( cc_buf->size );
98         hb_buffer_copy_settings( cpy, cc_buf );
99         memcpy( cpy->data, cc_buf->data, cc_buf->size );
100
101         subtitle = hb_list_item( m->list_subtitle, i++ );
102         hb_fifo_push( subtitle->fifo_in, cpy );
103     }
104     subtitle = hb_list_item( m->list_subtitle, i );
105     hb_fifo_push( subtitle->fifo_in, cc_buf );
106 }
107
108 static void hb_mpeg2_cc( hb_libmpeg2_t *m, const uint8_t *cc_block )
109 {
110     uint8_t cc_hdr = *cc_block;
111     
112     if ( ( cc_hdr & 0x4 ) == 0 )
113         // not valid - ignore
114         return;
115
116     switch (cc_hdr & 3)
117     {
118         case 0:
119             // CC1 stream
120             if ( ( cc_block[1] & 0x7f ) == 0 && ( cc_block[2] & 0x7f ) == 0 )
121                 // just padding - ignore
122                 return;
123
124             if ( m->last_cc1_buf )
125             {
126                 // new data from the same time as last call - add to buffer
127                 int len = m->last_cc1_buf->size;
128                 hb_buffer_realloc( m->last_cc1_buf, len + 2 );
129                 memcpy( m->last_cc1_buf->data + len, cc_block+1, 2 );
130                 m->last_cc1_buf->size = len + 2;
131                 return;
132             }
133
134             // allocate a new buffer and copy the caption data into it.
135             // (we don't send it yet because we don't know what timestamp to use).
136             hb_buffer_t *cc_buf = hb_buffer_init( 2 );
137             if( !cc_buf )
138                 return;
139
140             memcpy( cc_buf->data, cc_block+1, 2 );
141             m->last_cc1_buf = cc_buf;
142             break;
143 #ifdef notyet
144         case 1:
145             // CC2 stream
146             //process608( cc_block+1, 2, &m->cc608 );
147             break;
148         case 2: //EIA-708
149             // DTVCC packet data
150             // Fall through
151         case 3: //EIA-708
152             {
153                 uint8_t temp[4];
154                 temp[0]=cc_valid;
155                 temp[1]=cc_type;
156                 temp[2]=cc_block[1];
157                 temp[3]=cc_block[2];
158                 do_708 ((const unsigned char *) temp, 4);
159             }
160             break;
161 #endif
162         default:
163             break;
164     } 
165
166
167 static inline int have_captions( const uint8_t *user_data, uint32_t len )
168 {
169     return len >= 6 && 
170            ( ( user_data[0] == 0x43 && user_data[1] == 0x43 ) ||
171              ( user_data[0] == 0x47 && user_data[1] == 0x41 &&
172                user_data[2] == 0x39 && user_data[3] == 0x34 &&
173                user_data[4] == 3 && (user_data[5] & 0x40) ) );
174 }
175
176 static void do_one_dvd_cc( hb_libmpeg2_t *m, const uint8_t *header, int field1 )
177 {
178     uint8_t data[3];
179
180     data[0] = ( header[0] == 0xff && 0 == field1 )? 0x04 : 0x05;
181     data[1] = header[1];
182     data[2] = header[2];
183     hb_mpeg2_cc( m, data );
184
185     data[0] = ( header[3] == 0xff && 1 == field1 )? 0x04 : 0x05;
186     data[1] = header[4];
187     data[2] = header[5];
188     hb_mpeg2_cc( m, data );
189 }
190
191 // extract all the captions in the current frame and send them downstream
192 // to the decoder.
193 //
194 // (this routine should only be called if there are captions in the current
195 // frame. I.e., only if a call to 'have_captions' returns true.)
196 static void extract_mpeg2_captions( hb_libmpeg2_t *m )
197 {
198     const uint8_t *user_data = m->info->user_data;
199     int dvd_captions = user_data[0] == 0x43;
200     int capcount, field1packet = 0;
201     const uint8_t *header = &user_data[4];
202     if ( !dvd_captions )
203     {
204         // ATSC encapsulated captions - header starts one byte later
205         // and has an extra unused byte following it.
206         capcount = header[1] & 0x1f;
207         header += 3;
208     }
209     else
210     {
211         // DVD captions
212         if ( ( header[0] & 0x80 ) == 0x00 ) 
213             field1packet=1; /* expect Field 1 second */
214         capcount=(header[0] & 0x1e) / 2;
215         header++;
216     }
217
218     int i;
219     for( i=0; i<capcount; i++ )
220     {
221         if ( !dvd_captions )
222         {
223             hb_mpeg2_cc( m, header );
224             header += 3;
225         }
226         else
227         {
228             do_one_dvd_cc( m, header, field1packet );
229             header += 6;
230         }
231     }
232     if ( dvd_captions )
233     {
234         // Deal with extra closed captions some DVDs have.
235         while( header[0]==0xfe || header[0]==0xff )
236         {
237             do_one_dvd_cc( m, header, field1packet );
238             header += 6;
239         }   
240     }   
241 }
242
243 static void next_tag( hb_libmpeg2_t *m, hb_buffer_t *buf_es )
244 {
245     m->cur_tag = ( m->cur_tag + 1 ) & (NTAGS-1);
246     if ( m->tags[m->cur_tag].start >= 0 || m->tags[m->cur_tag].cc_buf )
247     {
248         if ( m->tags[m->cur_tag].start < 0 ||
249              ( m->got_iframe && m->tags[m->cur_tag].start >= m->first_pts ) )
250             hb_log("mpeg2 tag botch: pts %"PRId64", tag pts %"PRId64" buf 0x%p",
251                    buf_es->start, m->tags[m->cur_tag].start, m->tags[m->cur_tag].cc_buf);
252         if ( m->tags[m->cur_tag].cc_buf )
253             hb_buffer_close( &m->tags[m->cur_tag].cc_buf );
254     }
255     m->tags[m->cur_tag].start = buf_es->start;
256     mpeg2_tag_picture( m->libmpeg2, m->cur_tag, 0 );
257 }
258
259 static hb_buffer_t *hb_copy_frame( hb_job_t *job, int width, int height,
260                                    enum PixelFormat pixfmt,
261                                    uint8_t* y, uint8_t *u, uint8_t *v )
262 {
263     int dst_w = width, dst_h = height;
264     if ( job )
265     {
266         dst_w = job->title->width;
267         dst_h = job->title->height;
268     }
269     int dst_wh = dst_w * dst_h;
270     hb_buffer_t *buf  = hb_video_buffer_init( dst_w, dst_h );
271     buf->start = -1;
272
273     if ( dst_w != width || dst_h != height || pixfmt == PIX_FMT_YUV422P )
274     {
275         // we're encoding and the frame dimensions don't match the title dimensions -
276         // rescale & matte Y, U, V into our output buf.
277         AVPicture in, out;
278         avpicture_alloc(&in,  pixfmt, width, height );
279         avpicture_alloc(&out, PIX_FMT_YUV420P, dst_w, dst_h );
280
281         int src_wh = width * height;
282         if ( pixfmt == PIX_FMT_YUV422P )
283         {
284             memcpy( in.data[0], y, src_wh );
285             memcpy( in.data[1], u, src_wh >> 1 );
286             memcpy( in.data[2], v, src_wh >> 1 );
287         }
288         else
289         {
290             memcpy( in.data[0], y, src_wh );
291             memcpy( in.data[1], u, src_wh >> 2 );
292             memcpy( in.data[2], v, src_wh >> 2 );
293         }
294         struct SwsContext *context = hb_sws_get_context( width, height, pixfmt,
295                                                      dst_w, dst_h, PIX_FMT_YUV420P,
296                                                      SWS_LANCZOS|SWS_ACCURATE_RND);
297         sws_scale( context, in.data, in.linesize, 0, height, out.data, out.linesize );
298         sws_freeContext( context );
299
300         uint8_t *data = buf->data;
301         memcpy( data, out.data[0], dst_wh );
302         data += dst_wh;
303         // U & V planes are 1/4 the size of Y plane.
304         dst_wh >>= 2;
305         memcpy( data, out.data[1], dst_wh );
306         data += dst_wh;
307         memcpy( data, out.data[2], dst_wh );
308
309         avpicture_free( &out );
310         avpicture_free( &in );
311     }
312     else
313     {
314         // we're scanning or the frame dimensions match the title's dimensions
315         // so we can do a straight copy.
316         uint8_t *data = buf->data;
317         memcpy( data, y, dst_wh );
318         data += dst_wh;
319         // U & V planes are 1/4 the size of Y plane.
320         dst_wh >>= 2;
321         memcpy( data, u, dst_wh );
322         data += dst_wh;
323         memcpy( data, v, dst_wh );
324     }
325     return buf;
326 }
327
328 /**********************************************************************
329  * hb_libmpeg2_decode
330  **********************************************************************
331  *
332  *********************************************************************/
333 static int hb_libmpeg2_decode( hb_libmpeg2_t * m, hb_buffer_t * buf_es,
334                                hb_list_t * list_raw )
335 {
336     mpeg2_state_t    state;
337     hb_buffer_t    * buf;
338
339     if ( buf_es->size )
340     {
341         /* Feed libmpeg2 */
342         if( buf_es->start >= 0 )
343         {
344             next_tag( m, buf_es );
345         }
346         mpeg2_buffer( m->libmpeg2, buf_es->data, buf_es->data + buf_es->size );
347     }
348
349     for( ;; )
350     {
351         state = mpeg2_parse( m->libmpeg2 );
352         if( state == STATE_BUFFER )
353         {
354             /* Require some more data */
355             break;
356         }
357
358         // if the user requested captions, process
359         // any captions found in the current frame.
360         if ( m->list_subtitle && m->last_pts >= 0 &&
361              have_captions( m->info->user_data, m->info->user_data_len ) )
362         {
363             extract_mpeg2_captions( m );
364             // if we don't have a tag for the captions, make one
365             if ( m->last_cc1_buf && m->tags[m->cur_tag].cc_buf != m->last_cc1_buf )
366             {
367                 if (m->tags[m->cur_tag].cc_buf)
368                 {
369                     hb_log("mpeg2 tag botch2: pts %"PRId64", tag pts %"PRId64" buf 0x%p",
370                            buf_es->start, m->tags[m->cur_tag].start, m->tags[m->cur_tag].cc_buf);
371                     hb_buffer_close( &m->tags[m->cur_tag].cc_buf );
372                 }
373                 // see if we already made a tag for the timestamp. If so we
374                 // can just use it, otherwise make a new tag.
375                 if (m->tags[m->cur_tag].start < 0)
376                 {
377                     next_tag( m, buf_es );
378                 }
379                 m->tags[m->cur_tag].cc_buf = m->last_cc1_buf;
380             }
381         }
382         if( state == STATE_SEQUENCE )
383         {
384             if( !( m->width && m->height && m->rate ) )
385             {
386                 m->width  = m->info->sequence->width;
387                 m->height = m->info->sequence->height;
388                 m->rate   = m->info->sequence->frame_period;
389                 if ( m->aspect_ratio <= 0 && m->height &&
390                      m->info->sequence->pixel_height )
391                 {
392                     /* mpeg2_parse doesn't store the aspect ratio. Instead
393                      * it keeps the pixel width & height that would cause
394                      * the storage width & height to come out in the correct
395                      * aspect ratio. Convert these back to aspect ratio.
396                      */
397                     double ar_numer = m->width * m->info->sequence->pixel_width;
398                     double ar_denom = m->height * m->info->sequence->pixel_height;
399                     m->aspect_ratio = ar_numer / ar_denom;
400                 }
401             }
402             if ( m->info->sequence->width >> 1 == m->info->sequence->chroma_width &&
403                  m->info->sequence->height >> 1 == m->info->sequence->chroma_height )
404             {
405                 m->pixfmt = PIX_FMT_YUV420P;
406             }
407             else
408             {
409                 m->pixfmt = PIX_FMT_YUV422P;
410             }
411         }
412         else if( state == STATE_GOP && m->look_for_break)
413         {
414             // we were looking for a gop to add a chapter break - we found it
415             // so now start looking for an iframe.
416             m->look_for_iframe = m->look_for_break;
417             m->look_for_break = 0;
418         }
419         else if( ( state == STATE_SLICE || state == STATE_END ) &&
420                  m->info->display_fbuf )
421         {
422             m->last_cc1_buf = NULL;
423
424             if( !m->got_iframe && ( m->info->display_picture->flags &
425                   PIC_MASK_CODING_TYPE ) == PIC_FLAG_CODING_TYPE_I )
426             {
427                 // we got an iframe so we can start decoding video now
428                 m->got_iframe = 1;
429             }
430
431             if( m->got_iframe )
432             {
433                 buf  = hb_copy_frame( m->job, m->info->sequence->width,
434                                       m->info->sequence->height,
435                                       m->pixfmt,
436                                       m->info->display_fbuf->buf[0],
437                                       m->info->display_fbuf->buf[1],
438                                       m->info->display_fbuf->buf[2] );
439                 buf->sequence = buf_es->sequence;
440
441                 hb_buffer_t *cc_buf = NULL;
442                 if( m->info->display_picture->flags & PIC_FLAG_TAGS )
443                 {
444                     int t = m->info->display_picture->tag;
445                     buf->start = m->tags[t].start;
446                     cc_buf = m->tags[t].cc_buf;
447                     m->tags[t].start = -1;
448                     m->tags[t].cc_buf = NULL;
449                 }
450                 if( buf->start < 0 && m->last_pts >= 0 )
451                 {
452                     /* For some reason nb_fields is sometimes 1 while it
453                        should be 2 */
454                     buf->start = m->last_pts +
455                         MAX( 2, m->info->display_picture->nb_fields ) *
456                         m->info->sequence->frame_period / 600;
457                 }
458                 if ( buf->start >= 0 )
459                 {
460                     m->last_pts = buf->start;
461                 }
462
463                 // if we were accumulating captions we now know the timestamp
464                 // so ship them to the decoder.
465                 if ( cc_buf )
466                 {
467                     cc_buf->start = m->last_pts;
468                     cc_send_to_decoder( m, cc_buf );
469                 }
470
471                 if( m->look_for_iframe && ( m->info->display_picture->flags &
472                       PIC_MASK_CODING_TYPE ) == PIC_FLAG_CODING_TYPE_I )
473                 {
474                     // we were waiting for an iframe to insert a chapter mark
475                     // and we have one.
476                     buf->new_chap = m->look_for_iframe;
477                     m->look_for_iframe = 0;
478                     const char *chap_name = "";
479                     if ( m->job && buf->new_chap > 0 &&
480                          hb_list_item( m->job->title->list_chapter,
481                                        buf->new_chap - 1 ) )
482                     {
483                         hb_chapter_t * c = hb_list_item( m->job->title->list_chapter,
484                                                          buf->new_chap - 1 );
485                         chap_name = c->title;
486                     }
487                     hb_log( "mpeg2: \"%s\" (%d) at frame %u time %"PRId64,
488                             chap_name, buf->new_chap, m->nframes, buf->start );
489                 }
490                 else if ( m->nframes == 0 )
491                 {
492                     // this is the first frame returned by the decoder
493                     m->first_pts = buf->start;
494                     if ( m->job && hb_list_item( m->job->title->list_chapter,
495                                                  m->job->chapter_start - 1 ) )
496                     {
497                         hb_chapter_t * c = hb_list_item( m->job->title->list_chapter,
498                                                          m->job->chapter_start - 1 );
499                         hb_log( "mpeg2: \"%s\" (%d) at frame %u time %"PRId64,
500                                 c->title, m->job->chapter_start, m->nframes, buf->start );
501                     }
502                 }
503                 ++m->nframes;
504
505                 m->flag = m->info->display_picture->flags;
506
507 /*  Uncomment this block to see frame-by-frame picture flags, as the video encodes.
508                hb_log("***** MPEG 2 Picture Info for PTS %"PRId64" *****", buf->start);
509                 if( m->flag & TOP_FIRST )
510                     hb_log("MPEG2 Flag: Top field first");
511                 if( m->flag & PROGRESSIVE )
512                     hb_log("MPEG2 Flag: Progressive");
513                 if( m->flag & COMPOSITE )
514                     hb_log("MPEG2 Flag: Composite");
515                 if( m->flag & SKIP )
516                     hb_log("MPEG2 Flag: Skip!");
517                 if( m->flag & TAGS )
518                     hb_log("MPEG2 Flag: TAGS");
519                 if(fm->lag & REPEAT_FIRST )
520                     hb_log("MPEG2 Flag: Repeat first field");
521                 if( m->flag & COMPOSITE_MASK )
522                     hb_log("MPEG2 Flag: Composite mask");
523                 hb_log("fields: %d", m->info->display_picture->nb_fields);
524 */
525                 /*  Rotate the cadence tracking. */
526                 int i = 0;
527                 for(i=11; i > 0; i--)
528                 {
529                     m->cadence[i] = m->cadence[i-1];
530                 }
531
532                 if ( !(m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) )
533                 {
534                     /* Not progressive, not top first...
535                        That means it's probably bottom
536                        first, 2 fields displayed.
537                     */
538                     //hb_log("MPEG2 Flag: Bottom field first, 2 fields displayed.");
539                     m->cadence[0] = BT;
540                 }
541                 else if ( !(m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) )
542                 {
543                     /* Not progressive, top is first,
544                        Two fields displayed.
545                     */
546                     //hb_log("MPEG2 Flag: Top field first, 2 fields displayed.");
547                     m->cadence[0] = TB;
548                 }
549                 else if ( (m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) && !( m->flag & REPEAT_FIRST )  )
550                 {
551                     /* Progressive, but noting else.
552                        That means Bottom first,
553                        2 fields displayed.
554                     */
555                     //hb_log("MPEG2 Flag: Progressive. Bottom field first, 2 fields displayed.");
556                     m->cadence[0] = BT_PROG;
557                 }
558                 else if ( (m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) && ( m->flag & REPEAT_FIRST )  )
559                 {
560                     /* Progressive, and repeat. .
561                        That means Bottom first,
562                        3 fields displayed.
563                     */
564                     //hb_log("MPEG2 Flag: Progressive repeat. Bottom field first, 3 fields displayed.");
565                     m->cadence[0] = BTB_PROG;
566                 }
567                 else if ( (m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) && !( m->flag & REPEAT_FIRST )  )
568                 {
569                     /* Progressive, top first.
570                        That means top first,
571                        2 fields displayed.
572                     */
573                     //hb_log("MPEG2 Flag: Progressive. Top field first, 2 fields displayed.");
574                     m->cadence[0] = TB_PROG;
575                 }
576                 else if ( (m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) && ( m->flag & REPEAT_FIRST )  )
577                 {
578                     /* Progressive, top, repeat.
579                        That means top first,
580                        3 fields displayed.
581                     */
582                     //hb_log("MPEG2 Flag: Progressive repeat. Top field first, 3 fields displayed.");
583                     m->cadence[0] = TBT_PROG;
584                 }
585
586                 if ( (m->cadence[2] <= TB) && (m->cadence[1] <= TB) && (m->cadence[0] > TB) && (m->cadence[11]) )
587                     hb_log("%fs: Video -> Film", (float)buf->start / 90000);
588                 if ( (m->cadence[2] > TB) && (m->cadence[1] <= TB) && (m->cadence[0] <= TB) && (m->cadence[11]) )
589                     hb_log("%fs: Film -> Video", (float)buf->start / 90000);
590
591                 /* Store picture flags for later use by filters */
592                 buf->flags = m->info->display_picture->flags;
593
594                 hb_list_add( list_raw, buf );
595             }
596         }
597         else if( state == STATE_INVALID )
598         {
599             mpeg2_reset( m->libmpeg2, 0 );
600         }
601
602         /*
603          * Add closed captions to the title if we are scanning (no job).
604          *
605          * Just because we don't add this doesn't mean that there aren't any when 
606          * we scan, just that noone said anything. So you should be able to add
607          * closed captions some other way (See decmpeg2Init() for alternative
608          * approach of assuming that there are always CC, which is probably
609          * safer - however I want to leave the autodetect in here for now to
610          * see how it goes).
611          */
612         if( !m->job && m->title &&
613             have_captions( m->info->user_data, m->info->user_data_len ) )
614         {
615             hb_subtitle_t *subtitle;
616             int i = 0;
617             
618             while ( ( subtitle = hb_list_item( m->title->list_subtitle, i++ ) ) )
619             {
620                 /*
621                  * Let's call them 608 subs for now even if they aren't,
622                  * since they are the only types we grok.
623                  */
624                 if( subtitle->source == CC608SUB ) 
625                 {
626                     break;
627                 }
628             }
629             
630             if( ! subtitle )
631             {
632                 subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
633                 subtitle->track = 0;
634                 subtitle->id = 0;
635                 subtitle->format = TEXTSUB;
636                 subtitle->source = CC608SUB;
637                 subtitle->config.dest = PASSTHRUSUB;
638                 subtitle->type = 5; 
639                 snprintf( subtitle->lang, sizeof( subtitle->lang ), "Closed Captions");
640                 /*
641                  * The language of the subtitles will be the same as the first audio
642                  * track, i.e. the same as the video.
643                  */
644                 hb_audio_t *audio = hb_list_item( m->title->list_audio, 0 );
645                 if( audio )
646                 {
647                     snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), 
648                               audio->config.lang.iso639_2);
649                 } else {
650                     snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "und");
651                 }
652                 hb_list_add( m->title->list_subtitle, subtitle );
653             }
654         }
655     }
656     return 1;
657 }
658
659 /**********************************************************************
660  * hb_libmpeg2_close
661  **********************************************************************
662  *
663  *********************************************************************/
664 static void hb_libmpeg2_close( hb_libmpeg2_t ** _m )
665 {
666     hb_libmpeg2_t * m = *_m;
667
668     mpeg2_close( m->libmpeg2 );
669
670     int i;
671     for ( i = 0; i < NTAGS; ++i )
672     {
673         if ( m->tags[i].cc_buf )
674         {
675             if ( m->tags[i].cc_buf == m->last_cc1_buf )
676                 m->last_cc1_buf = NULL;
677             hb_buffer_close( &m->tags[i].cc_buf );
678         }
679     }
680     if ( m->last_cc1_buf )
681     {
682         hb_buffer_close( &m->last_cc1_buf );
683     }
684
685     free( m );
686     *_m = NULL;
687 }
688
689 /**********************************************************************
690  * The decmpeg2 work object
691  **********************************************************************
692  *
693  *********************************************************************/
694 struct hb_work_private_s
695 {
696     hb_libmpeg2_t * libmpeg2;
697     hb_list_t     * list;
698 };
699
700 /**********************************************************************
701  * hb_work_decmpeg2_init
702  **********************************************************************
703  *
704  *********************************************************************/
705 static int decmpeg2Init( hb_work_object_t * w, hb_job_t * job )
706 {
707     hb_work_private_t * pv;
708
709     pv              = calloc( 1, sizeof( hb_work_private_t ) );
710     w->private_data = pv;
711
712     pv->libmpeg2 = hb_libmpeg2_init();
713     pv->list     = hb_list_init();
714
715     pv->libmpeg2->job = job;
716
717     if( job && job->title ) {
718         pv->libmpeg2->title = job->title;
719     }
720
721     /*
722      * If not scanning, then are we supposed to extract Closed Captions
723      * and send them to the decoder? 
724      */
725     if( job && hb_list_count( job->list_subtitle ) > 0 )
726     {
727         hb_subtitle_t *subtitle;
728         int i = 0;
729         
730         for( i = 0; i < hb_list_count( job->list_subtitle ); i++ )
731         while ( ( subtitle = hb_list_item( job->list_subtitle, i++ ) ) != NULL )
732         {
733             if( subtitle->source == CC608SUB ) 
734             {
735                 if ( ! pv->libmpeg2->list_subtitle )
736                 {
737                     pv->libmpeg2->list_subtitle = hb_list_init();
738                 }
739                 hb_list_add(pv->libmpeg2->list_subtitle, subtitle);
740             }
741         }
742     }
743
744     return 0;
745 }
746
747 /**********************************************************************
748  * Work
749  **********************************************************************
750  *
751  *********************************************************************/
752 static int decmpeg2Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
753                          hb_buffer_t ** buf_out )
754 {
755     hb_work_private_t * pv = w->private_data;
756     hb_buffer_t * buf, * last = NULL;
757     int status = HB_WORK_OK;
758
759     if( w->title && pv && pv->libmpeg2 && !pv->libmpeg2->title ) {
760         pv->libmpeg2->title = w->title;
761     }
762
763     // The reader found a chapter break. Remove it from the input 
764     // stream. If we're reading (as opposed to scanning) start looking
765     // for the next GOP start since that's where the chapter begins.
766     if( (*buf_in)->new_chap )
767     {
768         if ( pv->libmpeg2->job )
769         {
770             pv->libmpeg2->look_for_break = (*buf_in)->new_chap;
771         }
772         (*buf_in)->new_chap = 0;
773     }
774
775     hb_libmpeg2_decode( pv->libmpeg2, *buf_in, pv->list );
776
777     /* if we got an empty buffer signaling end-of-stream send it downstream */
778     if ( (*buf_in)->size == 0 )
779     {
780         hb_list_add( pv->list, *buf_in );
781         *buf_in = NULL;
782         status = HB_WORK_DONE;
783
784         /*
785          * Purge any pending caption buffer then let the Closed Captions decoder
786          * know that it is the end of the data.
787          */
788         if ( pv->libmpeg2->list_subtitle )
789         {
790             if ( pv->libmpeg2->last_cc1_buf )
791             {
792                 cc_send_to_decoder( pv->libmpeg2, pv->libmpeg2->last_cc1_buf );
793                 if ( pv->libmpeg2->tags[pv->libmpeg2->cur_tag].cc_buf == 
794                      pv->libmpeg2->last_cc1_buf )
795                 {
796                     pv->libmpeg2->tags[pv->libmpeg2->cur_tag].cc_buf = NULL;
797                 }
798                 pv->libmpeg2->last_cc1_buf = NULL;
799             }
800             cc_send_to_decoder( pv->libmpeg2, hb_buffer_init( 0 ) );
801         }
802     }
803
804     *buf_out = NULL;
805     while( ( buf = hb_list_item( pv->list, 0 ) ) )
806     {
807         hb_list_rem( pv->list, buf );
808         if( last )
809         {
810             last->next = buf;
811             last       = buf;
812         }
813         else
814         {
815             *buf_out = buf;
816             last     = buf;
817         }
818     }
819
820     return status;
821 }
822
823 /**********************************************************************
824  * Close
825  **********************************************************************
826  *
827  *********************************************************************/
828 static void decmpeg2Close( hb_work_object_t * w )
829 {
830     hb_work_private_t * pv = w->private_data;
831
832     // don't log during scan
833     if ( pv->libmpeg2->job )
834     {
835         hb_log( "mpeg2 done: %d frames", pv->libmpeg2->nframes );
836     }
837     hb_list_empty( &pv->list );
838     if ( pv->libmpeg2->list_subtitle )
839     {
840         hb_list_close( &pv->libmpeg2->list_subtitle );
841     }
842     hb_libmpeg2_close( &pv->libmpeg2 );
843     free( pv );
844 }
845
846 static int decmpeg2Info( hb_work_object_t *w, hb_work_info_t *info )
847 {
848     hb_work_private_t *pv = w->private_data;
849
850     memset( info, 0, sizeof(*info) );
851
852     if ( pv && pv->libmpeg2 && pv->libmpeg2->info && pv->libmpeg2->info->sequence )
853     {
854         hb_libmpeg2_t *m = pv->libmpeg2;
855
856         info->width = m->width;
857         info->height = m->height;
858         info->pixel_aspect_width = m->info->sequence->pixel_width;
859         info->pixel_aspect_height = m->info->sequence->pixel_height;
860         info->aspect = m->aspect_ratio;
861
862         // if the frame is progressive & NTSC DVD height report it as 23.976 FPS
863         // so that scan can autodetect NTSC film
864         info->rate = 27000000;
865         info->rate_base = ( m->info->display_fbuf && m->info->display_picture &&
866                             (m->info->display_picture->flags & PROGRESSIVE) &&
867                             (m->height == 480 ) ) ?  1126125 : m->rate;
868
869         info->bitrate = m->info->sequence->byte_rate * 8;
870         info->profile = m->info->sequence->profile_level_id >> 4;
871         info->level = m->info->sequence->profile_level_id & 0xf;
872         info->name = "mpeg2";
873         return 1;
874     }
875     return 0;
876 }
877
878 hb_work_object_t hb_decmpeg2 =
879 {
880     WORK_DECMPEG2,
881     "MPEG-2 decoder (libmpeg2)",
882     decmpeg2Init,
883     decmpeg2Work,
884     decmpeg2Close,
885     decmpeg2Info
886 };
887