summaryrefslogtreecommitdiffstats
path: root/libhb/decavcodec.c
blob: 87e829a751a3cc23addf5da50f254d1998e54f4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
/* $Id: decavcodec.c,v 1.6 2005/03/06 04:08:54 titer Exp $

   This file is part of the HandBrake source code.
   Homepage: <http://handbrake.fr/>.
   It may be used under the terms of the GNU General Public License. */

/* This module is Handbrake's interface to the ffmpeg decoder library
   (libavcodec & small parts of libavformat). It contains four Handbrake
   "work objects":

    decavcodec  connects HB to an ffmpeg audio decoder
    decavcodecv connects HB to an ffmpeg video decoder

        (Two different routines are needed because the ffmpeg library
        has different decoder calling conventions for audio & video.
        The audio decoder should have had its name changed to "decavcodeca"
        but I got lazy.) These work objects are self-contained & follow all
        of HB's conventions for a decoder module. They can be used like
        any other HB decoder (deca52, decmpeg2, etc.).

    decavcodecai "internal" (incestuous?) version of decavcodec
    decavcodecvi "internal" (incestuous?) version of decavcodecv

        These routine are functionally equivalent to the routines above but
        can only be used by the ffmpeg-based stream reader in libhb/stream.c.
        The reason they exist is because the ffmpeg library leaves some of
        the information needed by the decoder in the AVStream (the data
        structure used by the stream reader) and we need to retrieve it
        to successfully decode frames. But in HB the reader and decoder
        modules are in completely separate threads and nothing goes between
        them but hb_buffers containing frames to be decoded. I.e., there's
        no easy way for the ffmpeg stream reader to pass a pointer to its
        AVStream over to the ffmpeg video or audio decoder. So the *i work
        objects use a private back door to the stream reader to get access
        to the AVStream (routines hb_ffmpeg_avstream and hb_ffmpeg_context)
        and the codec_param passed to these work objects is the key to this
        back door (it's basically an index that allows the correct AVStream
        to be retrieved).

    The normal & *i objects share a lot of code (the basic frame decoding
    and bitstream info code is factored out into subroutines that can be
    called by either) but the top level routines of the *i objects
    (decavcodecviWork, decavcodecviInfo, etc.) are different because:
     1) they *have* to use the AVCodecContext that's contained in the
        reader's AVStream rather than just allocating & using their own,
     2) the Info routines have access to stuff kept in the AVStream in addition
        to stuff kept in the AVCodecContext. This shouldn't be necessary but
        crucial information like video frame rate that should be in the
        AVCodecContext is either missing or wrong in the version of ffmpeg
        we're currently using.

    A consequence of the above is that the non-i work objects *can't* use
    information from the AVStream because there isn't one - they get their
    data from either the dvd reader or the mpeg reader, not the ffmpeg stream
    reader. That means that they have to make up for deficiencies in the
    AVCodecContext info by using stuff kept in the HB "title" struct. It
    also means that ffmpeg codecs that randomly scatter state needed by
    the decoder across both the AVCodecContext & the AVStream (e.g., the
    VC1 decoder) can't easily be used by the HB mpeg stream reader.
 */

#include "hb.h"
#include "hbffmpeg.h"
#include "downmix.h"
#include "libavcodec/audioconvert.h"

static void flushDelayQueue( hb_work_private_t *pv );
static int  decavcodecInit( hb_work_object_t *, hb_job_t * );
static int  decavcodecWork( hb_work_object_t *, hb_buffer_t **, hb_buffer_t ** );
static void decavcodecClose( hb_work_object_t * );
static int decavcodecInfo( hb_work_object_t *, hb_work_info_t * );
static int decavcodecBSInfo( hb_work_object_t *, const hb_buffer_t *, hb_work_info_t * );

hb_work_object_t hb_decavcodec =
{
    WORK_DECAVCODEC,
    "Audio decoder (libavcodec)",
    decavcodecInit,
    decavcodecWork,
    decavcodecClose,
    decavcodecInfo,
    decavcodecBSInfo
};

#define HEAP_SIZE 8
typedef struct {
    // there are nheap items on the heap indexed 1..nheap (i.e., top of
    // heap is 1). The 0th slot is unused - a marker is put there to check
    // for overwrite errs.
    int64_t h[HEAP_SIZE+1];
    int     nheap;
} pts_heap_t;

struct hb_work_private_s
{
    hb_job_t        *job;
    AVCodecContext  *context;
    AVCodecParserContext *parser;
    hb_list_t       *list;
    hb_list_t       *ff_audio_list;
    double          duration;   // frame duration (for video)
    double          pts_next;   // next pts we expect to generate
    int64_t         chap_time;  // time of next chap mark (if new_chap != 0)
    int             new_chap;   // output chapter mark pending
    uint32_t        nframes;
    uint32_t        ndrops;
    uint32_t        decode_errors;
    int             brokenByMicrosoft; // video stream may contain packed b-frames
    hb_buffer_t*    delayq[HEAP_SIZE];
    int             queue_primed;
    pts_heap_t      pts_heap;
    void*           buffer;
    struct SwsContext *sws_context; // if we have to rescale or convert color space
    hb_downmix_t    *downmix;
    int cadence[12];
};

static void decodeAudio( hb_audio_t * audio, hb_work_private_t *pv, uint8_t *data, int size, int64_t pts );
static hb_buffer_t *link_buf_list( hb_work_private_t *pv );


static int64_t heap_pop( pts_heap_t *heap )
{
    int64_t result;

    if ( heap->nheap <= 0 )
    {
        return -1;
    }

    // return the top of the heap then put the bottom element on top,
    // decrease the heap size by one & rebalence the heap.
    result = heap->h[1];

    int64_t v = heap->h[heap->nheap--];
    int parent = 1;
    int child = parent << 1;
    while ( child <= heap->nheap )
    {
        // find the smallest of the two children of parent
        if (child < heap->nheap && heap->h[child] > heap->h[child+1] )
            ++child;

        if (v <= heap->h[child])
            // new item is smaller than either child so it's the new parent.
            break;

        // smallest child is smaller than new item so move it up then
        // check its children.
        int64_t hp = heap->h[child];
        heap->h[parent] = hp;
        parent = child;
        child = parent << 1;
    }
    heap->h[parent] = v;
    return result;
}

static void heap_push( pts_heap_t *heap, int64_t v )
{
    if ( heap->nheap < HEAP_SIZE )
    {
        ++heap->nheap;
    }

    // stick the new value on the bottom of the heap then bubble it
    // up to its correct spot.
	int child = heap->nheap;
	while (child > 1) {
		int parent = child >> 1;
		if (heap->h[parent] <= v)
			break;
		// move parent down
		int64_t hp = heap->h[parent];
		heap->h[child] = hp;
		child = parent;
	}
	heap->h[child] = v;
}


/***********************************************************************
 * hb_work_decavcodec_init
 ***********************************************************************
 *
 **********************************************************************/
static int decavcodecInit( hb_work_object_t * w, hb_job_t * job )
{
    AVCodec * codec;
    int i;

    hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
    w->private_data = pv;

    pv->job   = job;
    pv->list  = hb_list_init();

    int codec_id = w->codec_param;
    /*XXX*/
    if ( codec_id == 0 )
        codec_id = CODEC_ID_MP2;

    codec = avcodec_find_decoder( codec_id );
    pv->parser = av_parser_init( codec_id );

    pv->context = avcodec_alloc_context3(codec);
    hb_ff_set_sample_fmt( pv->context, codec );
    hb_avcodec_open( pv->context, codec, 0 );

    if ( w->audio != NULL )
    {
        if ( hb_need_downmix( w->audio->config.in.channel_layout, 
                              w->audio->config.out.mixdown) )
        {
            pv->downmix = hb_downmix_init(w->audio->config.in.channel_layout, 
                                          w->audio->config.out.mixdown);
            hb_downmix_set_chan_map( pv->downmix, &hb_smpte_chan_map, &hb_smpte_chan_map );
        }

        pv->ff_audio_list = hb_list_init();
        for ( i = 0; i < hb_list_count( w->audio->priv.ff_audio_list ); i++ )
        {
            hb_work_private_t * ff_pv = calloc( 1, sizeof( hb_work_private_t ) );
            hb_list_add( pv->ff_audio_list, ff_pv );

            hb_audio_t *audio = hb_list_item( w->audio->priv.ff_audio_list, i );

            ff_pv->list  = hb_list_init();
            ff_pv->job   = job;

            if ( hb_need_downmix( audio->config.in.channel_layout, 
                                  audio->config.out.mixdown) )
            {
                ff_pv->downmix = hb_downmix_init(audio->config.in.channel_layout, 
                                              audio->config.out.mixdown);
                hb_downmix_set_chan_map( ff_pv->downmix, &hb_smpte_chan_map, &hb_smpte_chan_map );
            }
        }
    }

    return 0;
}

/***********************************************************************
 * Close
 ***********************************************************************
 *
 **********************************************************************/
static void closePrivData( hb_work_private_t ** ppv )
{
    hb_work_private_t * pv = *ppv;

    if ( pv )
    {
        flushDelayQueue( pv );

        if ( pv->job && pv->context && pv->context->codec )
        {
            hb_log( "%s-decoder done: %u frames, %u decoder errors, %u drops",
                    pv->context->codec->name, pv->nframes, pv->decode_errors,
                    pv->ndrops );
        }
        if ( pv->sws_context )
        {
            sws_freeContext( pv->sws_context );
        }
        if ( pv->parser )
        {
            av_parser_close(pv->parser);
        }
        if ( pv->context && pv->context->codec )
        {
            hb_avcodec_close( pv->context );
        }
        if ( pv->list )
        {
            hb_list_empty( &pv->list );
        }
        if ( pv->buffer )
        {
            av_free( pv->buffer );
            pv->buffer = NULL;
        }
        if ( pv->downmix )
        {
            hb_downmix_close( &(pv->downmix) );
        }
        free( pv );
    }
    *ppv = NULL;
}

static void decavcodecClose( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;

    if ( pv )
    {
        if ( pv->ff_audio_list != NULL )
        {
            hb_work_private_t * ff_pv;
            while ( ( ff_pv = hb_list_item( pv->list, 0 ) ) != NULL )
            {
                hb_list_rem( pv->ff_audio_list, ff_pv );
                closePrivData( &ff_pv );
            }
        }
        closePrivData( &pv );
        w->private_data = NULL;
    }
}

static void writeAudioEof( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;
    hb_audio_t * audio = w->audio;
    int i;
    hb_buffer_t * buf;

    for ( i = 0; i < hb_list_count( audio->priv.ff_audio_list ); i++ )
    {
        hb_audio_t *ff_audio = hb_list_item( audio->priv.ff_audio_list, i );
        hb_work_private_t *ff_pv = hb_list_item( pv->ff_audio_list, i );
        if ( ff_pv )
        {
            buf = hb_buffer_init( 0 );
            if ( buf )
            {
                while ( !*w->done )
                {
                    if ( hb_fifo_full_wait( ff_audio->priv.fifo_raw ) )
                    {
                        hb_fifo_push( ff_audio->priv.fifo_raw, buf );
                        buf = NULL;
                        break;
                    }
                }
                if ( buf )
                {
                    // w->done == true while waiting
                    hb_buffer_close( &buf );
                    break;
                }
            }
        }
    }
}

static void writeAudioFifos( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;
    hb_audio_t * audio = w->audio;
    int i;
    hb_buffer_t * buf;

    for ( i = 0; i < hb_list_count( audio->priv.ff_audio_list ); i++ )
    {
        hb_audio_t *ff_audio = hb_list_item( audio->priv.ff_audio_list, i );
        hb_work_private_t *ff_pv = hb_list_item( pv->ff_audio_list, i );
        if ( ff_pv )
        {
            buf = link_buf_list( ff_pv );
            if ( buf )
            {
                while ( !*w->done )
                {
                    if ( hb_fifo_full_wait( ff_audio->priv.fifo_raw ) )
                    {
                        hb_fifo_push( ff_audio->priv.fifo_raw, buf );
                        buf = NULL;
                        break;
                    }
                }
                if ( buf )
                {
                    // w->done == true while waiting
                    hb_buffer_close( &buf );
                    break;
                }
            }
        }
    }
}

/***********************************************************************
 * Work
 ***********************************************************************
 *
 **********************************************************************/
static int decavcodecWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
                    hb_buffer_t ** buf_out )
{
    hb_work_private_t * pv = w->private_data;
    hb_buffer_t * in = *buf_in;

    if ( in->size <= 0 )
    {
        /* EOF on input stream - send it downstream & say that we're done */
        *buf_out = in;
        *buf_in = NULL;
        writeAudioEof( w );
        return HB_WORK_DONE;
    }

    *buf_out = NULL;

    if ( in->start < -1 && pv->pts_next <= 0 )
    {
        // discard buffers that start before video time 0
        return HB_WORK_OK;
    }

    int pos, len;
    for ( pos = 0; pos < in->size; pos += len )
    {
        uint8_t *parser_output_buffer;
        int parser_output_buffer_len;
        int64_t cur;

        cur = in->start;

        if ( pv->parser != NULL )
        {
            len = av_parser_parse2( pv->parser, pv->context,
                    &parser_output_buffer, &parser_output_buffer_len,
                    in->data + pos, in->size - pos, cur, cur, 0 );
            cur = pv->parser->pts;
            if ( cur == AV_NOPTS_VALUE )
                cur = -1;
        }
        else
        {
            parser_output_buffer = in->data;
            len = parser_output_buffer_len = in->size;
        }
        if (parser_output_buffer_len)
        {
            // set the duration on every frame since the stream format can
            // change (it shouldn't but there's no way to guarantee it).
            // duration is a scaling factor to go from #bytes in the decoded
            // frame to frame time (in 90KHz mpeg ticks). 'channels' converts
            // total samples to per-channel samples. 'sample_rate' converts
            // per-channel samples to seconds per sample and the 90000
            // is mpeg ticks per second.
            if ( pv->context->sample_rate && pv->context->channels )
            {
                pv->duration = 90000. /
                            (double)( pv->context->sample_rate * pv->context->channels );
            }
            decodeAudio( w->audio, pv, parser_output_buffer, parser_output_buffer_len, cur );
        }
    }
    writeAudioFifos( w );
    *buf_out = link_buf_list( pv );
    return HB_WORK_OK;
}

static int decavcodecInfo( hb_work_object_t *w, hb_work_info_t *info )
{
    hb_work_private_t *pv = w->private_data;

    memset( info, 0, sizeof(*info) );

    if ( pv && pv->context )
    {
        AVCodecContext *context = pv->context;
        info->bitrate = context->bit_rate;
        info->rate = context->time_base.num;
        info->rate_base = context->time_base.den;
        info->profile = context->profile;
        info->level = context->level;
        return 1;
    }
    return 0;
}

static int decavcodecBSInfo( hb_work_object_t *w, const hb_buffer_t *buf,
                             hb_work_info_t *info )
{
    hb_work_private_t *pv = w->private_data;
    int ret = 0;

    memset( info, 0, sizeof(*info) );

    if ( pv && pv->context )
    {
        return decavcodecInfo( w, info );
    }
    // XXX
    // We should parse the bitstream to find its parameters but for right
    // now we just return dummy values if there's a codec that will handle it.
    AVCodec *codec = avcodec_find_decoder( w->codec_param? w->codec_param :
                                                           CODEC_ID_MP2 );
    if ( ! codec )
    {
        // there's no ffmpeg codec for this audio type - give up
        return -1;
    }

    static char codec_name[64];
    info->name =  strncpy( codec_name, codec->name, sizeof(codec_name)-1 );

    AVCodecParserContext *parser = av_parser_init( codec->id );
    AVCodecContext *context = avcodec_alloc_context3(codec);
    hb_ff_set_sample_fmt( context, codec );
    hb_avcodec_open( context, codec, 0 );
    uint8_t *buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE );
    int out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    unsigned char *pbuffer;
    int pos, pbuffer_size;

    while ( buf && !ret )
    {
        pos = 0;
        while ( pos < buf->size )
        {
            int len;

            if (parser != NULL )
            {
                len = av_parser_parse2( parser, context, &pbuffer, 
                                        &pbuffer_size, buf->data + pos, 
                                        buf->size - pos, buf->start, 
                                        buf->start, 0 );
            }
            else
            {
                pbuffer = buf->data;
                len = pbuffer_size = buf->size;
            }
            pos += len;
            if ( pbuffer_size > 0 )
            {
                AVPacket avp;
                av_init_packet( &avp );
                avp.data = pbuffer;
                avp.size = pbuffer_size;

                len = avcodec_decode_audio3( context, (int16_t*)buffer, 
                                             &out_size, &avp );
                if ( len > 0 && context->sample_rate > 0 )
                {
                    info->bitrate = context->bit_rate;
                    info->rate = context->sample_rate;
                    info->rate_base = 1;
                    info->channel_layout = 
                        hb_ff_layout_xlat(context->channel_layout, 
                                          context->channels);
                    ret = 1;
                    break;
                }
            }
        }
        buf = buf->next;
    }

    info->channel_map = &hb_smpte_chan_map;

    av_free( buffer );
    if ( parser != NULL )
        av_parser_close( parser );
    hb_avcodec_close( context );
    return ret;
}

/* -------------------------------------------------------------
 * General purpose video decoder using libavcodec
 */

static uint8_t *copy_plane( uint8_t *dst, uint8_t* src, int dstride, int sstride,
                            int h )
{
    if ( dstride == sstride )
    {
        memcpy( dst, src, dstride * h );
        return dst + dstride * h;
    }
    int lbytes = dstride <= sstride? dstride : sstride;
    while ( --h >= 0 )
    {
        memcpy( dst, src, lbytes );
        src += sstride;
        dst += dstride;
    }
    return dst;
}

// copy one video frame into an HB buf. If the frame isn't in our color space
// or at least one of its dimensions is odd, use sws_scale to convert/rescale it.
// Otherwise just copy the bits.
static hb_buffer_t *copy_frame( hb_work_private_t *pv, AVFrame *frame )
{
    AVCodecContext *context = pv->context;
    int w, h;
    if ( ! pv->job )
    {
        // if the dimensions are odd, drop the lsb since h264 requires that
        // both width and height be even.
        w = ( context->width >> 1 ) << 1;
        h = ( context->height >> 1 ) << 1;
    }
    else
    {
        w =  pv->job->title->width;
        h =  pv->job->title->height;
    }
    hb_buffer_t *buf = hb_video_buffer_init( w, h );
    uint8_t *dst = buf->data;

    if ( context->pix_fmt != PIX_FMT_YUV420P || w != context->width ||
         h != context->height )
    {
        // have to convert to our internal color space and/or rescale
        AVPicture dstpic;
        avpicture_fill( &dstpic, dst, PIX_FMT_YUV420P, w, h );

        if ( ! pv->sws_context )
        {
            pv->sws_context = hb_sws_get_context( context->width, context->height, context->pix_fmt,
                                              w, h, PIX_FMT_YUV420P,
                                              SWS_LANCZOS|SWS_ACCURATE_RND);
        }
        sws_scale( pv->sws_context, (const uint8_t* const *)frame->data, frame->linesize, 0, h,
                   dstpic.data, dstpic.linesize );
    }
    else
    {
        dst = copy_plane( dst, frame->data[0], w, frame->linesize[0], h );
        w = (w + 1) >> 1; h = (h + 1) >> 1;
        dst = copy_plane( dst, frame->data[1], w, frame->linesize[1], h );
        dst = copy_plane( dst, frame->data[2], w, frame->linesize[2], h );
    }
    return buf;
}

static int get_frame_buf( AVCodecContext *context, AVFrame *frame )
{
    return avcodec_default_get_buffer( context, frame );
}

static int reget_frame_buf( AVCodecContext *context, AVFrame *frame )
{
    return avcodec_default_reget_buffer( context, frame );
}

static void log_chapter( hb_work_private_t *pv, int chap_num, int64_t pts )
{
    hb_chapter_t *c;

    if ( !pv->job )
        return;

    c = hb_list_item( pv->job->title->list_chapter, chap_num - 1 );
    if ( c && c->title )
    {
        hb_log( "%s: \"%s\" (%d) at frame %u time %"PRId64,
                pv->context->codec->name, c->title, chap_num, pv->nframes, pts );
    }
    else
    {
        hb_log( "%s: Chapter %d at frame %u time %"PRId64,
                pv->context->codec->name, chap_num, pv->nframes, pts );
    }
}

static void flushDelayQueue( hb_work_private_t *pv )
{
    hb_buffer_t *buf;
    int slot = pv->queue_primed ? pv->nframes & (HEAP_SIZE-1) : 0;

    // flush all the video packets left on our timestamp-reordering delay q
    while ( ( buf = pv->delayq[slot] ) != NULL )
    {
        buf->start = heap_pop( &pv->pts_heap );
        hb_list_add( pv->list, buf );
        pv->delayq[slot] = NULL;
        slot = ( slot + 1 ) & (HEAP_SIZE-1);
    }
}

#define TOP_FIRST PIC_FLAG_TOP_FIELD_FIRST
#define PROGRESSIVE PIC_FLAG_PROGRESSIVE_FRAME
#define REPEAT_FIRST PIC_FLAG_REPEAT_FIRST_FIELD
#define TB 8
#define BT 16
#define BT_PROG 32
#define BTB_PROG 64
#define TB_PROG 128
#define TBT_PROG 256

static void checkCadence( int * cadence, uint16_t flags, int64_t start )
{
    /*  Rotate the cadence tracking. */
    int i = 0;
    for(i=11; i > 0; i--)
    {
        cadence[i] = cadence[i-1];
    }

    if ( !(flags & PROGRESSIVE) && !(flags & TOP_FIRST) )
    {
        /* Not progressive, not top first...
           That means it's probably bottom
           first, 2 fields displayed.
        */
        //hb_log("MPEG2 Flag: Bottom field first, 2 fields displayed.");
        cadence[0] = BT;
    }
    else if ( !(flags & PROGRESSIVE) && (flags & TOP_FIRST) )
    {
        /* Not progressive, top is first,
           Two fields displayed.
        */
        //hb_log("MPEG2 Flag: Top field first, 2 fields displayed.");
        cadence[0] = TB;
    }
    else if ( (flags & PROGRESSIVE) && !(flags & TOP_FIRST) && !( flags & REPEAT_FIRST )  )
    {
        /* Progressive, but noting else.
           That means Bottom first,
           2 fields displayed.
        */
        //hb_log("MPEG2 Flag: Progressive. Bottom field first, 2 fields displayed.");
        cadence[0] = BT_PROG;
    }
    else if ( (flags & PROGRESSIVE) && !(flags & TOP_FIRST) && ( flags & REPEAT_FIRST )  )
    {
        /* Progressive, and repeat. .
           That means Bottom first,
           3 fields displayed.
        */
        //hb_log("MPEG2 Flag: Progressive repeat. Bottom field first, 3 fields displayed.");
        cadence[0] = BTB_PROG;
    }
    else if ( (flags & PROGRESSIVE) && (flags & TOP_FIRST) && !( flags & REPEAT_FIRST )  )
    {
        /* Progressive, top first.
           That means top first,
           2 fields displayed.
        */
        //hb_log("MPEG2 Flag: Progressive. Top field first, 2 fields displayed.");
        cadence[0] = TB_PROG;
    }
    else if ( (flags & PROGRESSIVE) && (flags & TOP_FIRST) && ( flags & REPEAT_FIRST )  )
    {
        /* Progressive, top, repeat.
           That means top first,
           3 fields displayed.
        */
        //hb_log("MPEG2 Flag: Progressive repeat. Top field first, 3 fields displayed.");
        cadence[0] = TBT_PROG;
    }

    if ( (cadence[2] <= TB) && (cadence[1] <= TB) && (cadence[0] > TB) && (cadence[11]) )
        hb_log("%fs: Video -> Film", (float)start / 90000);
    if ( (cadence[2] > TB) && (cadence[1] <= TB) && (cadence[0] <= TB) && (cadence[11]) )
        hb_log("%fs: Film -> Video", (float)start / 90000);
}

/*
 * Decodes a video frame from the specified raw packet data 
 *      ('data', 'size', 'sequence').
 * The output of this function is stored in 'pv->list', which contains a list
 * of zero or more decoded packets.
 * 
 * The returned packets are guaranteed to have their timestamps in the correct 
 * order, even if the original packets decoded by libavcodec have misordered 
 * timestamps, due to the use of 'packed B-frames'.
 * 
 * Internally the set of decoded packets may be buffered in 'pv->delayq'
 * until enough packets have been decoded so that the timestamps can be
 * correctly rewritten, if this is necessary.
 */
static int decodeFrame( hb_work_private_t *pv, uint8_t *data, int size, int sequence, int64_t pts, int64_t dts )
{
    int got_picture, oldlevel = 0;
    AVFrame frame;
    AVPacket avp;

    if ( global_verbosity_level <= 1 )
    {
        oldlevel = av_log_get_level();
        av_log_set_level( AV_LOG_QUIET );
    }

    av_init_packet( &avp );
    avp.data = data;
    avp.size = size;
    avp.pts = pts;
    avp.dts = dts;
    if ( avcodec_decode_video2( pv->context, &frame, &got_picture, &avp ) < 0 )
    {
        ++pv->decode_errors;     
    }
    if ( global_verbosity_level <= 1 )
    {
        av_log_set_level( oldlevel );
    }
    if( got_picture )
    {
        uint16_t flags = 0;

        // ffmpeg makes it hard to attach a pts to a frame. if the MPEG ES
        // packet had a pts we handed it to av_parser_parse (if the packet had
        // no pts we set it to AV_NOPTS_VALUE, but before the parse we can't 
        // distinguish between the start of a video frame with no pts & an 
        // intermediate packet of some frame which never has a pts). we hope 
        // that when parse returns the frame to us the pts we originally 
        // handed it will be in parser->pts. we put this pts into avp.pts so 
        // that when avcodec_decode_video finally gets around to allocating an 
        // AVFrame to hold the decoded frame, avcodec_default_get_buffer can 
        // stuff that pts into the it. if all of these relays worked at this 
        // point frame.pts should hold the frame's pts from the original data 
        // stream or AV_NOPTS_VALUE if it didn't have one. in the latter case
        // we generate the next pts in sequence for it.
        double frame_dur = pv->duration;
        if ( frame_dur <= 0 )
        {
            frame_dur = 90000. * (double)pv->context->time_base.num /
                        (double)pv->context->time_base.den;
            pv->duration = frame_dur;
        }
        if ( pv->context->ticks_per_frame > 1 )
        {
            frame_dur *= 2;
        }
        if ( frame.repeat_pict )
        {
            frame_dur += frame.repeat_pict * pv->duration;
        }

        // If there was no pts for this frame, assume constant frame rate
        // video & estimate the next frame time from the last & duration.
        double pts;
        if (frame.pkt_pts == AV_NOPTS_VALUE)
        {
            pts = pv->pts_next;
        }
        else
        {
            pts = frame.pkt_pts;
        }
        pv->pts_next = pts + frame_dur;

        if ( frame.top_field_first )
        {
            flags |= PIC_FLAG_TOP_FIELD_FIRST;
        }
        if ( !frame.interlaced_frame )
        {
            flags |= PIC_FLAG_PROGRESSIVE_FRAME;
        }
        if ( frame.repeat_pict )
        {
            flags |= PIC_FLAG_REPEAT_FIRST_FIELD;
        }

        hb_buffer_t *buf;

        // if we're doing a scan or this content couldn't have been broken
        // by Microsoft we don't worry about timestamp reordering
        if ( ! pv->job || ! pv->brokenByMicrosoft )
        {
            buf = copy_frame( pv, &frame );
            buf->start = pts;
            buf->sequence = sequence;
            buf->flags = flags;
            if ( pv->new_chap && buf->start >= pv->chap_time )
            {
                buf->new_chap = pv->new_chap;
                pv->new_chap = 0;
                pv->chap_time = 0;
                log_chapter( pv, buf->new_chap, buf->start );
            }
            else if ( pv->nframes == 0 && pv->job )
            {
                log_chapter( pv, pv->job->chapter_start, buf->start );
            }
            checkCadence( pv->cadence, buf->flags, buf->start );
            hb_list_add( pv->list, buf );
            ++pv->nframes;
            return got_picture;
        }

        // XXX This following probably addresses a libavcodec bug but I don't
        //     see an easy fix so we workaround it here.
        //
        // The M$ 'packed B-frames' atrocity results in decoded frames with
        // the wrong timestamp. E.g., if there are 2 b-frames the timestamps
        // we see here will be "2 3 1 5 6 4 ..." instead of "1 2 3 4 5 6".
        // The frames are actually delivered in the right order but with
        // the wrong timestamp. To get the correct timestamp attached to
        // each frame we have a delay queue (longer than the max number of
        // b-frames) & a sorting heap for the timestamps. As each frame
        // comes out of the decoder the oldest frame in the queue is removed
        // and associated with the smallest timestamp. Then the new frame is
        // added to the queue & its timestamp is pushed on the heap.
        // This does nothing if the timestamps are correct (i.e., the video
        // uses a codec that Micro$oft hasn't broken yet) but the frames
        // get timestamped correctly even when M$ has munged them.

        // remove the oldest picture from the frame queue (if any) &
        // give it the smallest timestamp from our heap. The queue size
        // is a power of two so we get the slot of the oldest by masking
        // the frame count & this will become the slot of the newest
        // once we've removed & processed the oldest.
        int slot = pv->nframes & (HEAP_SIZE-1);
        if ( ( buf = pv->delayq[slot] ) != NULL )
        {
            pv->queue_primed = 1;
            buf->start = heap_pop( &pv->pts_heap );

            if ( pv->new_chap && buf->start >= pv->chap_time )
            {
                buf->new_chap = pv->new_chap;
                pv->new_chap = 0;
                pv->chap_time = 0;
                log_chapter( pv, buf->new_chap, buf->start );
            }
            else if ( pv->nframes == 0 && pv->job )
            {
                log_chapter( pv, pv->job->chapter_start, buf->start );
            }
            checkCadence( pv->cadence, buf->flags, buf->start );
            hb_list_add( pv->list, buf );
        }

        // add the new frame to the delayq & push its timestamp on the heap
        buf = copy_frame( pv, &frame );
        buf->sequence = sequence;
        buf->flags = flags;
        pv->delayq[slot] = buf;
        heap_push( &pv->pts_heap, pts );

        ++pv->nframes;
    }

    return got_picture;
}

static void decodeVideo( hb_work_private_t *pv, uint8_t *data, int size, int sequence, int64_t pts, int64_t dts )
{
    /*
     * The following loop is a do..while because we need to handle both
     * data & the flush at the end (signaled by size=0). At the end there's
     * generally a frame in the parser & one or more frames in the decoder
     * (depending on the bframes setting).
     */
    int pos = 0;
    do {
        uint8_t *pout;
        int pout_len;
        int len = av_parser_parse2( pv->parser, pv->context, &pout, &pout_len,
                                    data + pos, size - pos, pts, dts, 0 );
        pos += len;

        if ( pout_len > 0 )
        {
            decodeFrame( pv, pout, pout_len, sequence, pv->parser->pts, pv->parser->dts );
        }
    } while ( pos < size );

    /* the stuff above flushed the parser, now flush the decoder */
    if ( size <= 0 )
    {
        while ( decodeFrame( pv, NULL, 0, sequence, AV_NOPTS_VALUE, AV_NOPTS_VALUE ) )
        {
        }
        flushDelayQueue( pv );
    }
}

/*
 * Removes all packets from 'pv->list', links them together into
 * a linked-list, and returns the first packet in the list.
 */
static hb_buffer_t *link_buf_list( hb_work_private_t *pv )
{
    hb_buffer_t *head = hb_list_item( pv->list, 0 );

    if ( head )
    {
        hb_list_rem( pv->list, head );

        hb_buffer_t *last = head, *buf;

        while ( ( buf = hb_list_item( pv->list, 0 ) ) != NULL )
        {
            hb_list_rem( pv->list, buf );
            last->next = buf;
            last = buf;
        }
    }
    return head;
}


static int decavcodecvInit( hb_work_object_t * w, hb_job_t * job )
{

    hb_work_private_t *pv = calloc( 1, sizeof( hb_work_private_t ) );
    w->private_data = pv;
    pv->job   = job;
    pv->list = hb_list_init();

    int codec_id = w->codec_param;
    pv->parser = av_parser_init( codec_id );
    pv->context = avcodec_alloc_context2( AVMEDIA_TYPE_VIDEO );

    /* we have to wrap ffmpeg's get_buffer to be able to set the pts (?!) */
    pv->context->opaque = pv;
    pv->context->get_buffer = get_frame_buf;
    pv->context->reget_buffer = reget_frame_buf;

    return 0;
}

static int next_hdr( hb_buffer_t *in, int offset )
{
    uint8_t *dat = in->data;
    uint16_t last2 = 0xffff;
    for ( ; in->size - offset > 1; ++offset )
    {
        if ( last2 == 0 && dat[offset] == 0x01 )
            // found an mpeg start code
            return offset - 2;

        last2 = ( last2 << 8 ) | dat[offset];
    }

    return -1;
}

static int find_hdr( hb_buffer_t *in, int offset, uint8_t hdr_type )
{
    if ( in->size - offset < 4 )
        // not enough room for an mpeg start code
        return -1;

    for ( ; ( offset = next_hdr( in, offset ) ) >= 0; ++offset )
    {
        if ( in->data[offset+3] == hdr_type )
            // found it
            break;
    }
    return offset;
}

static int setup_extradata( hb_work_object_t *w, hb_buffer_t *in )
{
    hb_work_private_t *pv = w->private_data;

    // we can't call the avstream funcs but the read_header func in the
    // AVInputFormat may set up some state in the AVContext. In particular 
    // vc1t_read_header allocates 'extradata' to deal with header issues
    // related to Microsoft's bizarre engineering notions. We alloc a chunk
    // of space to make vc1 work then associate the codec with the context.
    if ( w->codec_param != CODEC_ID_VC1 )
    {
        // we haven't been inflicted with M$ - allocate a little space as
        // a marker and return success.
        pv->context->extradata_size = 0;
        // av_malloc uses posix_memalign which is allowed to
        // return NULL when allocating 0 bytes.  We use extradata == NULL
        // to trigger initialization of extradata and the decoder, so 
        // we can not set it to NULL here. So allocate a small
        // buffer instead.
        pv->context->extradata = av_malloc(1);
        return 0;
    }

    // find the start and and of the sequence header
    int shdr, shdr_end;
    if ( ( shdr = find_hdr( in, 0, 0x0f ) ) < 0 )
    {
        // didn't find start of seq hdr
        return 1;
    }
    if ( ( shdr_end = next_hdr( in, shdr + 4 ) ) < 0 )
    {
        shdr_end = in->size;
    }
    shdr_end -= shdr;

    // find the start and and of the entry point header
    int ehdr, ehdr_end;
    if ( ( ehdr = find_hdr( in, 0, 0x0e ) ) < 0 )
    {
        // didn't find start of entry point hdr
        return 1;
    }
    if ( ( ehdr_end = next_hdr( in, ehdr + 4 ) ) < 0 )
    {
        ehdr_end = in->size;
    }
    ehdr_end -= ehdr;

    // found both headers - allocate an extradata big enough to hold both
    // then copy them into it.
    pv->context->extradata_size = shdr_end + ehdr_end;
    pv->context->extradata = av_malloc(pv->context->extradata_size + 8);
    memcpy( pv->context->extradata, in->data + shdr, shdr_end );
    memcpy( pv->context->extradata + shdr_end, in->data + ehdr, ehdr_end );
    memset( pv->context->extradata + shdr_end + ehdr_end, 0, 8);
    return 0;
}

static int decavcodecvWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
                            hb_buffer_t ** buf_out )
{
    hb_work_private_t *pv = w->private_data;
    hb_buffer_t *in = *buf_in;
    int64_t pts = AV_NOPTS_VALUE;
    int64_t dts = pts;

    *buf_in = NULL;

    /* if we got an empty buffer signaling end-of-stream send it downstream */
    if ( in->size == 0 )
    {
        if ( pv->context->codec != NULL )
        {
            decodeVideo( pv, in->data, in->size, in->sequence, pts, dts );
        }
        hb_list_add( pv->list, in );
        *buf_out = link_buf_list( pv );
        return HB_WORK_DONE;
    }

    // if this is the first frame open the codec (we have to wait for the
    // first frame because of M$ VC1 braindamage).
    if ( pv->context->extradata == NULL )
    {
        AVCodec *codec = avcodec_find_decoder( w->codec_param );
        avcodec_get_context_defaults3( pv->context, codec );
        hb_ff_set_sample_fmt( pv->context, codec );
        if ( setup_extradata( w, in ) )
        {
            // we didn't find the headers needed to set up extradata.
            // the codec will abort if we open it so just free the buf
            // and hope we eventually get the info we need.
            hb_buffer_close( &in );
            return HB_WORK_OK;
        }
        // There's a mis-feature in ffmpeg that causes the context to be 
        // incorrectly initialized the 1st time avcodec_open is called.
        // If you close it and open a 2nd time, it finishes the job.
        hb_avcodec_open( pv->context, codec, 0 );
        hb_avcodec_close( pv->context );
        // disable threaded decoding for scan, can cause crashes
        hb_avcodec_open( pv->context, codec, pv->job ? HB_FFMPEG_THREADS_AUTO : 0 );
    }

    if( in->start >= 0 )
    {
        pts = in->start;
        dts = in->renderOffset;
    }
    if ( in->new_chap )
    {
        pv->new_chap = in->new_chap;
        pv->chap_time = pts >= 0? pts : pv->pts_next;
    }
    decodeVideo( pv, in->data, in->size, in->sequence, pts, dts );
    hb_buffer_close( &in );
    *buf_out = link_buf_list( pv );
    return HB_WORK_OK;
}

static int decavcodecvInfo( hb_work_object_t *w, hb_work_info_t *info )
{
    hb_work_private_t *pv = w->private_data;

    memset( info, 0, sizeof(*info) );

    if ( pv && pv->context )
    {
        AVCodecContext *context = pv->context;
        info->bitrate = context->bit_rate;
        info->width = context->width;
        info->height = context->height;

        /* ffmpeg gives the frame rate in frames per second while HB wants
         * it in units of the 27MHz MPEG clock. */
        info->rate = 27000000;
        info->rate_base = (int64_t)context->time_base.num * 27000000LL /
                          context->time_base.den;
        if ( context->ticks_per_frame > 1 )
        {
            // for ffmpeg 0.5 & later, the H.264 & MPEG-2 time base is
            // field rate rather than frame rate so convert back to frames.
            info->rate_base *= context->ticks_per_frame;
        }

        info->pixel_aspect_width = context->sample_aspect_ratio.num;
        info->pixel_aspect_height = context->sample_aspect_ratio.den;

        /* Sometimes there's no pixel aspect set in the source ffmpeg context
         * which appears to come from the video stream. In that case,
         * try the pixel aspect in AVStream (which appears to come from
         * the container). Else assume a 1:1 PAR. */
        if ( info->pixel_aspect_width == 0 ||
             info->pixel_aspect_height == 0 )
        {
            // There will not be an ffmpeg stream if the file is TS
            AVStream *st = hb_ffmpeg_avstream( w->codec_param );
            info->pixel_aspect_width = st && st->sample_aspect_ratio.num ?
                                       st->sample_aspect_ratio.num : 1;
            info->pixel_aspect_height = st && st->sample_aspect_ratio.den ?
                                        st->sample_aspect_ratio.den : 1;
        }
        /* ffmpeg returns the Pixel Aspect Ratio (PAR). Handbrake wants the
         * Display Aspect Ratio so we convert by scaling by the Storage
         * Aspect Ratio (w/h). We do the calc in floating point to get the
         * rounding right. */
        info->aspect = (double)info->pixel_aspect_width * 
                       (double)context->width /
                       (double)info->pixel_aspect_height /
                       (double)context->height;

        info->profile = context->profile;
        info->level = context->level;
        info->name = context->codec->name;
        return 1;
    }
    return 0;
}

static int decavcodecvBSInfo( hb_work_object_t *w, const hb_buffer_t *buf,
                             hb_work_info_t *info )
{
    return 0;
}

hb_work_object_t hb_decavcodecv =
{
    WORK_DECAVCODECV,
    "Video decoder (libavcodec)",
    decavcodecvInit,
    decavcodecvWork,
    decavcodecClose,
    decavcodecvInfo,
    decavcodecvBSInfo
};


// This is a special decoder for ffmpeg streams. The ffmpeg stream reader
// includes a parser and passes information from the parser to the decoder
// via a codec context kept in the AVStream of the reader's AVFormatContext.
// We *have* to use that codec context to decode the stream or we'll get
// garbage. ffmpeg_title_scan put a cookie that can be used to get to that
// codec context in our codec_param.

// this routine gets the appropriate context pointer from the ffmpeg
// stream reader. it can't be called until we get the first buffer because
// we can't guarantee that reader will be called before the our init
// routine and if our init is called first we'll get a pointer to the
// old scan stream (which has already been closed).
static void init_ffmpeg_context( hb_work_object_t *w )
{
    hb_work_private_t *pv = w->private_data;
    pv->context = hb_ffmpeg_context( w->codec_param );

    // during scan the decoder gets closed & reopened which will
    // close the codec so reopen it if it's not there
    if ( ! pv->context->codec )
    {
        AVCodec *codec = avcodec_find_decoder( pv->context->codec_id );
        hb_ff_set_sample_fmt( pv->context, codec );
        // disable threaded decoding for scan, can cause crashes
        hb_avcodec_open( pv->context, codec, pv->job ? HB_FFMPEG_THREADS_AUTO : 0 );
    }
    // set up our best guess at the frame duration.
    // the frame rate in the codec is usually bogus but it's sometimes
    // ok in the stream.
    AVStream *st = hb_ffmpeg_avstream( w->codec_param );

    if ( st->nb_frames && st->duration )
    {
        // compute the average frame duration from the total number
        // of frames & the total duration.
        pv->duration = ( (double)st->duration * (double)st->time_base.num ) /
                       ( (double)st->nb_frames * (double)st->time_base.den );
    }
    else
    {
        // XXX We don't have a frame count or duration so try to use the
        // far less reliable time base info in the stream.
        // Because the time bases are so screwed up, we only take values
        // in the range 8fps - 64fps.
        AVRational tb;
        if ( st->avg_frame_rate.den * 64L > st->avg_frame_rate.num &&
             st->avg_frame_rate.num > st->avg_frame_rate.den * 8L )
        {
            tb.num = st->avg_frame_rate.den;
            tb.den = st->avg_frame_rate.num;
        }
        else if ( st->time_base.num * 64L > st->time_base.den &&
                  st->time_base.den > st->time_base.num * 8L )
        {
            tb = st->time_base;
        }
        else if ( st->r_frame_rate.den * 64L > st->r_frame_rate.num &&
                  st->r_frame_rate.num > st->r_frame_rate.den * 8L )
        {
            tb.num = st->r_frame_rate.den;
            tb.den = st->r_frame_rate.num;
        }
        else
        {
            tb.num = 1001;  /*XXX*/
            tb.den = 24000; /*XXX*/
        }
        pv->duration =  (double)tb.num / (double)tb.den;
    }
    pv->duration *= 90000.;

    // we have to wrap ffmpeg's get_buffer to be able to set the pts (?!)
    pv->context->opaque = pv;
    pv->context->get_buffer = get_frame_buf;
    pv->context->reget_buffer = reget_frame_buf;

    // avi, mkv and possibly mp4 containers can contain the M$ VFW packed
    // b-frames abortion that messes up frame ordering and timestamps.
    // XXX ffmpeg knows which streams are broken but doesn't expose the
    //     info externally. We should patch ffmpeg to add a flag to the
    //     codec context for this but until then we mark all ffmpeg streams
    //     as suspicious.
    pv->brokenByMicrosoft = 1;
}

static int decavcodecviInit( hb_work_object_t * w, hb_job_t * job )
{

    hb_work_private_t *pv = calloc( 1, sizeof( hb_work_private_t ) );
    int i;
    w->private_data = pv;
    pv->job   = job;
    pv->list = hb_list_init();
    pv->pts_next = -1;

    if ( w->audio != NULL )
    {
        if ( hb_need_downmix( w->audio->config.in.channel_layout, 
                              w->audio->config.out.mixdown) )
        {
            pv->downmix = hb_downmix_init(w->audio->config.in.channel_layout, 
                                          w->audio->config.out.mixdown);
            hb_downmix_set_chan_map( pv->downmix, &hb_smpte_chan_map, &hb_smpte_chan_map );
        }

        pv->ff_audio_list = hb_list_init();
        for ( i = 0; i < hb_list_count( w->audio->priv.ff_audio_list ); i++ )
        {
            hb_work_private_t * ff_pv = calloc( 1, sizeof( hb_work_private_t ) );
            hb_list_add( pv->ff_audio_list, ff_pv );

            hb_audio_t *audio = hb_list_item( w->audio->priv.ff_audio_list, i );

            ff_pv->list  = hb_list_init();
            ff_pv->job   = job;
            ff_pv->pts_next = -1;

            if ( hb_need_downmix( audio->config.in.channel_layout, 
                                  audio->config.out.mixdown) )
            {
                ff_pv->downmix = hb_downmix_init(audio->config.in.channel_layout, 
                                              audio->config.out.mixdown);
                hb_downmix_set_chan_map( ff_pv->downmix, &hb_smpte_chan_map, &hb_smpte_chan_map );
            }
        }
    }

    return 0;
}

static int decavcodecviWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
                             hb_buffer_t ** buf_out )
{
    hb_work_private_t *pv = w->private_data;
    hb_buffer_t *in = *buf_in;
    *buf_in = NULL;

    /* if we got an empty buffer signaling end-of-stream send it downstream */
    if ( in->size == 0 )
    {
        /* flush any frames left in the decoder */
        while ( pv->context && decodeFrame( pv, NULL, 0, in->sequence, AV_NOPTS_VALUE, AV_NOPTS_VALUE ) )
        {
        }
        flushDelayQueue( pv );
        hb_list_add( pv->list, in );
        *buf_out = link_buf_list( pv );
        return HB_WORK_DONE;
    }

    if ( ! pv->context )
    {
        init_ffmpeg_context( w );
    }

    int64_t pts = in->start;
    if( pts >= 0 )
    {
        // use the first timestamp as our 'next expected' pts
        if ( pv->pts_next < 0 )
        {
            pv->pts_next = pts;
        }
    }

    if ( in->new_chap )
    {
        pv->new_chap = in->new_chap;
        pv->chap_time = pts >= 0? pts : pv->pts_next;
    }
    decodeFrame( pv, in->data, in->size, in->sequence, in->start, in->renderOffset );
    hb_buffer_close( &in );
    *buf_out = link_buf_list( pv );
    return HB_WORK_OK;
}

static int decavcodecviInfo( hb_work_object_t *w, hb_work_info_t *info )
{
    if ( decavcodecvInfo( w, info ) )
    {
        hb_work_private_t *pv = w->private_data;
        if ( ! pv->context )
        {
            init_ffmpeg_context( w );
        }
        // we have the frame duration in units of the 90KHz pts clock but
        // need it in units of the 27MHz MPEG clock. */
        info->rate = 27000000;
        info->rate_base = pv->duration * 300.;
        return 1;
    }
    return 0;
}

static hb_buffer_t * downmixAudio( 
    hb_audio_t *audio, 
    hb_work_private_t *pv, 
    hb_sample_t *buffer, 
    int channels,
    int nsamples )
{
    hb_buffer_t * buf = NULL;

    if ( pv->downmix )
    {
        int n_ch_samples = nsamples / channels;
        int out_channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(audio->config.out.mixdown);

        buf = hb_buffer_init( n_ch_samples * out_channels * sizeof(float) );
        hb_sample_t *samples = (hb_sample_t *)buf->data;
        hb_downmix(pv->downmix, samples, buffer, n_ch_samples);
    }
    else
    {
        buf = hb_buffer_init( nsamples * sizeof(float) );
        memcpy( buf->data, buffer, nsamples * sizeof(float) );
    }

    return buf;
}

static void decodeAudio( hb_audio_t * audio, hb_work_private_t *pv, uint8_t *data, int size, int64_t pts )
{
    AVCodecContext *context = pv->context;
    int pos = 0;
    int loop_limit = 256;

    if ( pts != -1 )
        pv->pts_next = pts;

    while ( pos < size )
    {
        float *buffer = pv->buffer;
        if ( buffer == NULL )
        {
            pv->buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE );
            buffer = pv->buffer;
        }

        AVPacket avp;
        av_init_packet( &avp );
        avp.data = data + pos;
        avp.size = size - pos;
        avp.pts = pv->pts_next;
        avp.dts = AV_NOPTS_VALUE;

        int out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
        int nsamples;
        int len = avcodec_decode_audio3( context, (int16_t*)buffer, &out_size, &avp );
        if ( len < 0 )
        {
            return;
        }
        if ( len == 0 )
        {
            if ( !(loop_limit--) )
                return;
        }
        else
            loop_limit = 256;

        pos += len;
        if( out_size > 0 )
        {
            int isamp = av_get_bytes_per_sample( context->sample_fmt );
            nsamples = out_size / isamp;
            double pts_next = pv->pts_next + nsamples * pv->duration;

            // DTS-HD can be passed through to mkv
            if( audio->config.out.codec & HB_ACODEC_PASS_FLAG )
            {
                // Note that even though we are doing passthru, we had
                // to decode so that we know the stop time and the
                // pts of the next audio packet.
                hb_buffer_t * buf;

                buf = hb_buffer_init( avp.size );
                memcpy( buf->data, avp.data, len );
                buf->start = pv->pts_next;
                buf->stop  = pts_next;
                hb_list_add( pv->list, buf );

                if ( hb_list_count( audio->priv.ff_audio_list ) == 0 )
                {
                    pv->pts_next = pts_next;
                    continue;
                }
                // Fall through and process the list of other audio
                // pipelines that use this ffmpeg audio stream.
            }

            // We require signed floats for the output format. If
            // we got something different convert it.
            if ( context->sample_fmt != AV_SAMPLE_FMT_FLT )
            {
                // Note: av_audio_convert seems to be a work-in-progress but
                //       looks like it will eventually handle general audio
                //       mixdowns which would allow us much more flexibility
                //       in handling multichannel audio in HB. If we were doing
                //       anything more complicated than a one-for-one format
                //       conversion we'd probably want to cache the converter
                //       context in the pv.
                AVAudioConvert *ctx;

                ctx = av_audio_convert_alloc( AV_SAMPLE_FMT_FLT, 1,
                                              context->sample_fmt, 1,
                                              NULL, 0 );

                // get output buffer size then malloc a buffer
                buffer = av_malloc( nsamples * sizeof(hb_sample_t) );

                // we're doing straight sample format conversion which 
                // behaves as if there were only one channel.
                const void * const ibuf[6] = { pv->buffer };
                void * const obuf[6] = { buffer };
                const int istride[6] = { isamp };
                const int ostride[6] = { sizeof(hb_sample_t) };

                av_audio_convert( ctx, obuf, ostride, ibuf, istride, nsamples );
                av_audio_convert_free( ctx );
            }

            if ( !( audio->config.out.codec & HB_ACODEC_PASS_FLAG ) )
            {
                hb_buffer_t * buf;
                buf = downmixAudio( audio, pv, buffer, context->channels, nsamples );
                buf->start = pv->pts_next;
                buf->stop = pts_next;
                hb_list_add( pv->list, buf );
            }

            int i;
            for ( i = 0; i < hb_list_count( audio->priv.ff_audio_list ); i++ )
            {
                hb_audio_t *ff_audio = hb_list_item( audio->priv.ff_audio_list, i );
                hb_work_private_t *ff_pv = hb_list_item( pv->ff_audio_list, i );
                if ( ff_pv )
                {
                    hb_buffer_t * buf;

                    if ( !( ff_audio->config.out.codec & HB_ACODEC_PASS_FLAG ) )
                    {
                        buf = downmixAudio( ff_audio, ff_pv, buffer, context->channels, nsamples );
                    }
                    else
                    {
                        buf = hb_buffer_init( avp.size );
                        memcpy( buf->data, avp.data, len );
                    }
                    buf->start = pv->pts_next;
                    buf->stop  = pts_next;
                    hb_list_add( ff_pv->list, buf );
                }
            }
            pv->pts_next = pts_next;

            // if we allocated a buffer for sample format conversion, free it
            if ( buffer != pv->buffer )
            {
                av_free( buffer );
            }
        }
    }
}

static int decavcodecaiWork( hb_work_object_t *w, hb_buffer_t **buf_in,
                    hb_buffer_t **buf_out )
{
    if ( (*buf_in)->size <= 0 )
    {
        /* EOF on input stream - send it downstream & say that we're done */
        *buf_out = *buf_in;
        *buf_in = NULL;
        writeAudioEof( w );
        return HB_WORK_DONE;
    }

    hb_work_private_t *pv = w->private_data;

    if ( (*buf_in)->start < -1 && pv->pts_next <= 0 )
    {
        // discard buffers that start before video time 0
        *buf_out = NULL;
        return HB_WORK_OK;
    }

    if ( ! pv->context )
    {
        init_ffmpeg_context( w );
        // duration is a scaling factor to go from #bytes in the decoded
        // frame to frame time (in 90KHz mpeg ticks). 'channels' converts
        // total samples to per-channel samples. 'sample_rate' converts
        // per-channel samples to seconds per sample and the 90000
        // is mpeg ticks per second.
        pv->duration = 90000. /
                    (double)( pv->context->sample_rate * pv->context->channels );
    }
    hb_buffer_t *in = *buf_in;

    // if the packet has a timestamp use it if we don't have a timestamp yet
    // or if there's been a timing discontinuity of more than 100ms.
    if ( in->start >= 0 )
    {
        pv->pts_next = in->start;
    }
    decodeAudio( w->audio, pv, in->data, in->size, pv->pts_next );
    writeAudioFifos( w );
    *buf_out = link_buf_list( pv );

    return HB_WORK_OK;
}

hb_work_object_t hb_decavcodecvi =
{
    WORK_DECAVCODECVI,
    "Video decoder (ffmpeg streams)",
    decavcodecviInit,
    decavcodecviWork,
    decavcodecClose,
    decavcodecviInfo,
    decavcodecvBSInfo
};

hb_work_object_t hb_decavcodecai =
{
    WORK_DECAVCODECAI,
    "Audio decoder (ffmpeg streams)",
    decavcodecviInit,
    decavcodecaiWork,
    decavcodecClose,
    decavcodecInfo,
    decavcodecBSInfo
};