-
Notifications
You must be signed in to change notification settings - Fork 18
/
ffmpeg_ntsc.cpp
2332 lines (2060 loc) · 87.8 KB
/
ffmpeg_ntsc.cpp
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
// NTS: This is not like modern "posterize" filters where the pixels are quantizied to N levels then scaled out to 0..255
// That requires a multiply/divide per pixel. Think old-school hardware where such operations were too expensive.
// The "posterize" we emulate here is more the type where you run the video through an ADC, truncate the least significant
// bits, then run back through a DAC on the other side (well within the realm of 1980s/1990s hardware)
#define __STDC_CONSTANT_MACROS
#define __STDC_LIMIT_MACROS
#include <sys/types.h>
#include <signal.h>
#include <stdint.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <math.h>
extern "C" {
#include <libavutil/opt.h>
#include <libavutil/avutil.h>
#include <libavutil/pixfmt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/samplefmt.h>
#include <libavutil/pixelutils.h>
#include <libavcodec/avcodec.h>
#include <libavcodec/version.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavformat/version.h>
#include <libswscale/swscale.h>
#include <libswscale/version.h>
#include <libswresample/swresample.h>
#include <libswresample/version.h>
}
using namespace std;
#include <map>
#include <string>
#include <vector>
#include <stdexcept>
/* return a floating point value specifying what to scale the sample
* value by to reduce it from full volume to dB decibels */
double dBFS(double dB)
{
/* 10 ^ (dB / 20),
based on reversing the formula for converting samples to decibels:
dB = 20.0 * log10(sample);
where "sample" is -1.0 <= x <= 1.0 */
return pow(10.0,dB / 20.0);
}
/* attenuate a sample value by this many dBFS */
/* so if you want to reduce it by 20dBFS you pass -20 as dB */
double attenuate_dBFS(double sample,double dB)
{
return sample * dBFS(dB);
}
/* opposite: convert sample to decibels */
double dBFS_measure(double sample) {
return 20.0 * log10(sample);
}
// lowpass filter
// you can make it a highpass filter by applying a lowpass then subtracting from source.
class LowpassFilter {
public:
LowpassFilter() : timeInterval(0), cutoff(0), alpha(0), prev(0), tau(0) {
}
void setFilter(const double rate/*sample rate of audio*/,const double hz/*cutoff*/) {
#ifndef M_PI
#error your math.h does not include M_PI constant
#endif
timeInterval = 1.0 / rate;
tau = 1 / (hz * 2 * M_PI);
cutoff = hz;
alpha = timeInterval / (tau + timeInterval);
}
void resetFilter(const double val=0) {
prev = val;
}
double lowpass(const double sample) {
const double stage1 = sample * alpha;
const double stage2 = prev - (prev * alpha); /* NTS: Instead of prev * (1.0 - alpha) */
return (prev = (stage1 + stage2)); /* prev = stage1+stage2 then return prev */
}
double highpass(const double sample) {
const double stage1 = sample * alpha;
const double stage2 = prev - (prev * alpha); /* NTS: Instead of prev * (1.0 - alpha) */
return sample - (prev = (stage1 + stage2)); /* prev = stage1+stage2 then return (sample - prev) */
}
public:
double timeInterval;
double cutoff;
double alpha; /* timeInterval / (tau + timeInterval) */
double prev;
double tau;
};
class HiLoPair {
public:
LowpassFilter hi,lo; // highpass, lowpass
public:
void setFilter(const double rate/*sample rate of audio*/,const double low_hz,const double high_hz) {
lo.setFilter(rate,low_hz);
hi.setFilter(rate,high_hz);
}
double filter(const double sample) {
return hi.highpass(lo.lowpass(sample)); /* first lowpass, then highpass */
}
};
class HiLoPass : public vector<HiLoPair> { // all passes, one sample of one channel
public:
HiLoPass() : vector() { }
public:
void setFilter(const double rate/*sample rate of audio*/,const double low_hz,const double high_hz) {
for (size_t i=0;i < size();i++) (*this)[i].setFilter(rate,low_hz,high_hz);
}
double filter(double sample) {
for (size_t i=0;i < size();i++) sample = (*this)[i].lo.lowpass(sample);
for (size_t i=0;i < size();i++) sample = (*this)[i].hi.highpass(sample);
return sample;
}
void init(const unsigned int passes) {
clear();
resize(passes);
assert(size() >= passes);
}
};
class HiLoSample : public vector<HiLoPass> { // all passes, all channels of one sample period
public:
HiLoSample() : vector() { }
public:
void init(const unsigned int channels,const unsigned int passes) {
clear();
resize(channels);
assert(size() >= channels);
for (size_t i=0;i < size();i++) (*this)[i].init(passes);
}
void setFilter(const double rate/*sample rate of audio*/,const double low_hz,const double high_hz) {
for (size_t i=0;i < size();i++) (*this)[i].setFilter(rate,low_hz,high_hz);
}
};
class HiLoComboPass {
public:
HiLoComboPass() : passes(0), channels(0), rate(0), low_cutoff(0), high_cutoff(0) {
}
~HiLoComboPass() {
clear();
}
void setChannels(const size_t _channels) {
if (channels != _channels) {
clear();
channels = _channels;
}
}
void setCutoff(const double _low_cutoff,const double _high_cutoff) {
if (low_cutoff != _low_cutoff || high_cutoff != _high_cutoff) {
clear();
low_cutoff = _low_cutoff;
high_cutoff = _high_cutoff;
}
}
void setRate(const double _rate) {
if (rate != _rate) {
clear();
rate = _rate;
}
}
void setPasses(const size_t _passes) {
if (passes != _passes) {
clear();
passes = _passes;
}
}
void clear() {
audiostate.clear();
}
void init() {
clear();
if (channels == 0 || passes == 0 || rate == 0 || low_cutoff == 0 || high_cutoff == 0) return;
audiostate.init(channels,passes);
audiostate.setFilter(rate,low_cutoff,high_cutoff);
}
public:
double rate;
size_t passes;
size_t channels;
double low_cutoff;
double high_cutoff;
HiLoSample audiostate;
};
bool use_422_colorspace = false; // I would default this to true but Adobe Premiere Pro apparently can't handle 4:2:2 H.264 >:(
AVRational output_field_rate = { 60000, 1001 }; // NTSC 60Hz default
int output_width = 720;
int output_height = 480;
bool output_ntsc = true; // NTSC color subcarrier emulation
bool output_pal = false; // PAL color subcarrier emulation
int output_audio_channels = 2; // VHS stereo (set to 1 for mono)
int output_audio_rate = 44100; // VHS Hi-Fi goes up to 20KHz
int video_scanline_phase_shift = 180;
int video_scanline_phase_shift_offset = 0;
#define RGBTRIPLET(r,g,b) (((uint32_t)(r) << (uint32_t)16) + ((uint32_t)(g) << (uint32_t)8) + ((uint32_t)(b) << (uint32_t)0))
AVFormatContext* output_avfmt = NULL;
AVStream* output_avstream_audio = NULL; // do not free
AVCodecContext* output_avstream_audio_codec_context = NULL; // do not free
AVStream* output_avstream_video = NULL; // do not free
AVCodecContext* output_avstream_video_codec_context = NULL; // do not free
std::vector<AVFrame*> output_avstream_video_frame; // ARGB
AVFrame* output_avstream_video_encode_frame = NULL; // 4:2:2 or 4:2:0
size_t output_avstream_video_frame_delay = 1;
size_t output_avstream_video_frame_index = 0;
struct SwsContext* output_avstream_video_resampler = NULL;
class InputFile {
public:
InputFile() {
input_avfmt = NULL;
audio_dst_data = NULL;
input_avstream_audio = NULL;
input_avstream_audio_frame = NULL;
input_avstream_audio_resampler = NULL;
input_avstream_audio_codec_context = NULL;
input_avstream_video = NULL;
input_avstream_video_frame = NULL;
input_avstream_video_frame_rgb = NULL;
input_avstream_video_resampler = NULL;
input_avstream_video_codec_context = NULL;
next_pts = next_dts = -1LL;
avpkt_valid = false;
eof_stream = false;
eof = false;
}
~InputFile() {
close_input();
}
public:
void reset_on_dup(void) {
path.clear();
}
bool open_input(void) {
if (input_avfmt == NULL) {
if (avformat_open_input(&input_avfmt,path.c_str(),NULL,NULL) < 0) {
fprintf(stderr,"Failed to open input file\n");
close_input();
return false;
}
if (avformat_find_stream_info(input_avfmt,NULL) < 0)
fprintf(stderr,"WARNING: Did not find stream info on input\n");
/* scan streams for one video, one audio */
{
size_t i;
AVStream *is;
int ac=0,vc=0;
AVCodecContext *isctx;
fprintf(stderr,"Input format: %u streams found\n",input_avfmt->nb_streams);
for (i=0;i < (size_t)input_avfmt->nb_streams;i++) {
is = input_avfmt->streams[i];
if (is == NULL) continue;
isctx = is->codec;
if (isctx == NULL) continue;
if (isctx->codec_type == AVMEDIA_TYPE_AUDIO) {
if (input_avstream_audio == NULL && ac == 0) {
if (avcodec_open2(isctx,avcodec_find_decoder(isctx->codec_id),NULL) >= 0) {
input_avstream_audio = is;
input_avstream_audio_codec_context = isctx;
fprintf(stderr,"Found audio stream idx=%zu %u-channel %uHz\n",
i,
input_avstream_audio_codec_context->channels,
input_avstream_audio_codec_context->sample_rate);
}
else {
fprintf(stderr,"Found audio stream but not able to decode\n");
}
}
ac++;
}
else if (isctx->codec_type == AVMEDIA_TYPE_VIDEO) {
if (input_avstream_video == NULL && vc == 0) {
if (avcodec_open2(isctx,avcodec_find_decoder(isctx->codec_id),NULL) >= 0) {
input_avstream_video = is;
input_avstream_video_codec_context = isctx;
fprintf(stderr,"Found video stream idx=%zu\n",i);
}
else {
fprintf(stderr,"Found video stream but not able to decode\n");
}
}
vc++;
}
}
if (input_avstream_video == NULL && input_avstream_audio == NULL) {
fprintf(stderr,"Neither video nor audio found\n");
close_input();
return 1;
}
}
}
/* prepare audio decoding */
if (input_avstream_audio != NULL) {
input_avstream_audio_frame = av_frame_alloc();
if (input_avstream_audio_frame == NULL) {
fprintf(stderr,"Failed to alloc audio frame\n");
close_input();
return 1;
}
}
/* prepare video decoding */
if (input_avstream_video != NULL) {
input_avstream_video_frame = av_frame_alloc();
if (input_avstream_video_frame == NULL) {
fprintf(stderr,"Failed to alloc video frame\n");
close_input();
return 1;
}
/* prepare video encoding */
input_avstream_video_frame_rgb = av_frame_alloc();
if (input_avstream_video_frame_rgb == NULL) {
fprintf(stderr,"Failed to alloc video frame\n");
close_input();
return 1;
}
input_avstream_video_frame_rgb->format = AV_PIX_FMT_BGRA;
input_avstream_video_frame_rgb->height = output_height;
input_avstream_video_frame_rgb->width = output_width;
if (av_frame_get_buffer(input_avstream_video_frame_rgb,64) < 0) {
fprintf(stderr,"Failed to alloc render frame\n");
close_input();
return 1;
}
memset(input_avstream_video_frame_rgb->data[0],0,input_avstream_video_frame_rgb->linesize[0]*input_avstream_video_frame_rgb->height);
}
input_avstream_video_resampler_format = AV_PIX_FMT_NONE;
input_avstream_video_resampler_height = -1;
input_avstream_video_resampler_width = -1;
last_written_sample = 0;
audio_dst_data_out_audio_sample = 0;
audio_sample = 0;
audio_dst_data = NULL;
audio_dst_data_alloc_samples = 0;
audio_dst_data_linesize = 0;
audio_dst_data_samples = 0;
audio_dst_data_out_samples = 0;
input_avstream_audio_resampler_channels = -1;
input_avstream_audio_resampler_rate = -1;
eof_stream = false;
got_audio = false;
got_video = false;
adj_time = 0;
t = pt = -1;
eof = false;
avpkt_init();
next_pts = next_dts = -1LL;
return (input_avfmt != NULL);
}
bool next_packet(void) {
if (eof) return false;
if (input_avfmt == NULL) return false;
do {
if (eof_stream) break;
avpkt_release();
avpkt_init();
if (av_read_frame(input_avfmt,&avpkt) < 0) {
eof_stream = true;
return false;
}
if (avpkt.stream_index >= input_avfmt->nb_streams)
continue;
// ugh... this can happen if the source is an AVI file
if (avpkt.pts == AV_NOPTS_VALUE) avpkt.pts = avpkt.dts;
/* track time and keep things monotonic for our code */
if (avpkt.pts != AV_NOPTS_VALUE) {
t = avpkt.pts * av_q2d(input_avfmt->streams[avpkt.stream_index]->time_base);
if (pt < 0)
adj_time = -t;
else if ((t+1.5) < pt) { // time code jumps backwards (1.5 is safe for DVD timecode resets)
adj_time += pt - t;
fprintf(stderr,"Time code jump backwards %.6f->%.6f. adj_time=%.6f\n",pt,t,adj_time);
}
else if (t > (pt+5)) { // time code jumps forwards
adj_time += pt - t;
fprintf(stderr,"Time code jump forwards %.6f->%.6f. adj_time=%.6f\n",pt,t,adj_time);
}
pt = t;
}
if (pt < 0)
continue;
if (avpkt.pts != AV_NOPTS_VALUE) {
avpkt.pts += (adj_time * input_avfmt->streams[avpkt.stream_index]->time_base.den) /
input_avfmt->streams[avpkt.stream_index]->time_base.num;
}
if (avpkt.dts != AV_NOPTS_VALUE) {
avpkt.dts += (adj_time * input_avfmt->streams[avpkt.stream_index]->time_base.den) /
input_avfmt->streams[avpkt.stream_index]->time_base.num;
}
got_audio = false;
got_video = false;
if (input_avstream_audio != NULL && avpkt.stream_index == input_avstream_audio->index) {
if (got_audio) fprintf(stderr,"Audio content lost\n");
av_packet_rescale_ts(&avpkt,input_avstream_audio->time_base,output_avstream_audio->time_base);
handle_audio(/*&*/avpkt);
got_audio = true;
break;
}
else if (input_avstream_video != NULL && avpkt.stream_index == input_avstream_video->index) {
if (got_video) fprintf(stderr,"Video content lost\n");
AVRational m = (AVRational){output_field_rate.den, output_field_rate.num};
av_packet_rescale_ts(&avpkt,input_avstream_video->time_base,m); // convert to FIELD number
handle_frame(/*&*/avpkt); // will set got_video
break;
}
avpkt_release();
} while (1);
if (eof_stream) {
avpkt_release();
avpkt.size = 0;
avpkt.data = NULL;
handle_frame(/*&*/avpkt); // will set got_video
if (!got_video) eof = true;
else fprintf(stderr,"Got latent frame\n");
}
return true;
}
void handle_audio(AVPacket &pkt) {
int got_frame = 0;
if (avcodec_decode_audio4(input_avstream_audio_codec_context,input_avstream_audio_frame,&got_frame,&pkt) >= 0) {
if (got_frame != 0 && input_avstream_audio_frame->nb_samples != 0) {
if (input_avstream_audio_frame->pts == AV_NOPTS_VALUE)
input_avstream_audio_frame->pts = pkt.pts;
if (input_avstream_audio_resampler != NULL) {
if (input_avstream_audio_resampler_rate != input_avstream_audio_codec_context->sample_rate ||
input_avstream_audio_resampler_channels != input_avstream_audio_codec_context->channels) {
fprintf(stderr,"Audio format changed\n");
swr_free(&input_avstream_audio_resampler);
}
}
if (input_avstream_audio_resampler == NULL) {
input_avstream_audio_resampler = swr_alloc();
av_opt_set_int(input_avstream_audio_resampler, "in_channel_count", input_avstream_audio_codec_context->channels, 0); // FIXME: FFMPEG should document this!!
av_opt_set_int(input_avstream_audio_resampler, "out_channel_count", output_avstream_audio_codec_context->channels, 0); // FIXME: FFMPEG should document this!!
av_opt_set_int(input_avstream_audio_resampler, "in_channel_layout", input_avstream_audio_codec_context->channel_layout, 0);
av_opt_set_int(input_avstream_audio_resampler, "out_channel_layout", output_avstream_audio_codec_context->channel_layout, 0);
av_opt_set_int(input_avstream_audio_resampler, "in_sample_rate", input_avstream_audio_codec_context->sample_rate, 0);
av_opt_set_int(input_avstream_audio_resampler, "out_sample_rate", output_avstream_audio_codec_context->sample_rate, 0);
av_opt_set_sample_fmt(input_avstream_audio_resampler, "in_sample_fmt", input_avstream_audio_codec_context->sample_fmt, 0);
av_opt_set_sample_fmt(input_avstream_audio_resampler, "out_sample_fmt", output_avstream_audio_codec_context->sample_fmt, 0);
if (swr_init(input_avstream_audio_resampler) < 0) {
fprintf(stderr,"Failed to init audio resampler\n");
swr_free(&input_avstream_audio_resampler);
return;
}
input_avstream_audio_resampler_rate = input_avstream_audio_codec_context->sample_rate;
input_avstream_audio_resampler_channels = input_avstream_audio_codec_context->channels;
if (audio_dst_data != NULL) {
av_freep(&audio_dst_data[0]); // NTS: Why??
av_freep(&audio_dst_data);
}
audio_dst_data_alloc_samples = 0;
fprintf(stderr,"Audio resampler init %uHz -> %uHz\n",
input_avstream_audio_codec_context->sample_rate,
output_avstream_audio_codec_context->sample_rate);
}
audio_dst_data_samples = av_rescale_rnd(
swr_get_delay(input_avstream_audio_resampler, input_avstream_audio_frame->sample_rate) + input_avstream_audio_frame->nb_samples,
output_avstream_audio_codec_context->sample_rate, input_avstream_audio_frame->sample_rate, AV_ROUND_UP);
if (audio_dst_data == NULL || audio_dst_data_samples > audio_dst_data_alloc_samples) {
if (audio_dst_data != NULL) {
av_freep(&audio_dst_data[0]); // NTS: Why??
av_freep(&audio_dst_data);
}
audio_dst_data_alloc_samples = 0;
fprintf(stderr,"Allocating audio buffer %u samples\n",(unsigned int)audio_dst_data_samples);
if (av_samples_alloc_array_and_samples(&audio_dst_data,&audio_dst_data_linesize,
output_avstream_audio_codec_context->channels,audio_dst_data_samples,
output_avstream_audio_codec_context->sample_fmt, 0) >= 0) {
audio_dst_data_alloc_samples = audio_dst_data_samples;
}
else {
fprintf(stderr,"Failure to allocate audio buffer\n");
audio_dst_data_alloc_samples = 0;
}
}
if (audio_dst_data != NULL) {
if ((audio_dst_data_out_samples=swr_convert(input_avstream_audio_resampler,audio_dst_data,audio_dst_data_samples,
(const uint8_t**)input_avstream_audio_frame->data,input_avstream_audio_frame->nb_samples)) > 0) {
}
else if (audio_dst_data_out_samples < 0) {
fprintf(stderr,"Failed to resample audio\n");
}
audio_dst_data_out_audio_sample = audio_sample;
audio_sample += audio_dst_data_out_samples;
}
}
}
}
void frame_copy_scale(void) {
if (input_avstream_video_frame_rgb == NULL) {
fprintf(stderr,"New input frame\n");
input_avstream_video_frame_rgb = av_frame_alloc();
if (input_avstream_video_frame_rgb == NULL) {
fprintf(stderr,"Failed to alloc video frame\n");
return;
}
input_avstream_video_frame_rgb->format = AV_PIX_FMT_BGRA;
input_avstream_video_frame_rgb->height = output_height;
input_avstream_video_frame_rgb->width = output_width;
if (av_frame_get_buffer(input_avstream_video_frame_rgb,64) < 0) {
fprintf(stderr,"Failed to alloc render frame\n");
return;
}
memset(input_avstream_video_frame_rgb->data[0],0,input_avstream_video_frame_rgb->linesize[0]*input_avstream_video_frame_rgb->height);
}
if (input_avstream_video_resampler != NULL) { // pixel format change or width/height change = free resampler and reinit
if (input_avstream_video_resampler_format != input_avstream_video_frame->format ||
input_avstream_video_resampler_width != input_avstream_video_frame->width ||
input_avstream_video_resampler_height != input_avstream_video_frame->height) {
sws_freeContext(input_avstream_video_resampler);
input_avstream_video_resampler = NULL;
}
}
if (input_avstream_video_resampler == NULL) {
input_avstream_video_resampler = sws_getContext(
// source
input_avstream_video_frame->width,
input_avstream_video_frame->height,
(AVPixelFormat)input_avstream_video_frame->format,
// dest
input_avstream_video_frame_rgb->width,
input_avstream_video_frame_rgb->height,
(AVPixelFormat)input_avstream_video_frame_rgb->format,
// opt
SWS_BILINEAR, NULL, NULL, NULL);
if (input_avstream_video_resampler != NULL) {
fprintf(stderr,"sws_getContext new context\n");
input_avstream_video_resampler_format = (AVPixelFormat)input_avstream_video_frame->format;
input_avstream_video_resampler_width = input_avstream_video_frame->width;
input_avstream_video_resampler_height = input_avstream_video_frame->height;
}
else {
fprintf(stderr,"sws_getContext fail\n");
}
}
if (input_avstream_video_resampler != NULL) {
input_avstream_video_frame_rgb->pts = input_avstream_video_frame->pts;
input_avstream_video_frame_rgb->pkt_pts = input_avstream_video_frame->pkt_pts;
input_avstream_video_frame_rgb->pkt_dts = input_avstream_video_frame->pkt_dts;
input_avstream_video_frame_rgb->top_field_first = input_avstream_video_frame->top_field_first;
input_avstream_video_frame_rgb->interlaced_frame = input_avstream_video_frame->interlaced_frame;
if (sws_scale(input_avstream_video_resampler,
// source
input_avstream_video_frame->data,
input_avstream_video_frame->linesize,
0,input_avstream_video_frame->height,
// dest
input_avstream_video_frame_rgb->data,
input_avstream_video_frame_rgb->linesize) <= 0)
fprintf(stderr,"WARNING: sws_scale failed\n");
}
}
void handle_frame(AVPacket &pkt) {
int got_frame = 0;
if (avcodec_decode_video2(input_avstream_video_codec_context,input_avstream_video_frame,&got_frame,&pkt) >= 0) {
if (got_frame != 0 && input_avstream_video_frame->width > 0 && input_avstream_video_frame->height > 0) {
got_video = true;
}
}
else {
fprintf(stderr,"No video decoded\n");
}
}
void avpkt_init(void) {
if (!avpkt_valid) {
avpkt_valid = true;
av_init_packet(&avpkt);
}
}
void avpkt_release(void) {
if (avpkt_valid) {
avpkt_valid = false;
av_packet_unref(&avpkt);
}
got_audio = false;
got_video = false;
}
void close_input(void) {
eof = true;
avpkt_release();
if (input_avstream_audio_codec_context != NULL) {
avcodec_close(input_avstream_audio_codec_context);
input_avstream_audio_codec_context = NULL;
input_avstream_audio = NULL;
}
if (input_avstream_video_codec_context != NULL) {
avcodec_close(input_avstream_video_codec_context);
input_avstream_video_codec_context = NULL;
input_avstream_video = NULL;
}
if (input_avstream_audio_frame != NULL)
av_frame_free(&input_avstream_audio_frame);
if (input_avstream_video_frame != NULL)
av_frame_free(&input_avstream_video_frame);
if (input_avstream_video_frame_rgb != NULL)
av_frame_free(&input_avstream_video_frame_rgb);
if (input_avstream_audio_resampler != NULL)
swr_free(&input_avstream_audio_resampler);
if (input_avstream_video_resampler != NULL) {
sws_freeContext(input_avstream_video_resampler);
input_avstream_video_resampler = NULL;
}
if (audio_dst_data != NULL) {
av_freep(&audio_dst_data[0]); // NTS: Why??
av_freep(&audio_dst_data);
}
input_avstream_audio_resampler_channels = -1;
input_avstream_audio_resampler_rate = -1;
avformat_close_input(&input_avfmt);
}
public:
std::string path;
uint32_t color;
bool eof;
bool eof_stream;
bool got_audio;
bool got_video;
public:
unsigned long long last_written_sample;
unsigned long long audio_sample;
uint8_t** audio_dst_data;
int audio_dst_data_alloc_samples;
int audio_dst_data_linesize;
int audio_dst_data_samples;
int audio_dst_data_out_samples;
unsigned long long audio_dst_data_out_audio_sample;
int input_avstream_audio_resampler_rate;
int input_avstream_audio_resampler_channels;
AVFormatContext* input_avfmt;
AVStream* input_avstream_audio; // do not free
AVCodecContext* input_avstream_audio_codec_context; // do not free
AVFrame* input_avstream_audio_frame;
AVStream* input_avstream_video; // do not free
AVCodecContext* input_avstream_video_codec_context; // do not free
AVFrame* input_avstream_video_frame;
AVFrame* input_avstream_video_frame_rgb;
struct SwrContext* input_avstream_audio_resampler;
struct SwsContext* input_avstream_video_resampler;
AVPixelFormat input_avstream_video_resampler_format;
int input_avstream_video_resampler_height;
int input_avstream_video_resampler_width;
signed long long next_pts;
signed long long next_dts;
AVPacket avpkt;
bool avpkt_valid;
double adj_time;
double t,pt;
};
std::vector<InputFile> input_files;
std::string output_file;
InputFile ¤t_input_file(void) {
if (input_files.empty()) {
std::string what = "input files empty";
throw std::out_of_range(/*&*/what);
}
return *(input_files.rbegin()); /* last one */
}
InputFile &new_input_file(void) {
if (!input_files.empty()) {
/* copy the last one, except for some fields */
{
InputFile &last = current_input_file();
input_files.push_back(last);
}
{
InputFile &last = current_input_file();
last.reset_on_dup();
}
}
else {
/* make a new one with defaults */
input_files.push_back(InputFile());
}
return current_input_file();
}
volatile int DIE = 0;
HiLoComboPass audio_hilopass;
// preemphsis emuluation
LowpassFilter audio_linear_preemphasis_pre[2];
LowpassFilter audio_linear_preemphasis_post[2];
double composite_preemphasis = 0; // analog artifacts related to anything that affects the raw composite signal i.e. CATV modulation
double composite_preemphasis_cut = 1000000;
double vhs_out_sharpen = 1.5;
bool vhs_head_switching = false;
double vhs_head_switching_point = 1.0 - ((4.5+0.01/*slight error, like most VHS tapes*/) / 262.5); // 4 scanlines NTSC up from vsync
double vhs_head_switching_phase = ((1.0-0.01/*slight error, like most VHS tapes*/) / 262.5); // 4 scanlines NTSC up from vsync
double vhs_head_switching_phase_noise = (((1.0 / 500)/*slight error, like most VHS tapes*/) / 262.5); // 1/500th of a scanline
bool composite_in_chroma_lowpass = true; // apply chroma lowpass before composite encode
bool composite_out_chroma_lowpass = true;
bool composite_out_chroma_lowpass_lite = true;
int video_yc_recombine = 0; // additional Y/C combine/sep phases (testing)
int video_color_fields = 4; // NTSC color framing
int video_chroma_noise = 0;
int video_chroma_phase_noise = 0;
int video_chroma_loss = 0;
int video_noise = 2;
int subcarrier_amplitude = 50;
int subcarrier_amplitude_back = 50;
double output_audio_hiss_db = -72;
double output_audio_linear_buzz = -42; // how loud the "buzz" is audible in dBFS (S/N). Ever notice on old VHS tapes (prior to Hi-Fi) you can almost hear the video signal sync pulses in the audio?
double output_audio_highpass = 20; // highpass to filter out below 20Hz
double output_audio_lowpass = 20000; // lowpass to filter out above 20KHz
double vhs_linear_high_boost = 0.25;
// NTS:
// VHS Hi-Fi: 20Hz - 20KHz (70dBFS S/N)
// VHS SP: 100Hz - 10KHz (42dBFS S/N)
// VHS LP: 100Hz - 7KHz (right??) (42dBFS S/N)
// VHS EP: 100Hz - 4KHz (42dBFS S/N)
bool output_vhs_hifi = true;
bool output_vhs_linear_stereo = false; // not common
bool output_vhs_linear_audio = false; // if true (non Hi-Fi) then we emulate hiss and noise of linear VHS tracks including the video sync pulses audible in the audio.
bool emulating_vhs = false;
bool emulating_preemphasis = true; // emulate preemphasis
bool emulating_deemphasis = true; // emulate deemphasis
bool nocolor_subcarrier = false; // if set, emulate subcarrier but do not decode back to color (debug)
bool nocolor_subcarrier_after_yc_sep = false;// if set, separate luma-chroma but do not decode back to color (debug)
bool vhs_chroma_vert_blend = true; // if set, and VHS, blend vertically the chroma scanlines (as the VHS format does)
bool vhs_svideo_out = false; // if not set, and VHS, video is recombined as if composite out on VCR
bool enable_composite_emulation = true; // if not set, video goes straight back out to the encoder.
bool enable_audio_emulation = true;
int output_audio_hiss_level = 0; // out of 10000
enum {
VHS_SP=0,
VHS_LP,
VHS_EP
};
int output_vhs_tape_speed = VHS_SP;
void sigma(int x) {
if (++DIE >= 20) abort();
}
void preset_PAL() {
output_field_rate.num = 50;
output_field_rate.den = 1;
output_height = 576;
output_width = 720;
output_pal = true;
output_ntsc = false;
}
void preset_NTSC() {
output_field_rate.num = 60000;
output_field_rate.den = 1001;
output_height = 480;
output_width = 720;
output_pal = false;
output_ntsc = true;
}
static void help(const char *arg0) {
fprintf(stderr,"%s [options]\n",arg0);
fprintf(stderr," -i <input file> you can specify more than one input file, in order of layering\n");
fprintf(stderr," -o <output file>\n");
fprintf(stderr," -d <n> Video delay buffer (n frames)\n");
fprintf(stderr," -tvstd <pal|ntsc>\n");
fprintf(stderr," -vhs Emulation of VHS artifacts\n");
fprintf(stderr," -vhs-hifi <0|1> (default on)\n");
fprintf(stderr," -vhs-speed <ep|lp|sp> (default sp)\n");
fprintf(stderr," -preemphasis <0|1> Enable preemphasis emulation\n");
fprintf(stderr," -deemphasis <0|1> Enable deepmhasis emulation\n");
fprintf(stderr," -nocolor-subcarrier Emulate color subcarrier but do not decode back (debug)\n");
fprintf(stderr," -nocolor-subcarrier-after-yc-sep Emulate Y/C subcarrier separation but do not decode back (debug)\n");
fprintf(stderr," -subcarrier-amp <0...100> Subcarrier amplitude (0 to 100 percent of luma)\n");
fprintf(stderr," -noise <0..100> Noise amplitude\n");
fprintf(stderr," -chroma-noise <0..100> Chroma noise amplitude\n");
fprintf(stderr," -audio-hiss <-120..0> Audio hiss in decibels (0=100%)\n");
fprintf(stderr," -vhs-linear-video-crosstalk <x> Emulate video crosstalk in audio. Loudness in dBFS (0=100%)\n");
fprintf(stderr," -chroma-phase-noise <x> Chroma phase noise (0...100)\n");
fprintf(stderr," -vhs-chroma-vblend <0|1> Vertically blend chroma scanlines (as VHS format does)\n");
fprintf(stderr," -vhs-svideo <0|1> Render VHS as if S-Video (luma and chroma separate out of VHS)\n");
fprintf(stderr," -yc-recomb <n> Recombine Y/C n-times\n");
fprintf(stderr," -a <n> Pick the n'th audio stream\n");
fprintf(stderr," -an Don't render any audio stream\n");
fprintf(stderr," -v <n> Pick the n'th video stream\n");
fprintf(stderr," -vn Don't render any video stream\n");
fprintf(stderr," -comp-pre <s> Composite preemphasis scale\n");
fprintf(stderr," -comp-cut <f> Composite preemphasis freq\n");
fprintf(stderr," -comp-catv Composite preemphasis preset, as if CATV #1\n");
fprintf(stderr," -comp-catv2 Composite preemphasis preset, as if CATV #2\n");
fprintf(stderr," -comp-catv3 Composite preemphasis preset, as if CATV #3\n");
fprintf(stderr," -comp-catv4 Composite preemphasis preset, as if CATV #4\n");
fprintf(stderr," -vi Render video at frame rate, interlaced\n");
fprintf(stderr," -vp Render video at field rate, progressive (with bob filter)\n");
fprintf(stderr," -chroma-dropout <x> Chroma scanline dropouts (0...10000)\n");
fprintf(stderr," -vhs-linear-high-boost <x> Boost high frequencies in VHS audio (linear tracks)\n");
fprintf(stderr," -vhs-head-switching <0|1> Enable/disable VHS head switching emulation\n");
fprintf(stderr," -vhs-head-switching-point <x> Head switching point (0....1)\n");
fprintf(stderr," -vhs-head-switching-phase <x> Head switching displacement (-1....1)\n");
fprintf(stderr," -vhs-head-switching-noise-level <x> Head switching noise (variation)\n");
fprintf(stderr," -422 Render in 4:2:2 colorspace\n");
fprintf(stderr," -420 Render in 4:2:0 colorspace (default)\n"); // dammit Premiere >:(
fprintf(stderr," -nocomp Don't apply emulation, just transcode\n");
fprintf(stderr," -ss <t> Start transcoding from t seconds\n");
fprintf(stderr," -se <t> Stop transcoding at t seconds\n");
fprintf(stderr," -t <t> Transcode only t seconds\n");
fprintf(stderr," -in-composite-lowpass <n> Enable/disable chroma lowpass on composite in\n");
fprintf(stderr," -out-composite-lowpass <n> Enable/disable chroma lowpass on composite out\n");
fprintf(stderr," -out-composite-lowpass-lite <n> Enable/disable chroma lowpass on composite out (lite)\n");
fprintf(stderr," -bkey-feedback <n> Black key feedback (black level <= N)\n");
fprintf(stderr," -comp-phase <n> NTSC subcarrier phase per scanline (0, 90, 180, or 270)\n");
fprintf(stderr,"\n");
fprintf(stderr," Output file will be up/down converted to 720x480 (NTSC 29.97fps) or 720x576 (PAL 25fps).\n");
fprintf(stderr," Output will be rendered as interlaced video.\n");
}
static unsigned long long audio_proc_count = 0;
static LowpassFilter audio_post_vhs_boost[2];
static inline int clips16(const int x) {
if (x < -32768)
return -32768;
else if (x > 32767)
return 32767;
return x;
}
void composite_audio_process(int16_t *audio,unsigned int samples) { // number of channels = output_audio_channels, sample rate = output_audio_rate. audio is interleaved.
assert(audio_hilopass.audiostate.size() >= output_audio_channels);
double linear_buzz = dBFS(output_audio_linear_buzz);
double hsync_hz = output_ntsc ? /*NTSC*/15734 : /*PAL*/15625;
int vsync_lines = output_ntsc ? /*NTSC*/525 : /*PAL*/625;
int vpulse_end = output_ntsc ? /*NTSC*/10 : /*PAL*/12;
double hpulse_end = output_ntsc ? /*NTSC*/(hsync_hz * (4.7/*us*/ / 1000000)) : /*PAL*/(hsync_hz * (4.0/*us*/ / 1000000));
for (unsigned int s=0;s < samples;s++,audio += output_audio_channels) {
for (unsigned int c=0;c < output_audio_channels;c++) {
double s;
s = (double)audio[c] / 32768;
/* lowpass filter */
s = audio_hilopass.audiostate[c].filter(s);
/* preemphasis */
if (emulating_preemphasis) {
for (unsigned int i=0;i < output_audio_channels;i++) {
s = s + audio_linear_preemphasis_pre[i].highpass(s);
}
}
/* that faint "buzzing" noise on linear tracks because of audio/video crosstalk */
if (!output_vhs_hifi && linear_buzz > 0.000000001) {
const unsigned int oversample = 16;
for (unsigned int oi=0;oi < oversample;oi++) {
double t = ((((double)audio_proc_count * oversample) + oi) * hsync_hz) / output_audio_rate / oversample;
double hpos = fmod(t,1.0);
int vline = (int)fmod(floor(t + 0.0001/*fudge*/ - hpos),(double)vsync_lines / 2);
bool pulse = false;
if (hpos < hpulse_end)
pulse = true; // HSYNC
if (vline < vpulse_end)
pulse = true; // VSYNC
if (pulse)
s -= linear_buzz / oversample / 2;
}
}
/* analog limiting (when the signal is too loud) */
if (s > 1.0)
s = 1.0;
else if (s < -1.0)
s = -1.0;
/* hiss */
if (output_audio_hiss_level != 0)
s += ((double)(((int)((unsigned int)rand() % ((output_audio_hiss_level * 2) + 1))) - output_audio_hiss_level)) / 20000;
/* some VCRs (at least mine) will boost higher frequencies if playing linear tracks */
if (!output_vhs_hifi && vhs_linear_high_boost > 0)
s += audio_post_vhs_boost[c].highpass(s) * vhs_linear_high_boost;
/* deemphasis */
if (emulating_deemphasis) {
for (unsigned int i=0;i < output_audio_channels;i++) {
s = audio_linear_preemphasis_post[i].lowpass(s);
}
}
audio[c] = clips16(s * 32768);
}
audio_proc_count++;
}
}
static int parse_argv(int argc,char **argv) {
const char *a;
int i;
for (i=1;i < argc;) {
a = argv[i++];
if (*a == '-') {
do { a++; } while (*a == '-');
if (!strcmp(a,"h") || !strcmp(a,"help")) {
help(argv[0]);
return 1;
}
else if (!strcmp(a,"comp-phase-offset")) {
video_scanline_phase_shift_offset = atoi(argv[i++]);
}
else if (!strcmp(a,"comp-phase")) {
video_scanline_phase_shift = atoi(argv[i++]);
if (!(video_scanline_phase_shift == 0 || video_scanline_phase_shift == 90 ||
video_scanline_phase_shift == 180 || video_scanline_phase_shift == 270)) {
fprintf(stderr,"Invalid phase\n");
return 1;
}
}
else if (!strcmp(a,"width")) {
a = argv[i++];
if (a == NULL) return 1;
output_width = (int)strtoul(a,NULL,0);