forked from HandBrake/HandBrake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decavcodec.c
2345 lines (2124 loc) · 77.9 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-2019 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
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 "handbrake/handbrake.h"
#include "handbrake/hbffmpeg.h"
#include "handbrake/hbavfilter.h"
#include "libavfilter/avfilter.h"
#include "libavfilter/buffersrc.h"
#include "libavfilter/buffersink.h"
#include "libavutil/hwcontext.h"
#include "handbrake/lang.h"
#include "handbrake/audio_resample.h"
#if HB_PROJECT_FEATURE_QSV
#include "libavutil/hwcontext_qsv.h"
#include "handbrake/qsv_common.h"
#include "handbrake/qsv_libav.h"
#endif
static void compute_frame_duration( 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 * );
static int get_color_prim(int color_primaries, hb_geometry_t geometry, hb_rational_t rate);
static int get_color_transfer(int color_trc);
static int get_color_matrix(int colorspace, hb_geometry_t geometry);
hb_work_object_t hb_decavcodeca =
{
.id = WORK_DECAVCODEC,
.name = "Audio decoder (libavcodec)",
.init = decavcodecaInit,
.work = decavcodecaWork,
.close = decavcodecClose,
.info = decavcodecaInfo,
.bsinfo = decavcodecaBSInfo
};
typedef struct
{
uint8_t * data;
int size;
int64_t pts;
int64_t dts;
int frametype;
int scr_sequence;
int new_chap;
int discard;
} packet_info_t;
typedef struct reordered_data_s reordered_data_t;
struct reordered_data_s
{
int64_t sequence;
int64_t pts;
int scr_sequence;
int new_chap;
};
#define REORDERED_HASH_SZ (2 << 7)
#define REORDERED_HASH_MASK (REORDERED_HASH_SZ - 1)
struct video_filters_s
{
hb_avfilter_graph_t * graph;
int width;
int height;
int pix_fmt;
};
struct hb_work_private_s
{
hb_job_t * job;
hb_title_t * title;
AVCodec * codec;
AVCodecContext * context;
AVCodecParserContext * parser;
AVFrame * frame;
hb_buffer_t * palette;
int threads;
int video_codec_opened;
hb_buffer_list_t list;
double duration; // frame duration (for video)
double field_duration; // field duration (for video)
int64_t chap_time; // time of next chap mark
int chap_scr;
int new_chap; // output chapter mark pending
int64_t last_pts;
double next_pts;
uint32_t nframes;
uint32_t decode_errors;
packet_info_t packet_info;
uint8_t unfinished;
reordered_data_t * reordered_hash[REORDERED_HASH_SZ];
int64_t sequence;
int last_scr_sequence;
int last_chapter;
struct video_filters_s video_filters;
hb_audio_t * audio;
hb_audio_resample_t * resample;
int drop_samples;
#if HB_PROJECT_FEATURE_QSV
// QSV-specific settings
struct
{
int decode;
hb_qsv_config config;
const char * codec_name;
} qsv;
#endif
hb_list_t * list_subtitle;
};
static void decodeAudio( hb_work_private_t *pv, packet_info_t * packet_info );
/***********************************************************************
* 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;
pv->audio = w->audio;
pv->drop_samples = w->audio->config.in.encoder_delay;
pv->next_pts = (int64_t)AV_NOPTS_VALUE;
if (job)
pv->title = job->title;
else
pv->title = w->title;
hb_buffer_list_clear(&pv->list);
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_parameters_to_context(pv->context,
ic->streams[w->audio->id]->codecpar);
// 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))
{
// Currently, samplerate conversion is performed in sync.c
// So set output samplerate to input samplerate
// This should someday get reworked to be part of an audio
// filter pipleine.
pv->resample =
hb_audio_resample_init(AV_SAMPLE_FMT_FLT,
w->audio->config.in.samplerate,
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 audio decoders can downmix using embedded coefficients,
* or dedicated audio substreams for a specific channel layout.
*
* But some will e.g. use normalized mix coefficients unconditionally,
* so we need to make sure this matches what the user actually requested.
*/
int avcodec_downmix = 0;
switch (w->codec_param)
{
case AV_CODEC_ID_AC3:
case AV_CODEC_ID_EAC3:
avcodec_downmix = w->audio->config.out.normalize_mix_level != 0;
break;
case AV_CODEC_ID_DTS:
avcodec_downmix = w->audio->config.out.normalize_mix_level == 0;
break;
case AV_CODEC_ID_TRUEHD:
avcodec_downmix = (w->audio->config.out.normalize_mix_level == 0 ||
w->audio->config.out.mixdown == HB_AMIXDOWN_MONO ||
w->audio->config.out.mixdown == HB_AMIXDOWN_DOLBY ||
w->audio->config.out.mixdown == HB_AMIXDOWN_DOLBYPLII);
break;
default:
break;
}
if (avcodec_downmix)
{
switch (w->audio->config.out.mixdown)
{
// 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;
}
}
}
// libavcodec can't decode TrueHD Mono (bug #356)
// work around it by requesting Stereo and downmixing
if (w->codec_param == AV_CODEC_ID_TRUEHD &&
w->audio->config.in.channel_layout == AV_CH_LAYOUT_MONO)
{
pv->context->request_channel_layout = AV_CH_LAYOUT_STEREO;
}
// Set decoder opts...
AVDictionary * av_opts = NULL;
av_dict_set( &av_opts, "refcounted_frames", "1", 0 );
// Dynamic Range Compression
if (w->audio->config.out.dynamic_range_compression >= 0.0f &&
hb_audio_can_apply_drc(w->audio->config.in.codec,
w->audio->config.in.codec_param, 0))
{
float drc_scale_max = 1.0f;
/*
* avcodec_open will fail if the value for any of the options is out of
* range, so assume a conservative maximum of 1 and try to determine the
* option's actual upper limit.
*/
if (codec != NULL && codec->priv_class != NULL)
{
const AVOption *opt;
opt = av_opt_find2((void*)&codec->priv_class, "drc_scale", NULL,
AV_OPT_FLAG_DECODING_PARAM|AV_OPT_FLAG_AUDIO_PARAM,
AV_OPT_SEARCH_FAKE_OBJ, NULL);
if (opt != NULL)
{
drc_scale_max = opt->max;
}
}
if (w->audio->config.out.dynamic_range_compression > drc_scale_max)
{
hb_log("decavcodecaInit: track %d, sanitizing out-of-range DRC %.2f to %.2f",
w->audio->config.out.track,
w->audio->config.out.dynamic_range_compression, drc_scale_max);
w->audio->config.out.dynamic_range_compression = drc_scale_max;
}
char drc_scale[5]; // "?.??\n"
snprintf(drc_scale, sizeof(drc_scale), "%.2f",
w->audio->config.out.dynamic_range_compression);
av_dict_set(&av_opts, "drc_scale", drc_scale, 0);
}
if (hb_avcodec_open(pv->context, codec, &av_opts, 0))
{
av_dict_free( &av_opts );
hb_log("decavcodecaInit: avcodec_open failed");
return 1;
}
pv->context->pkt_timebase.num = pv->audio->config.in.timebase.num;
pv->context->pkt_timebase.den = pv->audio->config.in.timebase.den;
// avcodec_open populates av_opts with the things it didn't recognize.
AVDictionaryEntry *t = NULL;
while ((t = av_dict_get(av_opts, "", t, AV_DICT_IGNORE_SUFFIX)) != NULL)
{
hb_log("decavcodecaInit: unknown option '%s'", t->key);
}
av_dict_free( &av_opts );
pv->frame = av_frame_alloc();
if (pv->frame == NULL)
{
hb_log("decavcodecaInit: av_frame_alloc failed");
return 1;
}
return 0;
}
/***********************************************************************
* Close
***********************************************************************
*
**********************************************************************/
static void close_video_filters(hb_work_private_t *pv)
{
hb_avfilter_graph_close(&pv->video_filters.graph);
}
static void closePrivData( hb_work_private_t ** ppv )
{
hb_work_private_t * pv = *ppv;
if ( pv )
{
hb_buffer_list_close(&pv->list);
if ( pv->job && pv->context && pv->context->codec )
{
hb_log( "%s-decoder done: %u frames, %u decoder errors",
pv->context->codec->name, pv->nframes, pv->decode_errors);
}
av_frame_free(&pv->frame);
close_video_filters(pv);
if ( pv->parser )
{
av_parser_close(pv->parser);
}
if ( pv->context && pv->context->codec )
{
#if HB_PROJECT_FEATURE_QSV
/*
* FIXME: knowingly leaked.
*
* If we're using our FFmpeg QSV wrapper, qsv_decode_end() will call
* MFXClose() on the QSV session. Even if decoding is complete, we
* still need that session for QSV filtering and/or encoding, so we
* we can't close the context here until we implement a proper fix.
*
* Interestingly, this may cause crashes even when QSV-accelerated
* decoding and encoding sessions are independent (e.g. decoding via
* libavcodec, but encoding using libhb, without us requesting any
* form of communication between the two libmfx sessions).
*/
//if (!(pv->qsv.decode && pv->job != NULL && (pv->job->vcodec & HB_VCODEC_QSV_MASK)))
hb_qsv_uninit_dec(pv->context);
#endif
{
hb_avcodec_free_context(&pv->context);
}
}
if ( pv->context )
{
hb_avcodec_free_context(&pv->context);
}
hb_audio_resample_free(pv->resample);
int ii;
for (ii = 0; ii < REORDERED_HASH_SZ; ii++)
{
free(pv->reordered_hash[ii]);
}
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;
}
}
static void audioParserFlush(hb_work_object_t * w)
{
hb_work_private_t * pv = w->private_data;
uint8_t * pout = NULL;
int pout_len = 0;
int64_t parser_pts = AV_NOPTS_VALUE;
do
{
if (pv->parser)
{
av_parser_parse2(pv->parser, pv->context, &pout, &pout_len,
NULL, 0,
AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0 );
parser_pts = pv->parser->pts;
}
if (pout != NULL && pout_len > 0)
{
pv->packet_info.data = pout;
pv->packet_info.size = pout_len;
pv->packet_info.pts = parser_pts;
decodeAudio(pv, &pv->packet_info);
}
} while (pout != NULL && pout_len > 0);
}
/***********************************************************************
* 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;
// libavcodec/mpeg12dec.c requires buffers to be zero padded.
// If not zero padded, it can get stuck in an infinite loop.
// It's likely there are other decoders that expect the same.
if (in->data != NULL)
{
memset(in->data + in->size, 0, in->alloc - in->size);
}
if (in->s.flags & HB_BUF_FLAG_EOF)
{
/* EOF on input stream - send it downstream & say that we're done */
audioParserFlush(w);
decodeAudio(pv, NULL);
hb_buffer_list_append(&pv->list, in);
*buf_in = NULL;
*buf_out = hb_buffer_list_clear(&pv->list);
return HB_WORK_DONE;
}
*buf_out = NULL;
int pos, len;
int64_t pts = in->s.start;
// There are a 3 scenarios that can happen here.
// 1. The buffer contains exactly one frame of data
// 2. The buffer contains multiple frames of data
// 3. The buffer contains a partial frame of data
//
// In scenario 2, we want to be sure that the timestamps are only
// applied to the first frame in the buffer. Additional frames
// in the buffer will have their timestamps computed in sync.
//
// In scenario 3, we need to save the ancillary buffer info of an
// unfinished frame so it can be applied when we receive the last
// buffer of that frame.
if (!pv->unfinished)
{
// New packet, and no previous data pending
pv->packet_info.scr_sequence = in->s.scr_sequence;
pv->packet_info.new_chap = in->s.new_chap;
pv->packet_info.frametype = in->s.frametype;
pv->packet_info.discard = !!(in->s.flags & HB_FLAG_DISCARD);
}
for (pos = 0; pos < in->size; pos += len)
{
uint8_t * pout = NULL;
int pout_len = 0;
int64_t parser_pts;
if ( pv->parser != NULL )
{
len = av_parser_parse2(pv->parser, pv->context, &pout, &pout_len,
in->data + pos, in->size - pos,
pts, pts, 0 );
parser_pts = pv->parser->pts;
pts = AV_NOPTS_VALUE;
}
else
{
pout = in->data;
len = pout_len = in->size;
parser_pts = in->s.start;
}
if (pout != NULL && pout_len > 0)
{
pv->packet_info.data = pout;
pv->packet_info.size = pout_len;
pv->packet_info.pts = parser_pts;
decodeAudio(pv, &pv->packet_info);
// There could have been an unfinished packet when we entered
// decodeAudio that is now finished. The next packet is associated
// with the input buffer, so set it's chapter and scr info.
pv->packet_info.scr_sequence = in->s.scr_sequence;
pv->packet_info.discard = !!(in->s.flags & HB_FLAG_DISCARD);
pv->unfinished = 0;
}
if (len > 0 && pout_len <= 0)
{
pv->unfinished = 1;
}
}
*buf_out = hb_buffer_list_clear(&pv->list);
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.num = context->time_base.num;
info->rate.den = context->time_base.den;
info->profile = context->profile;
info->level = context->level;
return 1;
}
return 0;
}
static int parse_adts_extradata( hb_audio_t * audio, AVCodecContext * context,
AVPacket * pkt )
{
const AVBitStreamFilter * bsf;
AVBSFContext * ctx = NULL;
int ret;
bsf = av_bsf_get_by_name("aac_adtstoasc");
ret = av_bsf_alloc(bsf, &ctx);
if (ret < 0)
{
hb_error("decavcodec: bitstream filter alloc failure");
return ret;
}
ctx->time_base_in.num = 1;
ctx->time_base_in.den = audio->config.out.samplerate;
avcodec_parameters_from_context(ctx->par_in, context);
ret = av_bsf_init(ctx);
if (ret < 0)
{
hb_error("decavcodec: bitstream filter init failure");
av_bsf_free(&ctx);
return ret;
}
ret = av_bsf_send_packet(ctx, pkt);
if (ret < 0)
{
hb_error("decavcodec: av_bsf_send_packet failure");
av_bsf_free(&ctx);
return ret;
}
ret = av_bsf_receive_packet(ctx, pkt);
av_bsf_free(&ctx);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
{
return 0;
}
else if (ret < 0)
{
if (ret != AVERROR_INVALIDDATA)
{
hb_error("decavcodec: av_bsf_receive_packet failure %x", -ret);
}
return ret;
}
if (audio->priv.config.extradata.length == 0)
{
const uint8_t * extradata;
int size;
extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
&size);
if (extradata != NULL && size > 0)
{
int len;
len = MIN(size, HB_CONFIG_MAX_SIZE);
memcpy(audio->priv.config.extradata.bytes, extradata, len);
audio->priv.config.extradata.length = len;
}
}
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 result = 0, done = 0;
hb_audio_t *audio = w->audio;
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 && w->title->opaque_priv != NULL)
{
AVFormatContext *ic = (AVFormatContext*)w->title->opaque_priv;
avcodec_parameters_to_context(context,
ic->streams[audio->id]->codecpar);
// 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 );
AVDictionary * av_opts = NULL;
av_dict_set( &av_opts, "err_detect", "crccheck+explode", 0 );
if ( hb_avcodec_open( context, codec, &av_opts, 0 ) )
{
av_dict_free( &av_opts );
return -1;
}
if (audio != NULL)
{
context->pkt_timebase.num = audio->config.in.timebase.num;
context->pkt_timebase.den = audio->config.in.timebase.den;
}
av_dict_free( &av_opts );
unsigned char *parse_buffer;
int parse_pos, parse_buffer_size;
while (buf != NULL && !done)
{
parse_pos = 0;
while (parse_pos < buf->size && !done)
{
int parse_len, truehd_mono = 0, ret;
if (parser != NULL)
{
parse_len = av_parser_parse2(parser, context,
&parse_buffer, &parse_buffer_size,
buf->data + parse_pos, buf->size - parse_pos,
buf->s.start, buf->s.start, 0);
}
else
{
parse_buffer = buf->data + parse_pos;
parse_len = parse_buffer_size = buf->size - parse_pos;
}
if (parse_buffer_size == 0)
{
parse_pos += parse_len;
continue;
}
// 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_channel_layout = AV_CH_LAYOUT_STEREO;
}
else
{
context->request_channel_layout = 0;
}
AVPacket avp;
av_init_packet(&avp);
avp.data = parse_buffer;
avp.size = parse_buffer_size;
ret = avcodec_send_packet(context, &avp);
if (ret < 0 && ret != AVERROR_EOF)
{
parse_pos += parse_len;
av_packet_unref(&avp);
continue;
}
AVFrame *frame = NULL;
do
{
if (frame == NULL)
{
frame = av_frame_alloc();
}
ret = avcodec_receive_frame(context, frame);
if (ret >= 0)
{
// libavcoded doesn't consistently set frame->sample_rate
if (frame->sample_rate != 0)
{
info->rate.num = frame->sample_rate;
}
else
{
info->rate.num = context->sample_rate;
hb_log("decavcodecaBSInfo: warning: invalid frame sample_rate! Using context sample_rate.");
}
info->rate.den = 1;
info->samples_per_frame = frame->nb_samples;
info->sample_bit_depth = context->bits_per_raw_sample;
int bps = av_get_bits_per_sample(context->codec_id);
int channels;
if (frame->channel_layout != 0)
{
channels = av_get_channel_layout_nb_channels(
frame->channel_layout);
}
else
{
channels = frame->channels;
}
info->bitrate = bps * channels * info->rate.num;
if (info->bitrate <= 0)
{
if (context->bit_rate > 0)
{
info->bitrate = context->bit_rate;
}
else
{
info->bitrate = 1;
}
}
if (truehd_mono)
{
info->channel_layout = AV_CH_LAYOUT_MONO;
info->matrix_encoding = AV_MATRIX_ENCODING_NONE;
}
else
{
AVFrameSideData *side_data;
if ((side_data =
av_frame_get_side_data(frame,
AV_FRAME_DATA_MATRIXENCODING)) != NULL)
{
info->matrix_encoding = *side_data->data;
}
else
{
info->matrix_encoding = AV_MATRIX_ENCODING_NONE;
}
if (info->matrix_encoding == AV_MATRIX_ENCODING_DOLBY ||
info->matrix_encoding == AV_MATRIX_ENCODING_DPLII)
{
info->channel_layout = AV_CH_LAYOUT_STEREO_DOWNMIX;
}
else
{
info->channel_layout = frame->channel_layout;
}
}
if (info->channel_layout == 0)
{
// Channel layout was not set. Guess a layout based
// on number of channels.
info->channel_layout = av_get_default_channel_layout(
frame->channels);
}
if (context->codec_id == AV_CODEC_ID_AC3 ||
context->codec_id == AV_CODEC_ID_EAC3)
{
if (context->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE)
{
info->mode = 7;
}
else
{
info->mode = context->audio_service_type;
}
}
else if (context->codec_id == AV_CODEC_ID_AAC &&
context->extradata_size == 0)
{
// Parse ADTS AAC streams for AudioSpecificConfig.
// This data is required in order to write
// proper headers in MP4, WebM, and MKV files.
parse_adts_extradata(audio, context, &avp);
}
result = 1;
done = 1;
av_frame_unref(frame);
break;
}
} while (ret >= 0);
av_packet_unref(&avp);
av_frame_free(&frame);
parse_pos += parse_len;
}
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_free_context(&context);
return result;
}
reordered_data_t *
reordered_hash_rem(hb_work_private_t * pv, int64_t sequence)
{
reordered_data_t * reordered;
int slot = sequence & REORDERED_HASH_MASK;
reordered = pv->reordered_hash[slot];
if (reordered == NULL)
{
// This shouldn't happen...
// But, this happens sometimes when libav outputs exactly the same
// frame twice for some reason.
hb_deep_log(3, "decavcodec: missing sequence %"PRId64"", sequence);
}
pv->reordered_hash[slot] = NULL;
return reordered;
}
void
reordered_hash_add(hb_work_private_t * pv, reordered_data_t * reordered)
{
int slot = reordered->sequence & REORDERED_HASH_MASK;
// Free any unused previous entries.
// This can happen due to libav parser feeding partial
// frames data to the decoder.
// It can also happen due to decoding errors.
free(pv->reordered_hash[slot]);
pv->reordered_hash[slot] = reordered;
}
/* -------------------------------------------------------------
* General purpose video decoder using libavcodec
*/
// send cc_buf to the CC decoder(s)
static void cc_send_to_decoder(hb_work_private_t *pv, hb_buffer_t *buf)
{
if (buf == NULL)
return;
// if there's more than one decoder for the captions send a copy
// of the buffer to all.
hb_subtitle_t *subtitle;
int ii = 0, n = hb_list_count(pv->list_subtitle);
while (--n > 0)
{
// make a copy of the buf then forward it to the decoder
hb_buffer_t *cpy = hb_buffer_dup(buf);
subtitle = hb_list_item(pv->list_subtitle, ii++);
hb_fifo_push(subtitle->fifo_in, cpy);
}
subtitle = hb_list_item(pv->list_subtitle, ii);
hb_fifo_push( subtitle->fifo_in, buf );
}
static hb_buffer_t * cc_fill_buffer(hb_work_private_t *pv, uint8_t *cc, int size)
{
int cc_count[4] = {0,};
int ii;
hb_buffer_t *buf = NULL;
for (ii = 0; ii < size; ii += 3)
{
if ((cc[ii] & 0x04) == 0) // not valid
continue;
if ((cc[ii+1] & 0x7f) == 0 && (cc[ii+2] & 0x7f) == 0) // stuffing
continue;
int type = cc[ii] & 0x03;
cc_count[type]++;
}
// Only handles CC1 for now.
if (cc_count[0] > 0)
{
buf = hb_buffer_init(cc_count[0] * 2);
int jj = 0;
for (ii = 0; ii < size; ii += 3)
{
if ((cc[ii] & 0x04) == 0) // not valid
continue;
if ((cc[ii+1] & 0x7f) == 0 && (cc[ii+2] & 0x7f) == 0) // stuffing
continue;
int type = cc[ii] & 0x03;
if (type == 0)
{
buf->data[jj++] = cc[ii+1];
buf->data[jj++] = cc[ii+2];
}
}
}
return buf;
}
// 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 )
{
reordered_data_t * reordered = NULL;
hb_buffer_t * out;
#if HB_PROJECT_FEATURE_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_VIDEO_MEMORY)
{
out = hb_qsv_copy_frame(pv->frame, pv->job->qsv.ctx);
}
else
#endif
{
out = hb_avframe_to_video_buffer(pv->frame, (AVRational){1,1});
}
if (pv->frame->pts != AV_NOPTS_VALUE)
{
reordered = reordered_hash_rem(pv, pv->frame->pts);
}
if (reordered != NULL)
{