OSDN Git Service

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