OSDN Git Service

fix a problem with point-to-point (and live preview) when there are subtitles
[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 = sws_getContext( width, height, pixfmt,
295                                                      dst_w, dst_h, PIX_FMT_YUV420P,
296                                                      SWS_LANCZOS|SWS_ACCURATE_RND,
297                                                      NULL, NULL, NULL );
298         sws_scale( context, in.data, in.linesize, 0, height, out.data, out.linesize );
299         sws_freeContext( context );
300
301         uint8_t *data = buf->data;
302         memcpy( data, out.data[0], dst_wh );
303         data += dst_wh;
304         // U & V planes are 1/4 the size of Y plane.
305         dst_wh >>= 2;
306         memcpy( data, out.data[1], dst_wh );
307         data += dst_wh;
308         memcpy( data, out.data[2], dst_wh );
309
310         avpicture_free( &out );
311         avpicture_free( &in );
312     }
313     else
314     {
315         // we're scanning or the frame dimensions match the title's dimensions
316         // so we can do a straight copy.
317         uint8_t *data = buf->data;
318         memcpy( data, y, dst_wh );
319         data += dst_wh;
320         // U & V planes are 1/4 the size of Y plane.
321         dst_wh >>= 2;
322         memcpy( data, u, dst_wh );
323         data += dst_wh;
324         memcpy( data, v, dst_wh );
325     }
326     return buf;
327 }
328
329 /**********************************************************************
330  * hb_libmpeg2_decode
331  **********************************************************************
332  *
333  *********************************************************************/
334 static int hb_libmpeg2_decode( hb_libmpeg2_t * m, hb_buffer_t * buf_es,
335                                hb_list_t * list_raw )
336 {
337     mpeg2_state_t    state;
338     hb_buffer_t    * buf;
339
340     if ( buf_es->size )
341     {
342         /* Feed libmpeg2 */
343         if( buf_es->start >= 0 )
344         {
345             next_tag( m, buf_es );
346         }
347         mpeg2_buffer( m->libmpeg2, buf_es->data, buf_es->data + buf_es->size );
348     }
349
350     for( ;; )
351     {
352         state = mpeg2_parse( m->libmpeg2 );
353         if( state == STATE_BUFFER )
354         {
355             /* Require some more data */
356             break;
357         }
358
359         // if the user requested captions, process
360         // any captions found in the current frame.
361         if ( m->list_subtitle && m->last_pts >= 0 &&
362              have_captions( m->info->user_data, m->info->user_data_len ) )
363         {
364             extract_mpeg2_captions( m );
365             // if we don't have a tag for the captions, make one
366             if ( m->last_cc1_buf && m->tags[m->cur_tag].cc_buf != m->last_cc1_buf )
367             {
368                 if (m->tags[m->cur_tag].cc_buf)
369                 {
370                     hb_log("mpeg2 tag botch2: pts %"PRId64", tag pts %"PRId64" buf 0x%p",
371                            buf_es->start, m->tags[m->cur_tag].start, m->tags[m->cur_tag].cc_buf);
372                     hb_buffer_close( &m->tags[m->cur_tag].cc_buf );
373                 }
374                 // see if we already made a tag for the timestamp. If so we
375                 // can just use it, otherwise make a new tag.
376                 if (m->tags[m->cur_tag].start < 0)
377                 {
378                     next_tag( m, buf_es );
379                 }
380                 m->tags[m->cur_tag].cc_buf = m->last_cc1_buf;
381             }
382         }
383         if( state == STATE_SEQUENCE )
384         {
385             if( !( m->width && m->height && m->rate ) )
386             {
387                 m->width  = m->info->sequence->width;
388                 m->height = m->info->sequence->height;
389                 m->rate   = m->info->sequence->frame_period;
390                 if ( m->aspect_ratio <= 0 && m->height &&
391                      m->info->sequence->pixel_height )
392                 {
393                     /* mpeg2_parse doesn't store the aspect ratio. Instead
394                      * it keeps the pixel width & height that would cause
395                      * the storage width & height to come out in the correct
396                      * aspect ratio. Convert these back to aspect ratio.
397                      */
398                     double ar_numer = m->width * m->info->sequence->pixel_width;
399                     double ar_denom = m->height * m->info->sequence->pixel_height;
400                     m->aspect_ratio = ar_numer / ar_denom;
401                 }
402             }
403             if ( m->info->sequence->width >> 1 == m->info->sequence->chroma_width &&
404                  m->info->sequence->height >> 1 == m->info->sequence->chroma_height )
405             {
406                 m->pixfmt = PIX_FMT_YUV420P;
407             }
408             else
409             {
410                 m->pixfmt = PIX_FMT_YUV422P;
411             }
412         }
413         else if( state == STATE_GOP && m->look_for_break)
414         {
415             // we were looking for a gop to add a chapter break - we found it
416             // so now start looking for an iframe.
417             m->look_for_iframe = m->look_for_break;
418             m->look_for_break = 0;
419         }
420         else if( ( state == STATE_SLICE || state == STATE_END ) &&
421                  m->info->display_fbuf )
422         {
423             m->last_cc1_buf = NULL;
424
425             if( !m->got_iframe && ( m->info->display_picture->flags &
426                   PIC_MASK_CODING_TYPE ) == PIC_FLAG_CODING_TYPE_I )
427             {
428                 // we got an iframe so we can start decoding video now
429                 m->got_iframe = 1;
430             }
431
432             if( m->got_iframe )
433             {
434                 buf  = hb_copy_frame( m->job, m->info->sequence->width,
435                                       m->info->sequence->height,
436                                       m->pixfmt,
437                                       m->info->display_fbuf->buf[0],
438                                       m->info->display_fbuf->buf[1],
439                                       m->info->display_fbuf->buf[2] );
440                 buf->sequence = buf_es->sequence;
441
442                 hb_buffer_t *cc_buf = NULL;
443                 if( m->info->display_picture->flags & PIC_FLAG_TAGS )
444                 {
445                     int t = m->info->display_picture->tag;
446                     buf->start = m->tags[t].start;
447                     cc_buf = m->tags[t].cc_buf;
448                     m->tags[t].start = -1;
449                     m->tags[t].cc_buf = NULL;
450                 }
451                 if( buf->start < 0 && m->last_pts >= 0 )
452                 {
453                     /* For some reason nb_fields is sometimes 1 while it
454                        should be 2 */
455                     buf->start = m->last_pts +
456                         MAX( 2, m->info->display_picture->nb_fields ) *
457                         m->info->sequence->frame_period / 600;
458                 }
459                 if ( buf->start >= 0 )
460                 {
461                     m->last_pts = buf->start;
462                 }
463
464                 // if we were accumulating captions we now know the timestamp
465                 // so ship them to the decoder.
466                 if ( cc_buf )
467                 {
468                     cc_buf->start = m->last_pts;
469                     cc_send_to_decoder( m, cc_buf );
470                 }
471
472                 if( m->look_for_iframe && ( m->info->display_picture->flags &
473                       PIC_MASK_CODING_TYPE ) == PIC_FLAG_CODING_TYPE_I )
474                 {
475                     // we were waiting for an iframe to insert a chapter mark
476                     // and we have one.
477                     buf->new_chap = m->look_for_iframe;
478                     m->look_for_iframe = 0;
479                     const char *chap_name = "";
480                     if ( m->job && buf->new_chap > 0 &&
481                          hb_list_item( m->job->title->list_chapter,
482                                        buf->new_chap - 1 ) )
483                     {
484                         hb_chapter_t * c = hb_list_item( m->job->title->list_chapter,
485                                                          buf->new_chap - 1 );
486                         chap_name = c->title;
487                     }
488                     hb_log( "mpeg2: \"%s\" (%d) at frame %u time %"PRId64,
489                             chap_name, buf->new_chap, m->nframes, buf->start );
490                 }
491                 else if ( m->nframes == 0 )
492                 {
493                     // this is the first frame returned by the decoder
494                     m->first_pts = buf->start;
495                     if ( m->job && hb_list_item( m->job->title->list_chapter,
496                                                  m->job->chapter_start - 1 ) )
497                     {
498                         hb_chapter_t * c = hb_list_item( m->job->title->list_chapter,
499                                                          m->job->chapter_start - 1 );
500                         hb_log( "mpeg2: \"%s\" (%d) at frame %u time %"PRId64,
501                                 c->title, m->job->chapter_start, m->nframes, buf->start );
502                     }
503                 }
504                 ++m->nframes;
505
506                 m->flag = m->info->display_picture->flags;
507
508 /*  Uncomment this block to see frame-by-frame picture flags, as the video encodes.
509                hb_log("***** MPEG 2 Picture Info for PTS %"PRId64" *****", buf->start);
510                 if( m->flag & TOP_FIRST )
511                     hb_log("MPEG2 Flag: Top field first");
512                 if( m->flag & PROGRESSIVE )
513                     hb_log("MPEG2 Flag: Progressive");
514                 if( m->flag & COMPOSITE )
515                     hb_log("MPEG2 Flag: Composite");
516                 if( m->flag & SKIP )
517                     hb_log("MPEG2 Flag: Skip!");
518                 if( m->flag & TAGS )
519                     hb_log("MPEG2 Flag: TAGS");
520                 if(fm->lag & REPEAT_FIRST )
521                     hb_log("MPEG2 Flag: Repeat first field");
522                 if( m->flag & COMPOSITE_MASK )
523                     hb_log("MPEG2 Flag: Composite mask");
524                 hb_log("fields: %d", m->info->display_picture->nb_fields);
525 */
526                 /*  Rotate the cadence tracking. */
527                 int i = 0;
528                 for(i=11; i > 0; i--)
529                 {
530                     m->cadence[i] = m->cadence[i-1];
531                 }
532
533                 if ( !(m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) )
534                 {
535                     /* Not progressive, not top first...
536                        That means it's probably bottom
537                        first, 2 fields displayed.
538                     */
539                     //hb_log("MPEG2 Flag: Bottom field first, 2 fields displayed.");
540                     m->cadence[0] = BT;
541                 }
542                 else if ( !(m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) )
543                 {
544                     /* Not progressive, top is first,
545                        Two fields displayed.
546                     */
547                     //hb_log("MPEG2 Flag: Top field first, 2 fields displayed.");
548                     m->cadence[0] = TB;
549                 }
550                 else if ( (m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) && !( m->flag & REPEAT_FIRST )  )
551                 {
552                     /* Progressive, but noting else.
553                        That means Bottom first,
554                        2 fields displayed.
555                     */
556                     //hb_log("MPEG2 Flag: Progressive. Bottom field first, 2 fields displayed.");
557                     m->cadence[0] = BT_PROG;
558                 }
559                 else if ( (m->flag & PROGRESSIVE) && !(m->flag & TOP_FIRST) && ( m->flag & REPEAT_FIRST )  )
560                 {
561                     /* Progressive, and repeat. .
562                        That means Bottom first,
563                        3 fields displayed.
564                     */
565                     //hb_log("MPEG2 Flag: Progressive repeat. Bottom field first, 3 fields displayed.");
566                     m->cadence[0] = BTB_PROG;
567                 }
568                 else if ( (m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) && !( m->flag & REPEAT_FIRST )  )
569                 {
570                     /* Progressive, top first.
571                        That means top first,
572                        2 fields displayed.
573                     */
574                     //hb_log("MPEG2 Flag: Progressive. Top field first, 2 fields displayed.");
575                     m->cadence[0] = TB_PROG;
576                 }
577                 else if ( (m->flag & PROGRESSIVE) && (m->flag & TOP_FIRST) && ( m->flag & REPEAT_FIRST )  )
578                 {
579                     /* Progressive, top, repeat.
580                        That means top first,
581                        3 fields displayed.
582                     */
583                     //hb_log("MPEG2 Flag: Progressive repeat. Top field first, 3 fields displayed.");
584                     m->cadence[0] = TBT_PROG;
585                 }
586
587                 if ( (m->cadence[2] <= TB) && (m->cadence[1] <= TB) && (m->cadence[0] > TB) && (m->cadence[11]) )
588                     hb_log("%fs: Video -> Film", (float)buf->start / 90000);
589                 if ( (m->cadence[2] > TB) && (m->cadence[1] <= TB) && (m->cadence[0] <= TB) && (m->cadence[11]) )
590                     hb_log("%fs: Film -> Video", (float)buf->start / 90000);
591
592                 /* Store picture flags for later use by filters */
593                 buf->flags = m->info->display_picture->flags;
594
595                 hb_list_add( list_raw, buf );
596             }
597         }
598         else if( state == STATE_INVALID )
599         {
600             mpeg2_reset( m->libmpeg2, 0 );
601         }
602
603         /*
604          * Add closed captions to the title if we are scanning (no job).
605          *
606          * Just because we don't add this doesn't mean that there aren't any when 
607          * we scan, just that noone said anything. So you should be able to add
608          * closed captions some other way (See decmpeg2Init() for alternative
609          * approach of assuming that there are always CC, which is probably
610          * safer - however I want to leave the autodetect in here for now to
611          * see how it goes).
612          */
613         if( !m->job && m->title &&
614             have_captions( m->info->user_data, m->info->user_data_len ) )
615         {
616             hb_subtitle_t *subtitle;
617             int i = 0;
618             
619             while ( ( subtitle = hb_list_item( m->title->list_subtitle, i++ ) ) )
620             {
621                 /*
622                  * Let's call them 608 subs for now even if they aren't,
623                  * since they are the only types we grok.
624                  */
625                 if( subtitle->source == CC608SUB ) 
626                 {
627                     break;
628                 }
629             }
630             
631             if( ! subtitle )
632             {
633                 subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
634                 subtitle->track = 0;
635                 subtitle->id = 0;
636                 subtitle->format = TEXTSUB;
637                 subtitle->source = CC608SUB;
638                 subtitle->config.dest = PASSTHRUSUB;
639                 subtitle->type = 5; 
640                 snprintf( subtitle->lang, sizeof( subtitle->lang ), "Closed Captions");
641                 /*
642                  * The language of the subtitles will be the same as the first audio
643                  * track, i.e. the same as the video.
644                  */
645                 hb_audio_t *audio = hb_list_item( m->title->list_audio, 0 );
646                 if( audio )
647                 {
648                     snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), 
649                               audio->config.lang.iso639_2);
650                 } else {
651                     snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "und");
652                 }
653                 hb_list_add( m->title->list_subtitle, subtitle );
654             }
655         }
656     }
657     return 1;
658 }
659
660 /**********************************************************************
661  * hb_libmpeg2_close
662  **********************************************************************
663  *
664  *********************************************************************/
665 static void hb_libmpeg2_close( hb_libmpeg2_t ** _m )
666 {
667     hb_libmpeg2_t * m = *_m;
668
669     mpeg2_close( m->libmpeg2 );
670
671     int i;
672     for ( i = 0; i < NTAGS; ++i )
673     {
674         if ( m->tags[i].cc_buf )
675             hb_buffer_close( &m->tags[i].cc_buf );
676     }
677
678     free( m );
679     *_m = NULL;
680 }
681
682 /**********************************************************************
683  * The decmpeg2 work object
684  **********************************************************************
685  *
686  *********************************************************************/
687 struct hb_work_private_s
688 {
689     hb_libmpeg2_t * libmpeg2;
690     hb_list_t     * list;
691 };
692
693 /**********************************************************************
694  * hb_work_decmpeg2_init
695  **********************************************************************
696  *
697  *********************************************************************/
698 static int decmpeg2Init( hb_work_object_t * w, hb_job_t * job )
699 {
700     hb_work_private_t * pv;
701
702     pv              = calloc( 1, sizeof( hb_work_private_t ) );
703     w->private_data = pv;
704
705     pv->libmpeg2 = hb_libmpeg2_init();
706     pv->list     = hb_list_init();
707
708     pv->libmpeg2->job = job;
709
710     if( job && job->title ) {
711         pv->libmpeg2->title = job->title;
712     }
713
714     /*
715      * If not scanning, then are we supposed to extract Closed Captions
716      * and send them to the decoder? 
717      */
718     if( job && hb_list_count( job->list_subtitle ) > 0 )
719     {
720         hb_subtitle_t *subtitle;
721         int i = 0;
722         
723         for( i = 0; i < hb_list_count( job->list_subtitle ); i++ )
724         while ( ( subtitle = hb_list_item( job->list_subtitle, i++ ) ) != NULL )
725         {
726             if( subtitle->source == CC608SUB ) 
727             {
728                 if ( ! pv->libmpeg2->list_subtitle )
729                 {
730                     pv->libmpeg2->list_subtitle = hb_list_init();
731                 }
732                 hb_list_add(pv->libmpeg2->list_subtitle, subtitle);
733             }
734         }
735     }
736
737     return 0;
738 }
739
740 /**********************************************************************
741  * Work
742  **********************************************************************
743  *
744  *********************************************************************/
745 static int decmpeg2Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
746                          hb_buffer_t ** buf_out )
747 {
748     hb_work_private_t * pv = w->private_data;
749     hb_buffer_t * buf, * last = NULL;
750     int status = HB_WORK_OK;
751
752     if( w->title && pv && pv->libmpeg2 && !pv->libmpeg2->title ) {
753         pv->libmpeg2->title = w->title;
754     }
755
756     // The reader found a chapter break. Remove it from the input 
757     // stream. If we're reading (as opposed to scanning) start looking
758     // for the next GOP start since that's where the chapter begins.
759     if( (*buf_in)->new_chap )
760     {
761         if ( pv->libmpeg2->job )
762         {
763             pv->libmpeg2->look_for_break = (*buf_in)->new_chap;
764         }
765         (*buf_in)->new_chap = 0;
766     }
767
768     hb_libmpeg2_decode( pv->libmpeg2, *buf_in, pv->list );
769
770     /* if we got an empty buffer signaling end-of-stream send it downstream */
771     if ( (*buf_in)->size == 0 )
772     {
773         hb_list_add( pv->list, *buf_in );
774         *buf_in = NULL;
775         status = HB_WORK_DONE;
776
777         /*
778          * Purge any pending caption buffer then let the Closed Captions decoder
779          * know that it is the end of the data.
780          */
781         if ( pv->libmpeg2->list_subtitle )
782         {
783             if ( pv->libmpeg2->last_cc1_buf )
784             {
785                 cc_send_to_decoder( pv->libmpeg2, pv->libmpeg2->last_cc1_buf );
786                 pv->libmpeg2->last_cc1_buf = NULL;
787             }
788             cc_send_to_decoder( pv->libmpeg2, hb_buffer_init( 0 ) );
789         }
790     }
791
792     *buf_out = NULL;
793     while( ( buf = hb_list_item( pv->list, 0 ) ) )
794     {
795         hb_list_rem( pv->list, buf );
796         if( last )
797         {
798             last->next = buf;
799             last       = buf;
800         }
801         else
802         {
803             *buf_out = buf;
804             last     = buf;
805         }
806     }
807
808     return status;
809 }
810
811 /**********************************************************************
812  * Close
813  **********************************************************************
814  *
815  *********************************************************************/
816 static void decmpeg2Close( hb_work_object_t * w )
817 {
818     hb_work_private_t * pv = w->private_data;
819
820     // don't log during scan
821     if ( pv->libmpeg2->job )
822     {
823         hb_log( "mpeg2 done: %d frames", pv->libmpeg2->nframes );
824     }
825     if ( pv->libmpeg2->last_cc1_buf )
826     {
827         hb_buffer_close( &pv->libmpeg2->last_cc1_buf );
828     }
829     hb_list_close( &pv->list );
830     if ( pv->libmpeg2->list_subtitle )
831     {
832         hb_list_close( &pv->libmpeg2->list_subtitle );
833     }
834     hb_libmpeg2_close( &pv->libmpeg2 );
835     free( pv );
836 }
837
838 static int decmpeg2Info( hb_work_object_t *w, hb_work_info_t *info )
839 {
840     hb_work_private_t *pv = w->private_data;
841
842     memset( info, 0, sizeof(*info) );
843
844     if ( pv && pv->libmpeg2 && pv->libmpeg2->info && pv->libmpeg2->info->sequence )
845     {
846         hb_libmpeg2_t *m = pv->libmpeg2;
847
848         info->width = m->width;
849         info->height = m->height;
850         info->pixel_aspect_width = m->info->sequence->pixel_width;
851         info->pixel_aspect_height = m->info->sequence->pixel_height;
852         info->aspect = m->aspect_ratio;
853
854         // if the frame is progressive & NTSC DVD height report it as 23.976 FPS
855         // so that scan can autodetect NTSC film
856         info->rate = 27000000;
857         info->rate_base = ( m->info->display_fbuf && m->info->display_picture &&
858                             (m->info->display_picture->flags & PROGRESSIVE) &&
859                             (m->height == 480 ) ) ?  1126125 : m->rate;
860
861         info->bitrate = m->info->sequence->byte_rate * 8;
862         info->profile = m->info->sequence->profile_level_id >> 4;
863         info->level = m->info->sequence->profile_level_id & 0xf;
864         info->name = "mpeg2";
865         return 1;
866     }
867     return 0;
868 }
869
870 hb_work_object_t hb_decmpeg2 =
871 {
872     WORK_DECMPEG2,
873     "MPEG-2 decoder (libmpeg2)",
874     decmpeg2Init,
875     decmpeg2Work,
876     decmpeg2Close,
877     decmpeg2Info
878 };
879