forked from rofafor/vdr-plugin-vaapidevice
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcodec.c
2596 lines (2373 loc) · 78.8 KB
/
codec.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
///
/// @file codec.c @brief Codec functions
///
/// Copyright (c) 2009 - 2015 by Johns. All Rights Reserved.
///
/// Contributor(s):
///
/// License: AGPLv3
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Affero General Public License as
/// published by the Free Software Foundation, either version 3 of the
/// License.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Affero General Public License for more details.
///
/// $Id$
//////////////////////////////////////////////////////////////////////////////
///
/// @defgroup Codec The codec module.
///
/// This module contains all decoder and codec functions.
/// It is uses ffmpeg (http://ffmpeg.org) as backend.
///
/// It may work with libav (http://libav.org), but the tests show
/// many bugs and incompatiblity in it. Don't use this shit.
///
/// compile with pass-through support (stable, AC-3, E-AC-3 only)
#define USE_PASSTHROUGH
/// compile audio drift correction support (very experimental)
#define USE_AUDIO_DRIFT_CORRECTION
/// compile AC-3 audio drift correction support (very experimental)
#define USE_AC3_DRIFT_CORRECTION
/// use ffmpeg libswresample API (autodected, Makefile)
#define noUSE_SWRESAMPLE
/// use libav libavresample API (autodected, Makefile)
#define noUSE_AVRESAMPLE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __FreeBSD__
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <libintl.h>
#define _(str) gettext(str) ///< gettext shortcut
#define _N(str) str ///< gettext_noop shortcut
#include <libavcodec/avcodec.h>
#include <libavutil/mem.h>
#include <libavutil/pixdesc.h>
// support old ffmpeg versions <1.0
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,18,102)
#define AVCodecID CodecID
#define AV_CODEC_ID_MP2 CODEC_ID_MP2
#define AV_CODEC_ID_AC3 CODEC_ID_AC3
#define AV_CODEC_ID_EAC3 CODEC_ID_EAC3
#define AV_CODEC_ID_DTS CODEC_ID_DTS
#define AV_CODEC_ID_MPEG2VIDEO CODEC_ID_MPEG2VIDEO
#define AV_CODEC_ID_H264 CODEC_ID_H264
#endif
#ifdef USE_VAAPI
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,74,100)
#include <libavcodec/vaapi.h>
#endif
#endif
#ifdef USE_VDPAU
#include <libavcodec/vdpau.h>
#endif
#ifdef USE_SWRESAMPLE
#include <libswresample/swresample.h>
#endif
#ifdef USE_AVRESAMPLE
#include <libavresample/avresample.h>
#endif
#ifdef USE_AVFILTER
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#endif
#include <libavutil/opt.h>
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,7,100)
#define CODEC_CAP_HWACCEL_VDPAU AV_CODEC_CAP_HWACCEL_VDPAU
#define CODEC_CAP_TRUNCATED AV_CODEC_CAP_TRUNCATED
#define CODEC_CAP_DR1 AV_CODEC_CAP_DR1
#define CODEC_CAP_FRAME_THREADS AV_CODEC_CAP_FRAME_THREADS
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <pthread.h>
#include "iatomic.h"
#include "misc.h"
#include "video.h"
#include "audio.h"
#include "codec.h"
//----------------------------------------------------------------------------
// correct is AV_VERSION_INT(56,35,101) but some gentoo i* think
// they must change it.
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,26,100) && LIBAVCODEC_VERSION_INT < AV_VERSION_INT(56,60,100)
/// ffmpeg 2.6 started to show artifacts after channel switch
/// to SDTV channels
#define FFMPEG_WORKAROUND_ARTIFACTS 1
#endif
/// artifacts with VDPAU when codec flushed
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
#define FFMPEG_4_WORKAROUND_ARTIFACTS 1
#endif
//----------------------------------------------------------------------------
// Global
//----------------------------------------------------------------------------
///
/// ffmpeg lock mutex
///
/// new ffmpeg dislikes simultanous open/close
/// this breaks our code, until this is fixed use lock.
///
static pthread_mutex_t CodecLockMutex;
/// Flag prefer fast channel switch
char CodecUsePossibleDefectFrames;
//----------------------------------------------------------------------------
// Video
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Call-backs
//----------------------------------------------------------------------------
/**
** Callback to negotiate the PixelFormat.
**
** @param video_ctx codec context
** @param fmt is the list of formats which are supported by
** the codec, it is terminated by -1 as 0 is a
** valid format, the formats are ordered by
** quality.
*/
static enum AVPixelFormat Codec_get_format(AVCodecContext * video_ctx,
const enum AVPixelFormat *fmt)
{
VideoDecoder *decoder;
decoder = video_ctx->opaque;
#if LIBAVCODEC_VERSION_INT == AV_VERSION_INT(54,86,100)
// this begins to stink, 1.1.2 calls get_format for each frame
// 1.1.3 has the same version, but works again
if (decoder->GetFormatDone) {
if (decoder->GetFormatDone < 10) {
++decoder->GetFormatDone;
Error
("codec/video: ffmpeg/libav buggy: get_format called again\n");
}
return *fmt; // FIXME: this is hack
}
#endif
// bug in ffmpeg 1.1.1, called with zero width or height
if (!video_ctx->width || !video_ctx->height) {
Error("codec/video: ffmpeg/libav buggy: width or height zero\n");
}
return Video_get_format(decoder->HwDecoder, video_ctx, fmt);
}
static void Codec_free_buffer(void *opaque, uint8_t *data);
/**
** Video buffer management, get buffer for frame.
**
** Called at the beginning of each frame to get a buffer for it.
**
** @param video_ctx Codec context
** @param frame Get buffer for this frame
*/
static int Codec_get_buffer2(AVCodecContext * video_ctx, AVFrame * frame, int flags)
{
VideoDecoder *decoder;
decoder = video_ctx->opaque;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(54,86,100)
// ffmpeg has this already fixed
// libav 0.8.5 53.35.0 still needs this
#endif
if (!decoder->GetFormatDone) { // get_format missing
enum AVPixelFormat fmts[2];
fprintf(stderr, "codec: buggy libav, use ffmpeg\n");
Warning(_("codec: buggy libav, use ffmpeg\n"));
fmts[0] = video_ctx->pix_fmt;
fmts[1] = AV_PIX_FMT_NONE;
Codec_get_format(video_ctx, fmts);
}
#ifdef USE_VDPAU
#if LIBAVUTIL_VERSION_MAJOR < 56
// VDPAU: AV_PIX_FMT_VDPAU_H264 .. AV_PIX_FMT_VDPAU_VC1 AV_PIX_FMT_VDPAU_MPEG4
if ((AV_PIX_FMT_VDPAU_H264 <= video_ctx->pix_fmt
&& video_ctx->pix_fmt <= AV_PIX_FMT_VDPAU_VC1)
|| video_ctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG4) {
unsigned surface;
struct vdpau_render_state *vrs;
surface = VideoGetSurface(decoder->HwDecoder, video_ctx);
vrs = av_mallocz(sizeof(struct vdpau_render_state));
vrs->surface = surface;
//Debug(3, "codec: use surface %#010x\n", surface);
// render
frame->buf[0] = av_buffer_create((uint8_t*)vrs, 0, Codec_free_buffer, video_ctx, 0);
frame->data[0] = frame->buf[0]->data;
frame->data[1] = NULL;
frame->data[2] = NULL;
frame->data[3] = NULL;
return 0;
}
#endif
#endif
// VA-API and new VDPAU:
if (video_ctx->hw_frames_ctx || video_ctx->hwaccel_context) {
unsigned surface;
surface = VideoGetSurface(decoder->HwDecoder, video_ctx);
//Debug(3, "codec: use surface %#010x\n", surface);
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(52,48,101)
frame->type = FF_BUFFER_TYPE_USER;
#endif
#if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(53,46,0)
frame->age = 256 * 256 * 256 * 64;
#endif
// vaapi needs both fields set
frame->buf[0] = av_buffer_create((uint8_t*)(size_t)surface, 0, Codec_free_buffer, video_ctx, 0);
frame->data[0] = frame->buf[0]->data;
frame->data[3] = frame->data[0];
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(52,66,100)
// reordered frames
if (video_ctx->pkt) {
frame->pkt_pts = video_ctx->pkt->pts;
} else {
frame->pkt_pts = AV_NOPTS_VALUE;
}
#endif
return 0;
}
//Debug(3, "codec: fallback to default get_buffer\n");
return avcodec_default_get_buffer2(video_ctx, frame, flags);
}
/**
** Video buffer management, release buffer for frame.
** Called to release buffers which were allocated with get_buffer.
**
** @param opaque opaque data
** @param data buffer data
*/
static void Codec_free_buffer(void *opaque, uint8_t *data)
{
AVCodecContext *video_ctx = (AVCodecContext *)opaque;
#ifdef USE_VDPAU
#if LIBAVUTIL_VERSION_MAJOR < 56
// VDPAU: AV_PIX_FMT_VDPAU_H264 .. AV_PIX_FMT_VDPAU_VC1 AV_PIX_FMT_VDPAU_MPEG4
if ((AV_PIX_FMT_VDPAU_H264 <= video_ctx->pix_fmt
&& video_ctx->pix_fmt <= AV_PIX_FMT_VDPAU_VC1)
|| video_ctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG4) {
VideoDecoder *decoder;
struct vdpau_render_state *vrs;
unsigned surface;
decoder = video_ctx->opaque;
vrs = (struct vdpau_render_state *)data;
surface = vrs->surface;
//Debug(3, "codec: release surface %#010x\n", surface);
VideoReleaseSurface(decoder->HwDecoder, surface);
av_freep(&vrs->bitstream_buffers);
vrs->bitstream_buffers_allocated = 0;
av_freep(&data);
return;
}
#endif
#endif
// VA-API and new VDPAU
if (video_ctx->hw_frames_ctx || video_ctx->hwaccel_context) {
VideoDecoder *decoder;
unsigned surface;
decoder = video_ctx->opaque;
surface = (unsigned)(size_t) data;
//Debug(3, "codec: release surface %#010x\n", surface);
VideoReleaseSurface(decoder->HwDecoder, surface);
return;
}
}
/// libav: compatibility hack
#ifndef AV_NUM_DATA_POINTERS
#define AV_NUM_DATA_POINTERS 4
#endif
/**
** Draw a horizontal band.
**
** @param video_ctx Codec context
** @param frame draw this frame
** @param y y position of slice
** @param type 1->top field, 2->bottom field, 3->frame
** @param offset offset into AVFrame.data from which slice
** should be read
** @param height height of slice
*/
static void Codec_draw_horiz_band(AVCodecContext * video_ctx,
const AVFrame * frame, __attribute__ ((unused))
int offset[AV_NUM_DATA_POINTERS], __attribute__ ((unused))
int y, __attribute__ ((unused))
int type, __attribute__ ((unused))
int height)
{
(void)video_ctx;
(void)frame;
#ifdef USE_VDPAU
#if LIBAVUTIL_VERSION_MAJOR < 56
// VDPAU: AV_PIX_FMT_VDPAU_H264 .. AV_PIX_FMT_VDPAU_VC1 AV_PIX_FMT_VDPAU_MPEG4
if ((AV_PIX_FMT_VDPAU_H264 <= video_ctx->pix_fmt
&& video_ctx->pix_fmt <= AV_PIX_FMT_VDPAU_VC1)
|| video_ctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG4) {
VideoDecoder *decoder;
struct vdpau_render_state *vrs;
//unsigned surface;
decoder = video_ctx->opaque;
vrs = (struct vdpau_render_state *)frame->data[0];
//surface = vrs->surface;
//Debug(3, "codec: draw slice surface %#010x\n", surface);
//Debug(3, "codec: %d references\n", vrs->info.h264.num_ref_frames);
VideoDrawRenderState(decoder->HwDecoder, vrs);
return;
}
#endif
#endif
}
//----------------------------------------------------------------------------
// Test
//----------------------------------------------------------------------------
/**
** Allocate a new video decoder context.
**
** @param hw_decoder video hardware decoder
**
** @returns private decoder pointer for video decoder.
*/
VideoDecoder *CodecVideoNewDecoder(VideoHwDecoder * hw_decoder)
{
VideoDecoder *decoder;
if (!(decoder = calloc(1, sizeof(*decoder)))) {
Fatal(_("codec: can't allocate vodeo decoder\n"));
}
decoder->HwDecoder = hw_decoder;
return decoder;
}
/**
** Deallocate a video decoder context.
**
** @param decoder private video decoder
*/
void CodecVideoDelDecoder(VideoDecoder * decoder)
{
free(decoder);
}
#ifdef USE_AVFILTER
/**
** Init video filter.
**
** @param decoder private video decoder
** @param hardware enable hardware filter
*/
int CodecVideoInitFilter(VideoDecoder * decoder, const char *filter_descr)
{
char args[512];
int ret = 0;
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
const AVFilter *buffersink = avfilter_get_by_name("buffersink");
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(59,40,100)
enum AVPixelFormat pix_fmts[] = { decoder->VideoCtx->pix_fmt, AV_PIX_FMT_NONE };
#endif
if (!filter_descr) {
Error(_("codec: filter not described, filter disabled\n"));
ret = -1;
goto end;
}
// free filter if hardware decoder failed
if (decoder->filter_graph) {
avfilter_graph_free(&decoder->filter_graph);
}
decoder->filter_graph = avfilter_graph_alloc();
if (!outputs || !inputs || !decoder->filter_graph) {
ret = AVERROR(ENOMEM);
goto end;
}
#if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(9,16,100)
snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
decoder->VideoCtx->width, decoder->VideoCtx->height, decoder->VideoCtx->pix_fmt,
decoder->VideoCtx->pkt_timebase.num, decoder->VideoCtx->pkt_timebase.den,
decoder->VideoCtx->sample_aspect_ratio.num, decoder->VideoCtx->sample_aspect_ratio.den);
#else
snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d:colorspace=%d:range=%d",
decoder->VideoCtx->width, decoder->VideoCtx->height, decoder->VideoCtx->pix_fmt,
decoder->VideoCtx->pkt_timebase.num, decoder->VideoCtx->pkt_timebase.den,
decoder->VideoCtx->sample_aspect_ratio.num, decoder->VideoCtx->sample_aspect_ratio.den,
decoder->VideoCtx->colorspace,decoder->VideoCtx->color_range);
#endif
Debug(3,"codec: filter %s init args: %s\n", filter_descr, args);
decoder->buffersrc_ctx = avfilter_graph_alloc_filter(decoder->filter_graph, buffersrc, "in");
if (!decoder->buffersrc_ctx) {
Error(_("Cannot alloc buffer source %s\n"), args);
goto end;
}
if (decoder->active_hwaccel_id != HWACCEL_NONE) {
AVBufferSrcParameters *params = av_buffersrc_parameters_alloc();
if (!params) goto end;
params->hw_frames_ctx = decoder->VideoCtx->hw_frames_ctx;
ret = av_buffersrc_parameters_set(decoder->buffersrc_ctx, params);
av_free(params);
if (ret < 0) {
Debug(3, "Cannot set hw_frames_ctx to src\n");
goto end;
}
}
ret = avfilter_init_str(decoder->buffersrc_ctx, args);
if (ret < 0) {
Error(_("Cannot init buffer source %s\n"), args);
goto end;
}
ret = avfilter_graph_create_filter(&decoder->buffersink_ctx, buffersink, "out",
NULL, NULL, decoder->filter_graph);
if (ret < 0) {
Error(_("codec: cannot create buffer sink\n"));
goto end;
}
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(59,40,100)
ret = av_opt_set_int_list(decoder->buffersink_ctx, "pix_fmts", pix_fmts,
AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
Error(_("codec: cannot set output pixel format\n"));
goto end;
}
#endif
outputs->name = av_strdup("in");
outputs->filter_ctx = decoder->buffersrc_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
inputs->name = av_strdup("out");
inputs->filter_ctx = decoder->buffersink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
ret = avfilter_graph_parse_ptr(decoder->filter_graph, filter_descr, &inputs, &outputs, NULL);
if (ret < 0) {
Error(_("codec: cannot parse ptr filter graph\n"));
goto end;
}
ret = avfilter_graph_config(decoder->filter_graph, NULL);
if (ret < 0) {
Error(_("codec: cannot config filter graph %d\n"),ret);
goto end;
}
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
if (!(decoder->Filt_Frame = av_frame_alloc())) {
Error(_("codec: can't allocate video filter frame buffer\n"));
ret = -1;
goto end;
}
#else
if (!(decoder->Filt_Frame = avcodec_alloc_frame())) {
Error(_("codec: can't allocate video filter frame buffer\n"));
ret = -1;
goto end;
}
#endif
end:
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
if (ret < 0)
avfilter_graph_free(&decoder->filter_graph);
return ret;
}
#endif
/**
** Open video decoder.
**
** @param decoder private video decoder
** @param codec_id video codec id
*/
int CodecVideoOpen(VideoDecoder * decoder, int codec_id)
{
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59,0,100)
AVCodec *video_codec;
#else
const AVCodec *video_codec;
#endif
const char *name;
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
AVCodecParserContext *parser = NULL;
#endif
Debug(3, "codec: using video codec ID %#06x (%s)\n", codec_id,
avcodec_get_name(codec_id));
if (decoder->VideoCtx) {
Error(_("codec: missing close\n"));
}
name = NULL;
if (VideoIsDriverVdpau()) {
switch (codec_id) {
case AV_CODEC_ID_MPEG2VIDEO:
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,89,100)
name = VideoHardwareDecoder > HWmpeg2Off ? "mpegvideo_vdpau" : NULL;
#else
name = VideoHardwareDecoder > HWmpeg2Off ? "mpeg2video" : NULL;
#endif
break;
case AV_CODEC_ID_H264:
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,89,100)
name = VideoHardwareDecoder ? "h264_vdpau" : NULL;
#else
name = VideoHardwareDecoder ? "h264" : NULL;
#endif
break;
case AV_CODEC_ID_HEVC:
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57,89,100)
name = VideoHardwareDecoder > HWhevcOff? "hevc" : NULL; //Nvidia fix vdpau hevc in 4xx driver, Radeon can vdpau hevc
#endif
break;
}
}
if (VideoIsDriverCuvid()) {
switch (codec_id) {
case AV_CODEC_ID_MPEG2VIDEO:
name = VideoHardwareDecoder > HWmpeg2Off ? "mpeg2_cuvid" : NULL;
break;
case AV_CODEC_ID_H264:
name = VideoHardwareDecoder ? "h264_cuvid" : NULL;
break;
case AV_CODEC_ID_HEVC:
name = VideoHardwareDecoder ? "hevc_cuvid" : NULL;
break;
}
}
if (name && (video_codec = avcodec_find_decoder_by_name(name))) {
Debug(3, "codec: hw decoder found\n");
} else if (!(video_codec = avcodec_find_decoder(codec_id))) {
Error(_("codec: codec ID %#06x not found\n"), codec_id);
return 0;
}
decoder->VideoCodec = video_codec;
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
if (!VideoIsDriverCuvid() && codec_id == AV_CODEC_ID_MPEG2VIDEO) {
parser = av_parser_init(codec_id);
if (!parser)
Error(_("codec: can't init parser\n"));
}
decoder->parser = parser;
#endif
if (!(decoder->VideoCtx = avcodec_alloc_context3(video_codec))) {
Error(_("codec: can't allocate video codec context\n"));
decoder->VideoCodec = NULL;
return 0;
}
// FIXME: for software decoder use all cpus, otherwise 1
decoder->VideoCtx->thread_count = 1;
decoder->VideoCtx->pkt_timebase.num = 1;
decoder->VideoCtx->pkt_timebase.den = 90000;
#if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(60,16,101)
if (strstr(decoder->VideoCodec->name, "cuvid"))
av_opt_set_int(decoder->VideoCtx->priv_data, "surfaces", codec_id == AV_CODEC_ID_MPEG2VIDEO ? 10 : 21, 0);
#else
decoder->VideoCtx->extra_hw_frames = 5;
#endif
pthread_mutex_lock(&CodecLockMutex);
// open codec
#if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(53,5,0)
if (avcodec_open(decoder->VideoCtx, video_codec) < 0) {
pthread_mutex_unlock(&CodecLockMutex);
Error(_("codec: can't open video codec!\n"));
decoder->VideoCodec = NULL;
return 0;
}
#else
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,00,100)
if (video_codec->capabilities & (AV_CODEC_CAP_HWACCEL_VDPAU |
CODEC_CAP_HWACCEL)) {
Debug(3, "codec: video mpeg hack active\n");
// HACK around badly placed checks in mpeg_mc_decode_init
// taken from mplayer vd_ffmpeg.c
decoder->VideoCtx->slice_flags =
SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
decoder->VideoCtx->active_thread_type = 0;
}
#endif
if (avcodec_open2(decoder->VideoCtx, video_codec, NULL) < 0) {
pthread_mutex_unlock(&CodecLockMutex);
Error(_("codec: can't open video codec!\n"));
decoder->VideoCodec = NULL;
return 0;
}
#endif
pthread_mutex_unlock(&CodecLockMutex);
decoder->VideoCtx->opaque = decoder; // our structure
Debug(3, "codec: video '%s'\n", decoder->VideoCodec->long_name);
// if (codec_id == AV_CODEC_ID_H264) {
// 2.53 Ghz CPU is too slow for this codec at 1080i
//decoder->VideoCtx->skip_loop_filter = AVDISCARD_ALL;
//decoder->VideoCtx->skip_loop_filter = AVDISCARD_BIDIR;
// }
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(59,8,100)
if (video_codec->capabilities & AV_CODEC_CAP_TRUNCATED) {
Debug(3, "codec: video can use truncated packets\n");
//#ifndef USE_MPEG_COMPLETE
// we send incomplete frames, for old PES recordings
// this breaks the decoder for some stations
decoder->VideoCtx->flags |= AV_CODEC_FLAG_TRUNCATED;
//#endif
}
#endif
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,55,100)
if (VideoIsDriverNVdec()) {
decoder->VideoCtx->hwaccel_flags |= AV_HWACCEL_FLAG_UNSAFE_OUTPUT;
}
#endif
// FIXME: own memory management for video frames.
if (video_codec->capabilities & AV_CODEC_CAP_DR1) {
Debug(3, "codec: can use own buffer management\n");
}
#ifdef CODEC_CAP_FRAME_THREADS
if (video_codec->capabilities & AV_CODEC_CAP_FRAME_THREADS) {
Debug(3, "codec: codec supports frame threads\n");
}
#endif
//decoder->VideoCtx->debug = FF_DEBUG_STARTCODE;
//decoder->VideoCtx->err_recognition |= AV_EF_EXPLODE;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,00,100)
if ((video_codec->capabilities & (AV_CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_HWACCEL)) &&
#else
if (avcodec_get_hw_config(video_codec, 0) &&
#endif
VideoHardwareDecoder && !(codec_id == AV_CODEC_ID_MPEG2VIDEO
&& VideoHardwareDecoder == HWmpeg2Off) && !VideoIsDriverCpu()) {
Debug(3, "codec: can export data for HW decoding\n");
// FIXME: get_format never called.
decoder->VideoCtx->get_format = Codec_get_format;
if (!VideoIsDriverNVdec())
decoder->VideoCtx->get_buffer2 = Codec_get_buffer2;
decoder->VideoCtx->draw_horiz_band = Codec_draw_horiz_band;
decoder->VideoCtx->thread_count = 1;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,114,100)
decoder->VideoCtx->thread_safe_callbacks = 0;
#endif
decoder->VideoCtx->active_thread_type = 0;
decoder->VideoCtx->hwaccel_context =
VideoGetHwAccelContext(decoder->HwDecoder);
} else {
Debug(3, "codec: use SW decoding\n");
decoder->VideoCtx->get_format = Codec_get_format;
decoder->VideoCtx->get_buffer2 = Codec_get_buffer2;
decoder->VideoCtx->thread_count = 0;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,114,100)
decoder->VideoCtx->thread_safe_callbacks = 1;
#endif
decoder->VideoCtx->active_thread_type = 0;
decoder->VideoCtx->draw_horiz_band = NULL;
decoder->VideoCtx->hwaccel_context = NULL;
decoder->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
decoder->active_hwaccel_id = HWACCEL_NONE;
}
//
// Prepare frame buffer for decoder
//
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
if (!(decoder->Frame = av_frame_alloc())) {
Error(_("codec: can't allocate video decoder frame buffer\n"));
return 0;
}
#else
if (!(decoder->Frame = avcodec_alloc_frame())) {
Error(_("codec: can't allocate video decoder frame buffer\n"));
return 0;
}
#endif
// reset buggy ffmpeg/libav flag
decoder->GetFormatDone = 0;
#if defined FFMPEG_WORKAROUND_ARTIFACTS || defined FFMPEG_4_WORKAROUND_ARTIFACTS
decoder->FirstKeyFrame = 1;
#endif
return 1;
}
/**
** Close video decoder.
**
** @param video_decoder private video decoder
*/
void CodecVideoClose(VideoDecoder * video_decoder)
{
Debug(3, "codec: video codec close\n");
// FIXME: play buffered data
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
av_frame_free(&video_decoder->Frame); // callee does checks
#else
av_freep(&video_decoder->Frame);
#endif
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
if(video_decoder->parser) {
av_parser_close(video_decoder->parser);
video_decoder->parser = NULL;
}
#endif
if (video_decoder->VideoCtx) {
if (VideoIsDriverCuvid() || VideoIsDriverNVdec())
VideoUnregisterSurface(video_decoder->HwDecoder);
pthread_mutex_lock(&CodecLockMutex);
#ifdef USE_AVFILTER
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
av_frame_free(&video_decoder->Filt_Frame);
#else
av_freep(&video_decoder->Filt_Frame);
#endif
if (video_decoder->filter_graph) {
avfilter_graph_free(&video_decoder->filter_graph);
video_decoder->filter_graph = NULL;
}
#endif
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(55,63,100)
avcodec_close(video_decoder->VideoCtx);
av_freep(&video_decoder->VideoCtx);
#else
avcodec_free_context(&video_decoder->VideoCtx);
#endif
pthread_mutex_unlock(&CodecLockMutex);
}
}
#if 0
/**
** Display pts...
**
** ffmpeg-0.9 pts always AV_NOPTS_VALUE
** ffmpeg-0.9 pkt_pts nice monotonic (only with HD)
** ffmpeg-0.9 pkt_dts wild jumping -160 - 340 ms
**
** libav 0.8_pre20111116 pts always AV_NOPTS_VALUE
** libav 0.8_pre20111116 pkt_pts always 0 (could be fixed?)
** libav 0.8_pre20111116 pkt_dts wild jumping -160 - 340 ms
*/
void DisplayPts(AVCodecContext * video_ctx, AVFrame * frame)
{
int ms_delay;
int64_t pts;
static int64_t last_pts;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,61,100)
pts = frame->pkt_pts;
#else
pts = frame->pts;
#endif
if (pts == (int64_t) AV_NOPTS_VALUE) {
printf("*");
}
ms_delay = (1000 * video_ctx->time_base.num) / video_ctx->time_base.den;
ms_delay += frame->repeat_pict * ms_delay / 2;
printf("codec: PTS %s%s %" PRId64 " %d %d/%d %dms\n",
frame->repeat_pict ? "r" : " ", frame->interlaced_frame ? "I" : " ",
pts, (int)(pts - last_pts) / 90, video_ctx->time_base.num,
video_ctx->time_base.den, ms_delay);
if (pts != (int64_t) AV_NOPTS_VALUE) {
last_pts = pts;
}
}
#endif
/**
** Decode a video packet.
**
** @param decoder video decoder data
** @param avpkt video packet
*/
int CodecVideoDecode(VideoDecoder * decoder, const AVPacket * avpkt)
{
AVCodecContext *video_ctx;
AVFrame *frame;
int used = 0;
int got_frame = 0;
int interlaced = 0;
AVPacket pkt[1];
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
int parser_ret;
uint8_t *data;
size_t data_size;
data = avpkt->data;
data_size = avpkt->size;
#endif
video_ctx = decoder->VideoCtx;
if (video_ctx && video_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
frame = decoder->Frame;
*pkt = *avpkt; // use copy
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58,10,100)
while (data_size > 0) {
if (decoder->parser) {
parser_ret = av_parser_parse2(decoder->parser, video_ctx, &pkt->data, &pkt->size,
data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (parser_ret < 0) {
Debug(3,"parser err %d\n",parser_ret);
break;
}
data += parser_ret;
data_size -= parser_ret;
} else {
data_size = 0;
}
#endif
if (pkt->size) {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57,37,100)
used = avcodec_send_packet(video_ctx, pkt);
if (used < 0 && used != AVERROR(EAGAIN)&& used != AVERROR_EOF)
return -1;
while(!used) { //multiple frames
used = avcodec_receive_frame(video_ctx, frame);
if (used < 0 && used != AVERROR(EAGAIN) && used != AVERROR_EOF)
return -1;
if (used>=0)
got_frame = 1;
else got_frame = 0;
if (VideoIsDriverVdpau() && decoder->VideoCtx->hw_frames_ctx) {
#ifdef FFMPEG_4_WORKAROUND_ARTIFACTS
//VDPAU interlaced frames not clean after the codec flush, drop it before 2 key frames
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(58,7,100)
interlaced = video_ctx->framerate.num > 0 ? (video_ctx->framerate.num / video_ctx->framerate.den <= 30) : frame->interlaced_frame;
if (got_frame && frame->pict_type == 1 && interlaced) decoder->FirstKeyFrame++;
if (got_frame && interlaced && decoder->FirstKeyFrame < 3) got_frame = 0;
#else
interlaced = video_ctx->framerate.num > 0 ? (video_ctx->framerate.num / video_ctx->framerate.den <= 30) : frame->flags & AV_FRAME_FLAG_INTERLACED;
if (got_frame && frame->pict_type == 1 && interlaced) decoder->FirstKeyFrame++;
if (got_frame && interlaced && decoder->FirstKeyFrame < 3) got_frame = 0;
#endif
#endif
}
#else
next_part:
used = avcodec_decode_video2(video_ctx, frame, &got_frame, pkt);
#endif
Debug(4, "%s: %p %d -> %d %d\n", __FUNCTION__, pkt->data, pkt->size, used, got_frame);
if (got_frame) { // frame completed
#ifdef FFMPEG_WORKAROUND_ARTIFACTS
if (!CodecUsePossibleDefectFrames && decoder->FirstKeyFrame) {
decoder->FirstKeyFrame++;
if (frame->key_frame) {
Debug(3, "codec: key frame after %d frames\n",
decoder->FirstKeyFrame);
decoder->FirstKeyFrame = 0;
}
} else {
#endif
#ifdef USE_AVFILTER
//avfilter used for Cuvid(software), NVdec and CPU video modules
if (decoder->filter_graph) {
int ret;
if (av_buffersrc_add_frame_flags(decoder->buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
Error(_("Error while feeding the filtergraph\n"));
got_frame = 0;
}
while (got_frame) {
ret = av_buffersink_get_frame(decoder->buffersink_ctx, decoder->Filt_Frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
if (ret < 0) {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
av_frame_unref(decoder->Filt_Frame);
#endif
return -1;
}
if (decoder->Filt_Frame->pts != AV_NOPTS_VALUE)
decoder->Filt_Frame->pts /=2;
#if LIBAVUTIL_VERSION_INT < AV_VERSION_INT(58,7,100)
interlaced = frame->interlaced_frame;
decoder->Filt_Frame->interlaced_frame = 0;
#else
interlaced = frame->flags & AV_FRAME_FLAG_INTERLACED;
decoder->Filt_Frame->flags &= ~AV_FRAME_FLAG_INTERLACED;
#endif
decoder->Filt_Frame->sample_aspect_ratio = frame->sample_aspect_ratio;
// in most cases mpeg2 is interlaced and has flag issues
if (video_ctx->framerate.num > 0 && (video_ctx->framerate.num / video_ctx->framerate.den <= 30)
&& (interlaced || video_ctx->codec_id == AV_CODEC_ID_MPEG2VIDEO))
video_ctx->framerate.num *= 2;
//do not render frames when flush buffers
//avfilter not flushed when called avcodec_flush_buffers()
if(decoder->FirstKeyFrame > 1)
VideoRenderFrame(decoder->HwDecoder, video_ctx, decoder->Filt_Frame);
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56,28,1)
av_frame_unref(decoder->Filt_Frame);
#endif
}
} else
#endif
//DisplayPts(video_ctx, frame);
VideoRenderFrame(decoder->HwDecoder, video_ctx, frame);
#ifdef FFMPEG_WORKAROUND_ARTIFACTS
}
#endif
#ifdef USE_AVFILTER
//for drop avfilter output frames when flushed buffers
if (decoder->filter_graph) decoder->FirstKeyFrame++;
#endif
} else {
// some frames are needed for references, interlaced frames ...
// could happen with h264 dvb streams, just drop data.
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(60,2,100)
Debug(4, "codec: %8d incomplete interlaced frame %d bytes used\n",
video_ctx->frame_number, used);
#else
Debug(4, "codec: %8ld incomplete interlaced frame %d bytes used\n",
video_ctx->frame_num, used);
#endif
}
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,37,100)