forked from HandBrake/HandBrake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecavcodec.c
1799 lines (1629 loc) · 58.1 KB
/
decavcodec.c
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
/* decavcodec.c
Copyright (c) 2003-2013 HandBrake Team
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 v2.
For full terms see the file COPYING file or visit http://www.gnu.org/licenses/gpl-2.0.html
*/
/* This module is Handbrake's interface to the ffmpeg decoder library
(libavcodec & small parts of libavformat). It contains four Handbrake
"work objects":
decavcodeca 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.
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.).
These decoders handle 2 kinds of input. Streams that are demuxed
by HandBrake and streams that are demuxed by libavformat. In the
case of streams that are demuxed by HandBrake, there is an extra
parse step required that happens in decodeVideo and decavcodecaWork.
In the case of streams that are demuxed by libavformat, there is context
information that we need from the libavformat. This information is
propagated from hb_stream_open to these decoders through title->opaque_priv.
A consequence of the above is that the streams that are demuxed by HandBrake
*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 "audio_resample.h"
#ifdef USE_QSV
#include "enc_qsv.h"
#include "qsv_common.h"
#endif
static void compute_frame_duration( hb_work_private_t *pv );
static void flushDelayQueue( hb_work_private_t *pv );
static int decavcodecaInit( hb_work_object_t *, hb_job_t * );
static int decavcodecaWork( hb_work_object_t *, hb_buffer_t **, hb_buffer_t ** );
static void decavcodecClose( hb_work_object_t * );
static int decavcodecaInfo( hb_work_object_t *, hb_work_info_t * );
static int decavcodecaBSInfo( hb_work_object_t *, const hb_buffer_t *, hb_work_info_t * );
hb_work_object_t hb_decavcodeca =
{
.id = WORK_DECAVCODEC,
.name = "Audio decoder (libavcodec)",
.init = decavcodecaInit,
.work = decavcodecaWork,
.close = decavcodecClose,
.info = decavcodecaInfo,
.bsinfo = decavcodecaBSInfo
};
#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;
hb_title_t *title;
AVCodecContext *context;
AVCodecParserContext *parser;
int threads;
int video_codec_opened;
hb_list_t *list;
double duration; // frame duration (for video)
double field_duration; // field duration (for video)
int frame_duration_set; // Indicates valid timing was found in stream
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
int sws_width;
int sws_height;
int sws_pix_fmt;
int cadence[12];
int wait_for_keyframe;
hb_audio_resample_t *resample;
#ifdef USE_QSV
av_qsv_config qsv_config;
int qsv_decode;
const char *qsv_codec_name;
#define USE_QSV_PTS_WORKAROUND // work around out-of-order output timestamps
#ifdef USE_QSV_PTS_WORKAROUND
hb_list_t *qsv_pts_list;
#endif
#endif
};
#ifdef USE_QSV_PTS_WORKAROUND
// save/restore PTS if the decoder may not attach the right PTS to the frame
static void hb_av_add_new_pts(hb_list_t *list, int64_t new_pts)
{
int index = 0;
int64_t *cur_item, *new_item;
if (list != NULL && new_pts != AV_NOPTS_VALUE)
{
new_item = malloc(sizeof(int64_t));
if (new_item != NULL)
{
*new_item = new_pts;
// sort chronologically
for (index = 0; index < hb_list_count(list); index++)
{
cur_item = hb_list_item(list, index);
if (cur_item != NULL)
{
if (*cur_item == *new_item)
{
// no duplicates
free(new_item);
return;
}
if (*cur_item > *new_item)
{
// insert here
break;
}
}
}
hb_list_insert(list, index, new_item);
}
}
}
static int64_t hb_av_pop_next_pts(hb_list_t *list)
{
int64_t *item, next_pts = AV_NOPTS_VALUE;
if (list != NULL && hb_list_count(list) > 0)
{
item = hb_list_item(list, 0);
if (item != NULL)
{
next_pts = *item;
hb_list_rem(list, item);
free(item);
}
}
return next_pts;
}
#endif
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 decavcodecaInit( hb_work_object_t * w, hb_job_t * job )
{
AVCodec * codec;
hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
w->private_data = pv;
pv->job = job;
if (job)
pv->title = job->title;
else
pv->title = w->title;
pv->list = hb_list_init();
codec = avcodec_find_decoder(w->codec_param);
pv->context = avcodec_alloc_context3(codec);
if (pv->title->opaque_priv != NULL)
{
AVFormatContext *ic = (AVFormatContext*)pv->title->opaque_priv;
avcodec_copy_context(pv->context, ic->streams[w->audio->id]->codec);
// libav's eac3 parser toggles the codec_id in the context as
// it reads eac3 data between AV_CODEC_ID_AC3 and AV_CODEC_ID_EAC3.
// It detects an AC3 sync pattern sometimes in ac3_sync() which
// causes it to eventually set avctx->codec_id to AV_CODEC_ID_AC3
// in ff_aac_ac3_parse(). Since we are parsing some data before
// we get here, the codec_id may have flipped. This will cause an
// error in hb_avcodec_open(). So flip it back!
pv->context->codec_id = w->codec_param;
}
else
{
pv->parser = av_parser_init(w->codec_param);
}
hb_ff_set_sample_fmt(pv->context, codec, AV_SAMPLE_FMT_FLT);
/* Downmixing & sample_fmt conversion */
if (!(w->audio->config.out.codec & HB_ACODEC_PASS_FLAG))
{
pv->resample =
hb_audio_resample_init(AV_SAMPLE_FMT_FLT,
w->audio->config.out.mixdown,
w->audio->config.out.normalize_mix_level);
if (pv->resample == NULL)
{
hb_error("decavcodecaInit: hb_audio_resample_init() failed");
return 1;
}
// some decoders can downmix using embedded coefficients,
// or dedicated audio substreams for a specific channel layout
switch (w->audio->config.out.mixdown)
{
case HB_AMIXDOWN_MONO:
if (w->codec_param == AV_CODEC_ID_TRUEHD)
{
// libavcodec can't decode TrueHD Mono (bug #356)
// work around it by requesting Stereo and downmixing
pv->context->request_channels = 2;
pv->context->request_channel_layout = AV_CH_LAYOUT_STEREO;
break;
}
pv->context->request_channel_layout = AV_CH_LAYOUT_MONO;
break;
// request 5.1 before downmixing to dpl1/dpl2
case HB_AMIXDOWN_DOLBY:
case HB_AMIXDOWN_DOLBYPLII:
pv->context->request_channel_layout = AV_CH_LAYOUT_5POINT1;
break;
// request the layout corresponding to the selected mixdown
default:
pv->context->request_channel_layout =
hb_ff_mixdown_xlat(w->audio->config.out.mixdown, NULL);
break;
}
}
if (hb_avcodec_open(pv->context, codec, NULL, 0))
{
hb_log("decavcodecaInit: avcodec_open failed");
return 1;
}
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 )
{
#ifdef USE_QSV
if (!pv->qsv_decode)
#endif
{
hb_avcodec_close(pv->context);
}
}
if ( pv->context )
{
av_freep( &pv->context->extradata );
av_free( pv->context );
}
if ( pv->list )
{
hb_list_empty( &pv->list );
}
hb_audio_resample_free(pv->resample);
#ifdef USE_QSV_PTS_WORKAROUND
if (pv->qsv_decode && pv->qsv_pts_list != NULL)
{
while (hb_list_count(pv->qsv_pts_list) > 0)
{
int64_t *item = hb_list_item(pv->qsv_pts_list, 0);
hb_list_rem(pv->qsv_pts_list, item);
free(item);
}
hb_list_close(&pv->qsv_pts_list);
}
#endif
free( pv );
}
*ppv = NULL;
}
static void decavcodecClose( hb_work_object_t * w )
{
hb_work_private_t * pv = w->private_data;
if ( pv )
{
closePrivData( &pv );
w->private_data = NULL;
}
}
/***********************************************************************
* Work
***********************************************************************
*
**********************************************************************/
static int decavcodecaWork( 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;
return HB_WORK_DONE;
}
*buf_out = NULL;
if ( in->s.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 *pout;
int pout_len;
int64_t cur;
cur = in->s.start;
if ( pv->parser != NULL )
{
len = av_parser_parse2( pv->parser, pv->context, &pout, &pout_len,
in->data + pos, in->size - pos, cur, cur, 0 );
cur = pv->parser->pts;
if ( cur == AV_NOPTS_VALUE )
cur = -1;
}
else
{
pout = in->data;
len = pout_len = in->size;
}
if (pout)
{
// 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->duration = 90000. / (double)( pv->context->sample_rate );
}
decodeAudio( w->audio, pv, pout, pout_len, cur );
}
}
*buf_out = link_buf_list( pv );
return HB_WORK_OK;
}
static int decavcodecaInfo( 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 decavcodecaBSInfo( 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 decavcodecaInfo( w, info );
}
AVCodec *codec = avcodec_find_decoder( w->codec_param );
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 );
AVCodecContext *context = avcodec_alloc_context3(codec);
AVCodecParserContext *parser = NULL;
if (w->title->opaque_priv != NULL)
{
AVFormatContext *ic = (AVFormatContext*)w->title->opaque_priv;
avcodec_copy_context(context, ic->streams[w->audio->id]->codec);
// libav's eac3 parser toggles the codec_id in the context as
// it reads eac3 data between AV_CODEC_ID_AC3 and AV_CODEC_ID_EAC3.
// It detects an AC3 sync pattern sometimes in ac3_sync() which
// causes it to eventually set avctx->codec_id to AV_CODEC_ID_AC3
// in ff_aac_ac3_parse(). Since we are parsing some data before
// we get here, the codec_id may have flipped. This will cause an
// error in hb_avcodec_open(). So flip it back!
context->codec_id = w->codec_param;
}
else
{
parser = av_parser_init(codec->id);
}
hb_ff_set_sample_fmt( context, codec, AV_SAMPLE_FMT_FLT );
if ( hb_avcodec_open( context, codec, NULL, 0 ) )
{
return -1;
}
unsigned char *pbuffer;
int pos, pbuffer_size;
while (buf != NULL && !ret)
{
pos = 0;
while (pos < buf->size)
{
int len, truehd_mono = 0;
if (parser != NULL)
{
len = av_parser_parse2(parser, context, &pbuffer, &pbuffer_size,
buf->data + pos, buf->size - pos,
buf->s.start, buf->s.start, 0);
}
else
{
pbuffer = buf->data;
len = pbuffer_size = buf->size;
}
pos += len;
// libavcodec can't decode TrueHD Mono (bug #356)
// work around it by requesting Stereo before decoding
if (context->codec_id == AV_CODEC_ID_TRUEHD &&
context->channel_layout == AV_CH_LAYOUT_MONO)
{
truehd_mono = 1;
context->request_channels = 2;
context->request_channel_layout = AV_CH_LAYOUT_STEREO;
}
else
{
context->request_channels = 0;
context->request_channel_layout = 0;
}
if (pbuffer_size > 0)
{
int got_frame;
AVFrame frame = { { 0 } };
AVPacket avp;
av_init_packet(&avp);
avp.data = pbuffer;
avp.size = pbuffer_size;
len = avcodec_decode_audio4(context, &frame, &got_frame, &avp);
if (len > 0 && context->sample_rate > 0)
{
info->rate_base = 1;
info->rate = context->sample_rate;
info->samples_per_frame = frame.nb_samples;
int bps = av_get_bits_per_sample(context->codec_id);
if (bps > 0 && context->channels > 0)
{
info->bitrate = (bps *
context->channels *
context->sample_rate);
}
else if (context->bit_rate > 0)
{
info->bitrate = context->bit_rate;
}
else
{
info->bitrate = 1;
}
if (truehd_mono)
{
info->channel_layout = AV_CH_LAYOUT_MONO;
}
else
{
info->channel_layout =
hb_ff_layout_xlat(context->channel_layout,
context->channels);
}
ret = 1;
break;
}
}
}
buf = buf->next;
}
info->profile = context->profile;
info->level = context->level;
info->channel_map = &hb_libav_chan_map;
if ( parser != NULL )
av_parser_close( parser );
hb_avcodec_close( context );
av_free( 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 )
{
// HandBrake's video pipeline uses yuv420 color. This means all
// dimensions must be even. So we must adjust the dimensions
// of incoming video if not even.
w = context->width & ~1;
h = context->height & ~1;
}
else
{
w = pv->job->title->width;
h = pv->job->title->height;
}
hb_buffer_t *buf = hb_video_buffer_init( w, h );
#ifdef USE_QSV
// no need to copy the frame data when decoding with QSV to opaque memory
if (pv->qsv_decode &&
pv->qsv_config.io_pattern == MFX_IOPATTERN_OUT_OPAQUE_MEMORY)
{
buf->qsv_details.qsv_atom = frame->data[2];
return buf;
}
#endif
uint8_t *dst = buf->data;
if (context->pix_fmt != AV_PIX_FMT_YUV420P || w != context->width ||
h != context->height)
{
// have to convert to our internal color space and/or rescale
AVPicture dstpic;
hb_avpicture_fill(&dstpic, buf);
if (pv->sws_context == NULL ||
pv->sws_width != context->width ||
pv->sws_height != context->height ||
pv->sws_pix_fmt != context->pix_fmt)
{
if (pv->sws_context != NULL)
sws_freeContext(pv->sws_context);
pv->sws_context = hb_sws_get_context(context->width,
context->height,
context->pix_fmt,
w, h, AV_PIX_FMT_YUV420P,
SWS_LANCZOS|SWS_ACCURATE_RND);
pv->sws_width = context->width;
pv->sws_height = context->height;
pv->sws_pix_fmt = context->pix_fmt;
}
sws_scale(pv->sws_context,
(const uint8_t* const *)frame->data, frame->linesize,
0, context->height, dstpic.data, dstpic.linesize);
}
else
{
w = buf->plane[0].stride;
h = buf->plane[0].height;
dst = buf->plane[0].data;
copy_plane( dst, frame->data[0], w, frame->linesize[0], h );
w = buf->plane[1].stride;
h = buf->plane[1].height;
dst = buf->plane[1].data;
copy_plane( dst, frame->data[1], w, frame->linesize[1], h );
w = buf->plane[2].stride;
h = buf->plane[2].height;
dst = buf->plane[2].data;
copy_plane( dst, frame->data[2], w, frame->linesize[2], h );
}
return buf;
}
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->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->s.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_object_t *w, uint8_t *data, int size, int sequence, int64_t pts, int64_t dts, uint8_t frametype )
{
hb_work_private_t *pv = w->private_data;
int got_picture, oldlevel = 0;
AVFrame frame = { { 0 } };
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;
/*
* libav avcodec_decode_video2() needs AVPacket flagged with AV_PKT_FLAG_KEY
* for some codecs. For example, sequence of PNG in a mov container.
*/
if ( frametype & HB_FRAME_KEY )
{
avp.flags |= AV_PKT_FLAG_KEY;
}
#ifdef USE_QSV_PTS_WORKAROUND
/*
* The MediaSDK decoder will return decoded frames in the correct order,
* but *sometimes* with the incorrect timestamp assigned to them.
*
* We work around it by saving the input timestamps (in chronological order)
* and restoring them after decoding.
*/
if (pv->qsv_decode && avp.data != NULL)
{
hb_av_add_new_pts(pv->qsv_pts_list, avp.pts);
}
#endif
if ( avcodec_decode_video2( pv->context, &frame, &got_picture, &avp ) < 0 )
{
++pv->decode_errors;
}
#ifdef USE_QSV
if (pv->qsv_decode && pv->job->qsv == NULL && pv->video_codec_opened > 0)
{
// this is quite late, but we can't be certain that the QSV context is
// available until after we call avcodec_decode_video2() at least once
pv->job->qsv = pv->context->priv_data;
}
#endif
#ifdef USE_QSV_PTS_WORKAROUND
if (pv->qsv_decode && got_picture)
{
// we got a decoded frame, restore the lowest available PTS
frame.pkt_pts = hb_av_pop_next_pts(pv->qsv_pts_list);
}
#endif
if ( global_verbosity_level <= 1 )
{
av_log_set_level( oldlevel );
}
if( got_picture && pv->wait_for_keyframe > 0 )
{
// Libav is inconsistant about how it flags keyframes. For many
// codecs it simply sets frame.key_frame. But for others, it only
// sets frame.pict_type. And for yet others neither gets set at all
// (qtrle).
int key = frame.key_frame || (w->codec_param != AV_CODEC_ID_H264 &&
(frame.pict_type == 0 ||
frame.pict_type == AV_PICTURE_TYPE_I));
if( !key )
{
pv->wait_for_keyframe--;
return 0;
}
pv->wait_for_keyframe = 0;
}
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.
if ( !pv->frame_duration_set )
compute_frame_duration( pv );
double frame_dur = pv->duration;
if ( frame.repeat_pict )
{
frame_dur += frame.repeat_pict * pv->field_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 == 1 )
{
flags |= PIC_FLAG_REPEAT_FIRST_FIELD;
}
if ( frame.repeat_pict == 2 )