-
Notifications
You must be signed in to change notification settings - Fork 80
/
mpeg2dec.c
executable file
·2612 lines (2236 loc) · 85.9 KB
/
mpeg2dec.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
/*
* mpeg2dec.c
* Copyright (C) 2000-2003 Michel Lespinasse <[email protected]>
* Copyright (C) 1999-2000 Aaron Holtzman <[email protected]>
*
* This file is part of mpeg2dec, a free MPEG-2 video stream decoder.
* See http://libmpeg2.sourceforge.net/ for updates.
*
* mpeg2dec is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* mpeg2dec 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "platform.h"
#include "vo.h"
#include "comskip.h"
#ifdef HAVE_SDL
#include <SDL.h>
#endif
#include <argtable2.h>
#define SELFTEST
int pass = 0;
double test_pts = 0.0;
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
//#define restrict
//#include <libavcodec/ac3dec.h>
#include <libavutil/avutil.h>
#include <libavutil/pixdesc.h>
#include <libavutil/samplefmt.h>
#include <libswscale/swscale.h>
#ifdef HARDWARE_DECODE
#include <fftools/ffmpeg.h>
const HWAccel hwaccels[] = {
#if HAVE_VDPAU_X11
{ "vdpau", vdpau_init, HWACCEL_VDPAU, AV_PIX_FMT_VDPAU },
#endif
#if HAVE_DXVA2_LIB
{ "dxva2", dxva2_init, HWACCEL_DXVA2, AV_PIX_FMT_DXVA2_VLD },
#endif
#if CONFIG_VDA
{ "vda", vda_init, HWACCEL_VDA, AV_PIX_FMT_VDA },
#endif
#if HAVE_QSV
{ "qsv", qsv_init, HWACCEL_QSV, AV_PIX_FMT_QSV },
#endif
{ 0 },
};
static InputStream inputs;
static InputStream *ist = &inputs;
#endif
extern int hardware_decode;
extern int use_cuvid;
extern int use_vdpau;
extern int use_dxva2;
extern int use_qsv;
int av_log_level=AV_LOG_INFO;
#define SDL_AUDIO_BUFFER_SIZE 1024
#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0
#define SAMPLE_CORRECTION_PERCENT_MAX 30
#define AUDIO_DIFF_AVG_NB 10
#define FF_ALLOC_EVENT (SDL_USEREVENT)
#define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
#define FF_QUIT_EVENT (SDL_USEREVENT + 2)
#define VIDEO_PICTURE_QUEUE_SIZE 1
#define DEFAULT_AV_SYNC_TYPE AV_SYNC_ADUIO_MASTER
typedef struct VideoPicture
{
int width, height; /* source height & width */
int allocated;
double pts;
} VideoPicture;
typedef struct VideoState
{
AVFormatContext *pFormatCtx;
AVCodecContext *dec_ctx, *audio_ctx, *subtitle_ctx;
int videoStream, audioStream, subtitleStream;
int av_sync_type;
// double external_clock; /* external clock base */
// int64_t external_clock_time;
int seek_req;
int seek_by_bytes;
int seek_no_flush;
double seek_pts;
int seek_flags;
int64_t seek_pos;
double audio_clock;
AVStream *audio_st;
AVStream *subtitle_st;
//DECLARE_ALIGNED(16, uint8_t, audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2]);
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;
AVPacket audio_pkt_temp;
// uint8_t *audio_pkt_data;
// int audio_pkt_size;
int audio_hw_buf_size;
double audio_diff_cum; /* used for AV difference average computation */
double audio_diff_avg_coef;
double audio_diff_threshold;
int audio_diff_avg_count;
double frame_timer;
double frame_last_pts;
double frame_last_delay;
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
double video_clock_submitted;
double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
AVStream *video_st;
AVFrame *pFrame;
char filename[1024];
int quit;
AVFrame *frame;
double duration;
double fps;
struct SwsContext *img_convert_ctx;
} VideoState;
VideoState *is;
AVDictionary *myoptions = NULL;
enum
{
AV_SYNC_AUDIO_MASTER,
AV_SYNC_VIDEO_MASTER,
AV_SYNC_EXTERNAL_MASTER,
};
/* Since we only have one decoding thread, the Big Struct
can be global in case we need it. */
VideoState *global_video_state;
AVPacket flush_pkt;
int64_t pev_best_effort_timestamp = 0;
int video_stream_index = -1;
int audio_stream_index = -1;
// int width, height;
int have_frame_rate ;
int stream_index;
int64_t best_effort_timestamp;
#define USE_ASF 1
//#include "mpeg2convert.h"
#include "comskip.h"
extern int coding_type;
extern int audio_channels;
void InitComSkip(void);
void BuildCommListAsYouGo(void);
void ReviewResult(void);
int video_packet_process(VideoState *is,AVPacket *packet);
static FILE * in_file;
static FILE * sample_file;
static FILE * timing_file = 0;
extern int lastFrameCommCalculated;
extern int thread_count;
int is_AC3;
int AC3_rate;
int AC3_mode;
int is_h264=0;
int is_AAC=0;
extern unsigned int AC3_sampling_rate; //AC3
extern int AC3_byterate;
int demux_pid=0;
int demux_asf=0;
int last_pid;
#define PIDS 100
#define PID_MASK 0x1fff
int pids[PIDS];
int pid_type[PIDS];
int pid_pcr[PIDS];
int pid_pid[PIDS];
int top_pid_count[PID_MASK+1];
int top_pid_pid;
int pid;
int selected_video_pid=0;
int selected_audio_pid=0;
int selected_subtitle_pid=0;
int selection_restart_count = 0;
int found_pids=0;
int64_t pts;
double initial_pts = 0.0;
int64_t final_pts;
double pts_offset = 0.0;
int initial_pts_set = 0;
double initial_apts;
double apts_offset = 0.0;
int initial_apts_set = 0;
int do_audio_repair = 1;
extern int timeline_repair;
//int bitrate;
int muxrate,byterate=10000;
//#define PTS_FRAME (double)(1.0 / get_fps())
//#define PTS_FRAME (int) (90000 / get_fps())
//#define SAMPLE_TO_FRAME 2.8125
//#define SAMPLE_TO_FRAME (90000.0/(get_fps() * 1000.0))
//#define BYTERATE ((int)(21400 * 25 / get_fps()))
#define FSEEK _fseeki64
#define FTELL _ftelli64
// The following two functions are undocumented and not included in any public header,
// so we need to declare them ourselves
//extern int _fseeki64(FILE *, int64_t, int);
//extern int64_t _ftelli64(FILE *);
int soft_seeking=0;
extern char inbasename[];
char pict_type;
char tempstring[512];
//test
#define DUMP_OPEN if (output_timing) { sprintf(tempstring, "%s.timing.csv", inbasename); timing_file = myfopen(tempstring, "w"); DUMP_HEADER }
#define DUMP_HEADER if (timing_file) fprintf(timing_file, "sep=,\ntype ,real_pts, step ,pts ,clock ,delta ,offset, repeat\n");
#define DUMP_TIMING(T, D, P, C, O, S) if (timing_file && !csStepping && !csJumping && !csStartJump) fprintf(timing_file, "%7s, %12.3f, %12.3f, %12.3f, %12.3f, %12.3f, %12.3f, %d\n", \
T, (double) (D), (double) calculated_delay, (double) (P), (double) (C), ((double) (P) - (double) (C)), (O), (S));
#define DUMP_CLOSE if (timing_file) { fclose(timing_file); timing_file = NULL; }
extern int skip_B_frames;
extern int lowres;
static int sigint = 0;
static int verbose = 0;
extern int selftest;
double selftest_target = 0.0;
extern int frame_count;
int framenum;
fpos_t filepos;
extern int standoff;
int64_t goppos,infopos,packpos,ptspos,headerpos,frompos,SeekPos;
extern int max_repair_size;
extern int variable_bitrate;
int max_internal_repair_size = 40;
int reviewing = 0;
int count=0;
int currentSecond=0;
int cur_hour = 0;
int cur_minute = 0;
int cur_second = 0;
extern char HomeDir[256];
extern bool processCC;
int reorderCC = 0;
extern bool live_tv;
int csRestart;
int csStartJump;
int csStepping;
int csJumping;
int csFound;
int seekIter = 0;
int seekDirection = 0;
extern FILE * out_file;
extern uint8_t ccData[500];
extern int ccDataLen;
extern int height,width, videowidth;
extern bool output_debugwindow;
extern bool output_console;
extern bool output_timing;
extern bool output_srt;
extern bool output_smi;
extern unsigned char *frame_ptr;
extern int lastFrameWasSceneChange;
extern int live_tv_retries;
extern int dvrms_live_tv_retries;
int retries;
//extern void set_fps(double frame_delay, double dfps, int ticks, double rfps, double afps);
extern void set_fps(double frame_delay);
extern void dump_video (char *start, char *end);
extern void dump_audio (char *start, char *end);
extern void Debug(int level, char* fmt, ...);
extern void dump_video_start(void);
extern void dump_audio_start(void);
void file_open();
int DetectCommercials(int, double);
int BuildMasterCommList(void);
FILE* LoadSettings(int argc, char ** argv);
void ProcessCCData(void);
void dump_data(char *start, int length);
void close_data();
static void signal_handler (int sig)
{
sigint = 1;
signal (sig, SIG_DFL);
//return (RETSIGTYPE)0;
return;
}
#define AUDIOBUFFER 1600000
static double base_apts = 0.0, apts, top_apts = 0.0;
static short audio_buffer[AUDIOBUFFER];
static short *audio_buffer_ptr = audio_buffer;
static int audio_samples = 0;
#define ISSAME(T1,T2) (fabs((T1) - (T2)) < 0.001)
//extern double fps;
static int sound_frame_counter = 0;
extern double get_fps();
extern int get_samplerate();
extern int get_channels();
extern void add_volumes(int *volumes, int nr_frames);
extern void set_frame_volume(uint32_t framenr, int volume);
extern double get_frame_pts(int f);
static int max_volume_found = 0;
int ms_audio_delay = 5;
int tracks_without_sound = 0;
int frames_without_sound = 0;
#define MAX_FRAMES_WITHOUT_SOUND 100
int frames_with_loud_sound = 0;
void list_codecs()
{
const AVCodec *p;
int * p_i = (int *)NULL;
int i = 0;
// avcodec_register_all();
p = av_codec_iterate((void **)&p_i);
printf("Decoders:\n");
printf("---------\n");
while (p != NULL) {
if (av_codec_is_decoder(p)) {
printf("%s", p->name);
i += strlen(p->name);
if (i > 80) {
printf("\n");
i = 0;
} else
printf(", ");
}
p = av_codec_iterate((void **)&p_i);
}
printf("\n");
}
int retreive_frame_volume(double from_pts, double to_pts)
{
short *buffer;
int volume = -1;
VideoState *is = global_video_state;
int i;
double calculated_delay;
int s_per_frame = (to_pts - from_pts) * (double)(is->audio_st->codecpar->sample_rate+1);
if (s_per_frame > 1 && base_apts <= from_pts && to_pts < top_apts )
{
calculated_delay = 0.0;
// Debug(1,"fame=%d, =base=%6.3f, from=%6.3f, samples=%d, to=%6.3f, top==%6.3f\n", -1, base_apts, from_pts, s_per_frame, to_pts, top_apts);
buffer = & audio_buffer[(int)((from_pts - base_apts) * ((double)is->audio_st->codecpar->sample_rate+0.5) )];
volume = 0;
if (sample_file) fprintf(sample_file, "Frame %i\n", sound_frame_counter);
for (i = 0; i < s_per_frame; i++)
{
if (sample_file) fprintf(sample_file, "%i\n", *buffer);
volume += (*buffer>0 ? *buffer : - *buffer);
buffer++;
}
volume = volume/s_per_frame;
DUMP_TIMING("a read", is->audio_clock, to_pts, from_pts, (double)volume, s_per_frame);
audio_samples -= (int)((from_pts - base_apts) * (is->audio_st->codecpar->sample_rate+0.5)); // incomplete frame before complete frame
audio_samples -= s_per_frame;
if (volume == 0)
{
frames_without_sound++;
}
else if (volume > 20000)
{
if (volume > 256000)
volume = 220000;
frames_with_loud_sound++;
volume = -1;
}
else
{
frames_without_sound = 0;
}
if (max_volume_found < volume)
max_volume_found = volume;
// Remove use samples
audio_buffer_ptr = audio_buffer;
if (audio_samples > 0)
{
for (i = 0; i < audio_samples; i++)
{
*audio_buffer_ptr++ = *buffer++;
}
}
base_apts = to_pts;
top_apts = base_apts + audio_samples / (double)(is->audio_st->codecpar->sample_rate);
sound_frame_counter++;
}
return(volume);
}
void backfill_frame_volumes()
{
int f;
int volume;
double local_initial_pts = initial_pts;
if (framenum < 3)
return;
f = framenum-2;
if (fabs(local_initial_pts) > 200)
local_initial_pts = 0;
while (get_frame_pts(f) + local_initial_pts > base_apts && f > 1) // Find first frame with samples available, could be incomplete
f--;
while (f < framenum-1 && (get_frame_pts(f+1) + local_initial_pts )<= top_apts && (top_apts - base_apts) > .2 /* && get_frame_pts(f-1) >= base_apts */) {
volume = retreive_frame_volume(fmax(get_frame_pts(f) + local_initial_pts , base_apts), get_frame_pts(f+1) + local_initial_pts);
if (volume > -1) set_frame_volume(f, volume);
f++;
}
}
int ALIGN_AC3_PACKETS=0;
void sound_to_frames(VideoState *is, short **b, int s, int c, int format)
{
int i,l;
int volume;
static int old_c = 0;
double old_base_apts;
static double old_audio_clock=0.0;
double calculated_delay = 0.0;
double avg_volume = 0.0;
int planar = av_sample_fmt_is_planar(format);
float *(fb[16]);
short *(sb[16]);
static int old_sample_rate = 0;
audio_samples = (audio_buffer_ptr - audio_buffer);
if (old_sample_rate == is->audio_st->codecpar->sample_rate &&
((audio_buffer_ptr - audio_buffer) < 0 || (audio_buffer_ptr - audio_buffer) >= AUDIOBUFFER
|| (top_apts - base_apts) * (is->audio_st->codecpar->sample_rate+0.5) > AUDIOBUFFER
|| (top_apts < base_apts)
|| !ISSAME(((double)audio_samples /(double)(is->audio_st->codecpar->sample_rate+0.5))+ base_apts, top_apts)
|| audio_samples < 0
|| audio_samples >= AUDIOBUFFER)) {
Debug(1, "Panic: Audio buffering corrupt\n");
audio_buffer_ptr = audio_buffer;
top_apts = base_apts = 0;
audio_samples=0;
return;
}
if (old_c != 0 && old_c != c) {
Debug(5, "Audio channels switched at pts=%6.5f from %d to %d\n", base_apts, old_c, c);
// InsertBlackFrame()
}
audio_channels = c;
old_c = c;
if (old_sample_rate != 0 && old_sample_rate != is->audio_st->codecpar->sample_rate) {
Debug(5, "Audio samplerate switched from %d to %d\n", old_sample_rate, is->audio_st->codecpar->sample_rate );
}
old_sample_rate = is->audio_st->codecpar->sample_rate;
old_base_apts = base_apts;
if (fabs(base_apts - (is->audio_clock - ((double)audio_samples /(double)(is->audio_st->codecpar->sample_rate))))> 0.0001)
base_apts = (is->audio_clock - ((double)audio_samples /(double)(is->audio_st->codecpar->sample_rate)));
if (ALIGN_AC3_PACKETS && is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3) {
if ( ISSAME(base_apts - old_base_apts, 0.032)
|| ISSAME(base_apts - old_base_apts, -0.032)
|| ISSAME(base_apts - old_base_apts, 0.064)
|| ISSAME(base_apts - old_base_apts, -0.064)
|| ISSAME(base_apts - old_base_apts, -0.096)
)
old_base_apts = base_apts; // Ignore AC3 packet jitter
}
if (old_base_apts != 0.0 && (fabs(base_apts - old_base_apts)>0.01)) {
Debug(8, "Jump in base apts from %6.5f to %6.5f, delta=%6.5f\n",old_base_apts, base_apts, base_apts -old_base_apts);
}
if (s+audio_samples > AUDIOBUFFER ) {
Debug(1,"Panic: Audio buffer overflow, resetting audio buffer\n");
audio_buffer_ptr = audio_buffer;
top_apts = base_apts = 0;
audio_samples=0;
return;
}
if (s > 0)
{
if (format == AV_SAMPLE_FMT_FLTP)
{
for (l=0;l < c;l++ )
{
fb[l] = (float*)b[l];
}
for (i = 0; i < s; i++)
{
volume = 0;
if (planar)
for (l=0;l < c;l++ ) volume += *((fb[l])++) * 64000;
else
for (l=0;l < c;l++ ) volume += *((fb[0])++) * 64000;
*audio_buffer_ptr++ = volume / is->audio_st->codecpar->channels;
avg_volume += abs(volume / is->audio_st->codecpar->channels);
}
}
else
{
for (l=0;l < c;l++ )
{
sb[l] = (short*)b[l];
}
for (i = 0; i < s; i++)
{
volume = 0;
if (planar)
for (l=0;l < c;l++ ) volume += *((sb[l])++);
else
for (l=0;l < c;l++ ) volume += *((sb[0])++);
*audio_buffer_ptr++ = volume / is->audio_st->codecpar->channels;
avg_volume += abs(volume / is->audio_st->codecpar->channels);
}
}
}
avg_volume /= s;
audio_samples = (audio_buffer_ptr - audio_buffer);
top_apts = base_apts + audio_samples / (double)(is->audio_st->codecpar->sample_rate);
calculated_delay = is->audio_clock - old_audio_clock;
DUMP_TIMING("a frame", is->audio_clock, top_apts, base_apts, avg_volume,s);
old_audio_clock = is->audio_clock;
backfill_frame_volumes();
}
#define AC3_BUFFER_SIZE 100000
static uint8_t ac3_packet[AC3_BUFFER_SIZE];
static int ac3_packet_index = 0;
int data_size;
int ac3_package_misalignment_count = 0;
void audio_packet_process(VideoState *is, AVPacket *pkt)
{
int prev_codec_id = -1;
int len1, data_size;
uint8_t *pp;
double prev_audio_clock;
// AC3DecodeContext *s = is->audio_st->codecpar->priv_data;
int rps,ps;
AVPacket *pkt_temp = &is->audio_pkt_temp;
int got_frame;
if (!reviewing)
{
dump_audio_start();
dump_audio((char *)pkt->data,(char *) (pkt->data + pkt->size));
}
pkt_temp->data = pkt->data;
pkt_temp->size = pkt->size;
if ( !ALIGN_AC3_PACKETS && is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3
&& ((pkt_temp->data[0] != 0x0b || pkt_temp->data[1] != 0x77)))
{
// Debug(1, "AC3 packet misaligned, audio decoding will fail\n");
ac3_package_misalignment_count++;
} else {
ac3_package_misalignment_count = 0;
}
if (!ALIGN_AC3_PACKETS && ac3_package_misalignment_count > 4) {
Debug(8, "AC3 packets misaligned, enabling AC3 re-alignment\n");
ALIGN_AC3_PACKETS = 1;
}
if (ALIGN_AC3_PACKETS && is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3) {
if (ac3_packet_index + pkt_temp->size >= AC3_BUFFER_SIZE )
{
Debug(8,"AC3 sync error\n");
return;
}
memcpy(&ac3_packet[ac3_packet_index], pkt_temp->data, pkt_temp->size);
pkt_temp->data = ac3_packet;
pkt_temp->size += ac3_packet_index;
ac3_packet_index = pkt_temp->size;
ps = 0;
while (pkt_temp->size >= 2 && (pkt_temp->data[0] != 0x0b || pkt_temp->data[1] != 0x77) ) {
pkt_temp->data++;
pkt_temp->size--;
ps++;
}
if (pkt_temp->size < 2)
return; // No packet start found
if (ps>0)
Debug(8,"Skipped %d of added %d bytes in audio input stream around frame %d\n", ps, pkt->size, framenum);
pp = pkt_temp->data;
rps = pkt_temp->size-2;
while (rps > 1 && (pp[rps] != 0x0b || pp[rps+1] != 0x77) ) {
rps--;
}
if (rps >= 2)
{
pkt_temp->size = rps;
}
else
{
// No complete packet found;
rps = pkt_temp->size;
pp = &pkt_temp->data[0];
pkt_temp->size = 0;
return;
}
if ( (pkt_temp->size % 768 ) != 0)
Debug(8,"Strange packet size of %d bytes in audio input stream around frame %d\n", rps, framenum);
}
/* Try to align on packet boundary as some demuxers don't do that, in particular dvr-ms */
if (pkt->pts != AV_NOPTS_VALUE)
{
prev_audio_clock = is->audio_clock;
is->audio_clock = av_q2d(is->audio_st->time_base)*( pkt->pts - (is->audio_st->start_time != AV_NOPTS_VALUE ? is->audio_st->start_time : 0)) - apts_offset;
if (ALIGN_AC3_PACKETS && is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3) {
if ( ISSAME(is->audio_clock - prev_audio_clock, 0.032)
|| ISSAME(is->audio_clock - prev_audio_clock, -0.032)
|| ISSAME(is->audio_clock - prev_audio_clock, 0.064)
|| ISSAME(is->audio_clock - prev_audio_clock, -0.064)
|| ISSAME(is->audio_clock - prev_audio_clock, -0.096)
)
prev_audio_clock = is->audio_clock; // Ignore AC3 packet jitter
}
if ( initial_apts_set && is->audio_clock != 0.0 && fabs( is->audio_clock - prev_audio_clock) > 0.02) {
if (do_audio_repair && fabs( is->audio_clock - prev_audio_clock) < 1) {
is->audio_clock = prev_audio_clock; //Ignore small jitter
}
else {
Debug(8 ,"Strange audio pts step of %6.5f instead of %6.5f at frame %d\n", (is->audio_clock - prev_audio_clock)+0.0005, 0.0 , framenum);
if (do_audio_repair) {
// apts_offset += is->audio_clock - prev_audio_clock ;
// is->audio_clock = prev_audio_clock;
}
}
}
if (!initial_apts_set) {
initial_apts = is->audio_clock;
Debug( 10,"\nInitial audio pts = %10.3f\n", initial_apts);
}
}
initial_apts_set = 1;
len1 = avcodec_send_packet(is->audio_ctx, pkt_temp);
// fprintf(stderr, "sac = %f\n", is->audio_clock);
while ((len1 = avcodec_receive_frame(is->audio_ctx, is->frame)) != AVERROR(EAGAIN))
{
// data_size = STORAGE_SIZE;
got_frame = len1 >= 0;
if (prev_codec_id != -1 && (unsigned int)prev_codec_id != is->audio_st->codecpar->codec_id)
{
Debug(2 ,"Audio format change\n");
}
prev_codec_id = is->audio_st->codecpar->codec_id;
if (len1 < 0 && !ALIGN_AC3_PACKETS)
{
/* if error, we skip the frame */
pkt_temp->size = 0;
if (is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3) ac3_packet_index = 0;
break;
}
if (len1 < 0 && ALIGN_AC3_PACKETS)
{
len1 = 2; // Skip over packet start
pkt_temp->data += len1;
pkt_temp->size -= len1;
break;
}
pkt_temp->data += len1;
pkt_temp->size -= len1;
if (!got_frame)
{
/* stop sending empty packets if the decoder is finished */
continue;
}
data_size = av_samples_get_buffer_size(NULL, is->frame->channels,
is->frame->nb_samples,
is->frame->format, 1);
if (data_size > 0)
{
sound_to_frames(is, (short **)is->frame->data, is->frame->nb_samples ,is->frame->channels, is->frame->format);
}
is->audio_clock += (double)data_size /
(is->frame->channels * is->frame->sample_rate * av_get_bytes_per_sample(is->frame->format));
av_frame_unref(is->frame);
}
if (ALIGN_AC3_PACKETS && is->audio_st->codecpar->codec_id == AV_CODEC_ID_AC3) {
ps = 0;
rps = (pkt_temp->data - ac3_packet);
while (0 < ac3_packet_index - rps)
{
ac3_packet[ps] = ac3_packet[rps];
ps++;
rps++;
}
ac3_packet_index = ps;
}
}
static double print_fps (int final)
{
static uint32_t frame_counter = 0;
static struct timeval tv_beg, tv_start;
static int total_elapsed;
static int last_count = 0;
struct timeval tv_end;
double fps, tfps;
int frames, elapsed;
char cur_pos[100] = "0:00:00";
if (verbose)
return 0.0;
if(csStepping)
return 0.0;
if(final < 0)
{
frame_counter = 0;
last_count = 0;
return 0.0;
}
#ifdef DONATOR
#else
#ifndef DEBUG
again:
#endif
#endif
gettimeofday (&tv_end, NULL);
if (!frame_counter)
{
tv_start = tv_beg = tv_end;
signal (SIGINT, signal_handler);
}
elapsed = (tv_end.tv_sec - tv_beg.tv_sec) * 100 + (tv_end.tv_usec - tv_beg.tv_usec) / 10000;
total_elapsed = (tv_end.tv_sec - tv_start.tv_sec) * 100 + (tv_end.tv_usec - tv_start.tv_usec) / 10000;
if (final)
{
if (total_elapsed)
tfps = frame_counter * 100.0 / total_elapsed;
else
tfps = 0;
fprintf (stderr,"\n%d frames decoded in %.2f seconds (%.2f fps)\n",
frame_counter, total_elapsed / 100.0, tfps);
fflush(stderr);
return tfps;
}
frame_counter++;
frames = frame_counter - last_count;
#ifdef DONATOR
#else
#ifndef DEBUG
if (is_h264 && frames > 15 && elapsed < 100)
{
Sleep(100L);
goto again;
}
#endif
#endif
if (elapsed < 100) /* only display every 1.00 seconds */
return 0.0;
tv_beg = tv_end;
// cur_second = (int)(get_frame_pts(framenum));
cur_second = (int)((framenum)/get_fps());
cur_hour = cur_second / (60 * 60);
cur_second -= cur_hour * 60 * 60;
cur_minute = cur_second / 60;
cur_second -= cur_minute * 60;
sprintf(cur_pos, "%2i:%.2i:%.2i", cur_hour, cur_minute, cur_second);
fps = frames * 100.0 / elapsed;
tfps = frame_counter * 100.0 / total_elapsed;
fprintf (stderr, "%s - %d frames in %.2f sec(%.2f fps), "
"%.2f sec(%.2f fps), %d%%\r", cur_pos, frame_counter,
// total_elapsed / 100.0, tfps, elapsed / 100.0, fps, (int) (100.0 * get_frame_pts(framenum) / global_video_state->duration));
total_elapsed / 100.0, tfps, elapsed / 100.0, fps, (int) (100.0 * (framenum)/get_fps() / global_video_state->duration));
fflush(stderr);
last_count = frame_counter;
return tfps;
}
#ifdef PROCESS_CC
void CEW_reinit();
long process_block (unsigned char *data, long length);
#endif
int SubmitFrame(AVStream *video_st, AVFrame *pFrame , double pts)
{
int res=0;
int changed = 0;
// bitrate = pFrame->bit_rate;
if (pFrame->linesize[0] > MAXWIDTH || pFrame->height > MAXHEIGHT || pFrame->linesize[0] < 100 || pFrame->height < 100)
{
Debug(1, "Panic: illegal height (%d), width (%d) or frame period (%d)\n",
pFrame->height, pFrame->width, pFrame->linesize[0]);
frame_ptr = NULL;
return(0);
}
if (height != pFrame->height && pFrame->height > 100 && pFrame->height < MAXHEIGHT)
{
height= pFrame->height;
changed = 1;
}
if (width != pFrame->linesize[0] && pFrame->linesize[0] > 100 && pFrame->linesize[0] < MAXWIDTH)
{
width= pFrame->linesize[0];
changed = 1;
}
if (videowidth != pFrame->width && pFrame->width > 100 && pFrame->width < MAXWIDTH)
{
videowidth= pFrame->width;
changed = 1;
}
if (changed) Debug(5, "Format changed to [%d : %d]\n", videowidth, height);
infopos = headerpos;
frame_ptr = pFrame->data[0];
if (frame_ptr == NULL)
{
return(0);; // return; // exit(2);
}
if (pFrame->pict_type == AV_PICTURE_TYPE_B)
pict_type = 'B';
else if (pFrame->pict_type == AV_PICTURE_TYPE_I)
pict_type = 'I';
else
pict_type = 'P';
if (selftest == 2 && framenum == 0 && pass == 0 && test_pts == 0.0) //Reset file test
test_pts = pts;
if (selftest == 2 && pass > 0) //Reset file test
{
if (test_pts != pts)
{
sample_file = fopen("seektest.log", "a+");
fprintf(sample_file, "Reset file Failed, initial pts = %6.3f, seek pts = %6.3f, pass = %d, \"%s\"\n", test_pts, pts, pass+1, is->filename);
fclose(sample_file);
Debug( 1,"\nSelftest %d FAILED: Reset\n", selftest);
}
else
Debug( 1,"\nSelftest 2 OK: Reset\n");
exit(1);
}
if (!reviewing)
{
print_fps (0);
res = DetectCommercials((int)framenum, pts);
framenum++;
#ifdef SELFTEST
if (selftest == 2 && pass == 0 && framenum > 20) //Reset input file
{
res = true;
pass++;
}
#endif
if (res) {
framenum = 0;
sound_frame_counter = 0;
is->seek_req = 1;
is->seek_pos = 0;
is->seek_pts = 0.0;
}
}
return (res);
}
void Set_seek(VideoState *is, double pts)
{
AVFormatContext *ic = is->pFormatCtx;
double length = is->duration;
is->seek_flags = AVSEEK_FLAG_ANY;
is->seek_flags = AVSEEK_FLAG_BACKWARD;
is->seek_req = true;
is->seek_pts = pts;
#ifdef DEBUG
printf("Seek to %8.2f\n", pts);
#endif // DEBUG
#define MAX_GOP_SIZE 2.0
pts = fmax(0.0,pts-MAX_GOP_SIZE);
if (is->seek_by_bytes)