-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathntsc.rs
1172 lines (1039 loc) · 40.4 KB
/
ntsc.rs
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
use std::cell::OnceCell;
use std::collections::VecDeque;
use core::f32::consts::PI;
use image::RgbImage;
use rand::{Rng, RngCore, SeedableRng};
use rand_xoshiro::Xoshiro256PlusPlus;
use rayon::prelude::*;
use simdnoise::NoiseBuilder;
use crate::{
filter::TransferFunction,
random::{Geometric, Seeder},
shift::{shift_row, shift_row_to, BoundaryHandling},
yiq_fielding::{YiqOwned, YiqView},
};
pub use crate::settings::*;
// 315/88 Mhz rate * 4
// TODO: why do we multiply by 4? composite-video-simulator does this for every filter and ntscqt defines NTSC_RATE the
// same way as we do here.
const NTSC_RATE: f32 = (315000000.00 / 88.0) * 4.0;
/// Create a simple constant-k lowpass filter with the given frequency cutoff, which can then be used to filter a signal.
pub fn make_lowpass(cutoff: f32, rate: f32) -> TransferFunction {
let time_interval = 1.0 / rate;
let tau = (cutoff * 2.0 * PI).recip();
let alpha = time_interval / (tau + time_interval);
TransferFunction::new(vec![alpha], vec![1.0, -(1.0 - alpha)])
}
/// Simulate three constant-k lowpass filters in a row by multiplying the coefficients. The original code
/// (composite-video-simulator and ntscqt) applies a lowpass filter 3 times in a row, but it's more efficient to
/// multiply the coefficients and just apply the filter once, which is mathematically equivalent.
pub fn make_lowpass_triple(cutoff: f32, rate: f32) -> TransferFunction {
let time_interval = 1.0 / rate;
let tau = (cutoff * 2.0 * PI).recip();
let alpha = time_interval / (tau + time_interval);
let tf = TransferFunction::new(vec![alpha], vec![1.0, -(1.0 - alpha)]);
&(&tf * &tf) * &tf
}
/// Create an IIR notch filter.
pub fn make_notch_filter(freq: f32, quality: f32) -> TransferFunction {
// Adapted from scipy and simplified
// https://github.com/scipy/scipy/blob/686422c4f0a71be1b4258309590fd3e9de102e18/scipy/signal/_filter_design.py#L5099-L5171
if !(0.0..=1.0).contains(&freq) {
panic!("Frequency outside valid range");
}
let bandwidth = (freq / quality) * PI;
let freq = freq * PI;
let beta = (bandwidth * 0.5).tan();
let gain = (1.0 + beta).recip();
let num = vec![gain, -2.0 * freq.cos() * gain, gain];
let den = vec![1.0, -2.0 * freq.cos() * gain, 2.0 * gain - 1.0];
TransferFunction::new(num, den)
}
/// Filter initial condition.
#[allow(dead_code)]
enum InitialCondition {
/// Convenience value--just use 0.
Zero,
/// Set the initial filter condition to a constant.
Constant(f32),
/// Set the initial filter condition to that of the first sample to be filtered.
FirstSample,
}
struct ScratchBuffer {
cell: OnceCell<Box<[f32]>>,
len: usize,
}
impl ScratchBuffer {
pub fn new(len: usize) -> Self {
ScratchBuffer {
cell: OnceCell::new(),
len,
}
}
pub fn get(&mut self) -> &mut [f32] {
_ = self
.cell
.get_or_init(|| vec![0f32; self.len].into_boxed_slice());
self.cell.get_mut().unwrap()
}
}
/// Apply a given IIR filter to each row of one color plane.
/// # Arguments
/// - `plane` - The entire data (width * height) for the plane to be filtered.
/// - `width` - The width of each row.
/// - `filter` - The filter to apply to the plane.
/// - `initial` - The initial steady-state value of the filter.
/// - `scale` - Scale the effect of the filter on the signal by this amount.
/// - `delay` - Offset the filter output backwards (to the left) by this amount.
fn filter_plane(
plane: &mut [f32],
width: usize,
filter: &TransferFunction,
initial: InitialCondition,
scale: f32,
delay: usize,
) {
plane.par_chunks_mut(width).for_each(|field| {
let initial = match initial {
InitialCondition::Zero => 0.0,
InitialCondition::Constant(c) => c,
InitialCondition::FirstSample => field[0],
};
filter.filter_signal_in_place(field, initial, scale, delay);
});
}
/// Settings common to each invocation of the effect. Passed to each individual effect function.
struct CommonInfo {
seed: u64,
frame_num: usize,
bandwidth_scale: f32,
}
fn luma_filter(frame: &mut YiqView, filter_mode: LumaLowpass) {
match filter_mode {
LumaLowpass::None => {}
LumaLowpass::Box => {
frame.y.par_chunks_mut(frame.dimensions.0).for_each(|y| {
let mut delay = VecDeque::<f32>::with_capacity(4);
delay.push_back(16.0 / 255.0);
delay.push_back(16.0 / 255.0);
delay.push_back(y[0]);
delay.push_back(y[1]);
let mut sum: f32 = delay.iter().sum();
let width = y.len();
for index in 0..width {
// Box-blur the signal.
let c = y[usize::min(index + 2, width - 1)];
sum -= delay.pop_front().unwrap();
delay.push_back(c);
sum += c;
y[index] = sum * 0.25;
}
});
}
LumaLowpass::Notch => filter_plane(
frame.y,
frame.dimensions.0,
&make_notch_filter(0.5, 2.0),
InitialCondition::FirstSample,
1.0,
0,
),
}
}
/// Apply a lowpass filter to the input chroma, emulating broadcast NTSC's bandwidth cutoffs.
/// (Well, almost--Wikipedia (https://en.wikipedia.org/wiki/YIQ) puts the Q bandwidth at 0.4 MHz, not 0.6. Although
/// that statement seems unsourced and I can't find any info on it...
fn composite_chroma_lowpass(frame: &mut YiqView, info: &CommonInfo) {
let i_filter = make_lowpass_triple(1300000.0, NTSC_RATE * info.bandwidth_scale);
let q_filter = make_lowpass_triple(600000.0, NTSC_RATE * info.bandwidth_scale);
let width = frame.dimensions.0;
filter_plane(frame.i, width, &i_filter, InitialCondition::Zero, 1.0, 2);
filter_plane(frame.q, width, &q_filter, InitialCondition::Zero, 1.0, 4);
}
/// Apply a less intense lowpass filter to the input chroma.
fn composite_chroma_lowpass_lite(frame: &mut YiqView, info: &CommonInfo) {
let filter = make_lowpass_triple(2600000.0, NTSC_RATE * info.bandwidth_scale);
let width = frame.dimensions.0;
filter_plane(frame.i, width, &filter, InitialCondition::Zero, 1.0, 1);
filter_plane(frame.q, width, &filter, InitialCondition::Zero, 1.0, 1);
}
/// Calculate the chroma subcarrier phase for a given row/field
fn chroma_phase_shift(
scanline_phase_shift: PhaseShift,
offset: i32,
frame_num: usize,
line_num: usize,
) -> usize {
(match scanline_phase_shift {
PhaseShift::Degrees90 | PhaseShift::Degrees270 => {
(frame_num as i32 + offset + ((line_num as i32) >> 1)) & 3
}
PhaseShift::Degrees180 => (((frame_num + line_num) & 2) as i32 + offset) & 3,
PhaseShift::Degrees0 => 0,
} & 3) as usize
}
const I_MULT: [f32; 4] = [1.0, 0.0, -1.0, 0.0];
const Q_MULT: [f32; 4] = [0.0, 1.0, 0.0, -1.0];
fn chroma_into_luma_line(
y: &mut [f32],
i: &mut [f32],
q: &mut [f32],
xi: usize,
subcarrier_amplitude: f32,
) {
y.iter_mut()
.zip(i.iter_mut().zip(q))
.enumerate()
.for_each(|(index, (y, (i, q)))| {
let phase = (index + (xi & 3)) & 3;
*y += (*i * I_MULT[phase] + *q * Q_MULT[phase]) * subcarrier_amplitude / 50.0;
// *i = 0.0;
// *q = 0.0;
});
}
/// Modulate the chrominance signal (I and Q planes) into the Y (luminance) plane.
/// TODO: sample rate
fn chroma_into_luma(
yiq: &mut YiqView,
info: &CommonInfo,
phase_shift: PhaseShift,
phase_offset: i32,
subcarrier_amplitude: f32,
) {
let width = yiq.dimensions.0;
let y_lines = yiq.y.par_chunks_mut(width);
let i_lines = yiq.i.par_chunks_mut(width);
let q_lines = yiq.q.par_chunks_mut(width);
y_lines
.zip(i_lines.zip(q_lines))
.enumerate()
.for_each(|(index, (y, (i, q)))| {
let xi = chroma_phase_shift(phase_shift, phase_offset, info.frame_num, index * 2);
chroma_into_luma_line(y, i, q, xi, subcarrier_amplitude);
});
}
#[inline]
fn demodulate_chroma(
chroma: f32,
index: usize,
xi: usize,
subcarrier_amplitude: f32,
i: &mut [f32],
q: &mut [f32],
) {
let width = i.len();
let chroma = (chroma * 50.0) / subcarrier_amplitude;
let offset = (index + (xi & 3)) & 3;
let i_modulated = -(chroma * I_MULT[offset]);
let q_modulated = -(chroma * Q_MULT[offset]);
// TODO: ntscQT seems to mess this up, giving chroma a "jagged" look reminiscent of the "dot crawl" artifact.
// Is that worth trying to replicate, or should it just be left like this?
if index < width - 1 {
i[index + 1] = i_modulated * 0.5;
q[index + 1] = q_modulated * 0.5;
}
i[index] += i_modulated;
q[index] += q_modulated;
if index > 0 {
i[index - 1] += i_modulated * 0.5;
q[index - 1] += q_modulated * 0.5;
}
}
/// Demodulate the chrominance signal using a box filter to separate it out.
fn luma_into_chroma_line_box(
y: &mut [f32],
i: &mut [f32],
q: &mut [f32],
xi: usize,
subcarrier_amplitude: f32,
) {
let mut delay = VecDeque::<f32>::with_capacity(4);
delay.push_back(16.0 / 255.0);
delay.push_back(16.0 / 255.0);
delay.push_back(y[0]);
delay.push_back(y[1]);
let mut sum: f32 = delay.iter().sum();
let width = y.len();
for index in 0..width {
// Box-blur the signal to get the luminance.
let c = y[usize::min(index + 2, width - 1)];
sum -= delay.pop_front().unwrap();
delay.push_back(c);
sum += c;
y[index] = sum * 0.25;
let chroma = c - y[index];
demodulate_chroma(chroma, index, xi, subcarrier_amplitude, i, q);
}
}
fn luma_into_chroma_line_iir(
y: &mut [f32],
scratch: &mut [f32],
i: &mut [f32],
q: &mut [f32],
filter: &TransferFunction,
delay: usize,
xi: usize,
subcarrier_amplitude: f32,
) {
let width = y.len();
filter.filter_signal_into(y, scratch, 0.0, 1.0, delay);
for index in 0..width {
let chroma = scratch[index] - y[index];
y[index] = scratch[index];
demodulate_chroma(chroma, index, xi, subcarrier_amplitude, i, q);
}
}
/// Demodulate the chroma signal from the Y (luma) plane back into the I and Q planes.
/// TODO: sample rate
fn luma_into_chroma(
yiq: &mut YiqView,
info: &CommonInfo,
filter_mode: ChromaDemodulationFilter,
scratch_buffer: &mut ScratchBuffer,
phase_shift: PhaseShift,
phase_offset: i32,
subcarrier_amplitude: f32,
) {
let width = yiq.dimensions.0;
match filter_mode {
ChromaDemodulationFilter::Box | ChromaDemodulationFilter::Notch => {
let y_lines = yiq.y.par_chunks_mut(width);
let i_lines = yiq.i.par_chunks_mut(width);
let q_lines = yiq.q.par_chunks_mut(width);
match filter_mode {
ChromaDemodulationFilter::Box => {
y_lines.zip(i_lines.zip(q_lines)).enumerate().for_each(
|(index, (y, (i, q)))| {
let xi = chroma_phase_shift(
phase_shift,
phase_offset,
info.frame_num,
index * 2,
);
luma_into_chroma_line_box(y, i, q, xi, subcarrier_amplitude);
},
);
}
ChromaDemodulationFilter::Notch => {
let scratch = scratch_buffer.get();
let filter: TransferFunction = make_notch_filter(0.5, 2.0);
(y_lines.zip(scratch.par_chunks_mut(width)))
.zip(i_lines.zip(q_lines))
.enumerate()
.for_each(|(index, ((y, scratch), (i, q)))| {
let xi = chroma_phase_shift(
phase_shift,
phase_offset,
info.frame_num,
index * 2,
);
luma_into_chroma_line_iir(
y,
scratch,
i,
q,
&filter,
1,
xi,
subcarrier_amplitude,
);
});
}
_ => unreachable!(),
}
}
ChromaDemodulationFilter::OneLineComb => {
let mut delay = Vec::from(&yiq.y[width..width * 2]);
let y_lines = yiq.y.chunks_mut(width);
let i_lines = yiq.i.chunks_mut(width);
let q_lines = yiq.q.chunks_mut(width);
y_lines
.zip(i_lines.zip(q_lines))
.enumerate()
.for_each(|(line_index, (y, (i, q)))| {
for index in 0..width {
let blended = (y[index] + delay[index]) * 0.5;
delay[index] = y[index];
let chroma = blended - y[index];
y[index] = blended;
let xi = chroma_phase_shift(
phase_shift,
phase_offset,
info.frame_num,
line_index * 2,
);
demodulate_chroma(chroma, index, xi, subcarrier_amplitude, i, q);
}
});
}
ChromaDemodulationFilter::TwoLineComb => {
// This holds the "previous" line--we overwrite in place so we need to cache the previous line's
// non-filtered value. It starts out as the second line in order to maintain the checkerboard pattern
// and essentially make the first line a 1-line comb filter.
let mut delay = Vec::from(&yiq.y[width..width * 2]);
for line_index in 0..yiq.num_rows() {
for sample_index in 0..width {
let prev_line = delay[sample_index];
let next_line = yiq
.y
.get((line_index + 1) * width + sample_index)
.cloned()
// On the last line, blend with the above line twice (making it an average of the 2) since
// there's no line after it to average with
.unwrap_or(prev_line);
let cur_line = &mut yiq.y[line_index * width + sample_index];
let blended = (*cur_line * 0.5) + (prev_line * 0.25) + (next_line * 0.25);
let chroma = blended - *cur_line;
delay[sample_index] = *cur_line;
*cur_line = blended;
let xi = chroma_phase_shift(
phase_shift,
phase_offset,
info.frame_num,
line_index * 2,
);
demodulate_chroma(
chroma,
sample_index,
xi,
subcarrier_amplitude,
&mut yiq.i[line_index * width..(line_index + 1) * width],
&mut yiq.q[line_index * width..(line_index + 1) * width],
);
}
}
}
};
}
/// We use a seeded RNG to generate random noise deterministically, but we don't want every pass which uses noise to use
/// the *same* noise. Each pass gets its own random seed which is mixed into the RNG.
mod noise_seeds {
pub const VIDEO_COMPOSITE: u64 = 0;
pub const VIDEO_CHROMA: u64 = 1;
pub const HEAD_SWITCHING: u64 = 2;
pub const TRACKING_NOISE: u64 = 3;
pub const VIDEO_CHROMA_PHASE: u64 = 4;
pub const EDGE_WAVE: u64 = 5;
pub const SNOW: u64 = 6;
pub const CHROMA_LOSS: u64 = 7;
}
/// Helper function to apply gradient noise to a single row of a single plane.
fn video_noise_line(
row: &mut [f32],
seeder: &Seeder,
index: usize,
frequency: f32,
intensity: f32,
) {
let width = row.len();
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seeder.clone().mix(index as u64).finalize());
let noise_seed = rng.next_u32();
let offset = rng.gen::<f32>() * width as f32;
let noise = NoiseBuilder::gradient_1d_offset(offset, width)
.with_seed(noise_seed as i32)
.with_freq(frequency)
.generate()
.0;
row.iter_mut().enumerate().for_each(|(x, pixel)| {
*pixel += noise[x] * 0.25 * intensity;
});
}
/// Add noise to an NTSC-encoded signal.
fn composite_noise(yiq: &mut YiqView, info: &CommonInfo, frequency: f32, intensity: f32) {
let width = yiq.dimensions.0;
let seeder = Seeder::new(info.seed)
.mix(noise_seeds::VIDEO_COMPOSITE)
.mix(info.frame_num);
yiq.y
.par_chunks_mut(width)
.enumerate()
.for_each(|(index, row)| {
video_noise_line(
row,
&seeder,
index,
frequency / info.bandwidth_scale,
intensity,
);
});
}
/// Add noise to the chrominance (I and Q) planes of a de-modulated signal.
fn chroma_noise(yiq: &mut YiqView, info: &CommonInfo, frequency: f32, intensity: f32) {
let width = yiq.dimensions.0;
let seeder = Seeder::new(info.seed)
.mix(noise_seeds::VIDEO_CHROMA)
.mix(info.frame_num);
yiq.i
.par_chunks_mut(width)
.zip(yiq.q.par_chunks_mut(width))
.enumerate()
.for_each(|(index, (i, q))| {
video_noise_line(
i,
&seeder,
index,
frequency / info.bandwidth_scale,
intensity,
);
video_noise_line(
q,
&seeder,
index,
frequency / info.bandwidth_scale,
intensity,
);
});
}
fn chroma_phase_offset_line(i: &mut [f32], q: &mut [f32], offset: f32) {
// Phase shift angle in radians. Mapped so that an intensity of 1.0 is a phase shift ranging from a full
// rotation to the left - a full rotation to the right.
let phase_shift = offset * PI * 2.0;
let (sin_angle, cos_angle) = phase_shift.sin_cos();
for (i, q) in i.iter_mut().zip(q.iter_mut()) {
// Treat (i, q) as a 2D vector and rotate it by the phase shift amount.
let rotated_i = (*i * cos_angle) - (*q * sin_angle);
let rotated_q = (*i * sin_angle) + (*q * cos_angle);
*i = rotated_i;
*q = rotated_q;
}
}
fn chroma_phase_error(yiq: &mut YiqView, intensity: f32) {
let width = yiq.dimensions.0;
yiq.i
.par_chunks_mut(width)
.zip(yiq.q.par_chunks_mut(width))
.for_each(|(i, q)| {
chroma_phase_offset_line(i, q, intensity);
});
}
/// Add per-scanline chroma phase error.
fn chroma_phase_noise(yiq: &mut YiqView, info: &CommonInfo, intensity: f32) {
let width = yiq.dimensions.0;
let seeder = Seeder::new(info.seed)
.mix(noise_seeds::VIDEO_CHROMA_PHASE)
.mix(info.frame_num);
yiq.i
.par_chunks_mut(width)
.zip(yiq.q.par_chunks_mut(width))
.enumerate()
.for_each(|(index, (i, q))| {
// Phase shift angle in radians. Mapped so that an intensity of 1.0 is a phase shift ranging from a full
// rotation to the left - a full rotation to the right.
let phase_shift = (seeder.clone().mix(index).finalize::<f32>() - 0.5) * 2.0 * intensity;
chroma_phase_offset_line(i, q, phase_shift);
});
}
/// Emulate VHS head-switching at the bottom of the image.
fn head_switching(
yiq: &mut YiqView,
info: &CommonInfo,
num_rows: usize,
offset: usize,
shift: f32,
) {
if offset > num_rows {
return;
}
let num_affected_rows = num_rows - offset;
let width = yiq.dimensions.0;
let height = yiq.num_rows();
// Handle cases where the number of affected rows exceeds the number of actual rows in the image
let start_row = height.max(num_affected_rows) - num_affected_rows;
let affected_rows = &mut yiq.y[start_row * width..];
let cut_off_rows = if num_affected_rows > height {
num_affected_rows - height
} else {
0
};
let seeder = Seeder::new(info.seed)
.mix(noise_seeds::HEAD_SWITCHING)
.mix(info.frame_num);
affected_rows
.par_chunks_mut(width)
.enumerate()
.for_each(|(index, row)| {
let index = num_affected_rows - (index + cut_off_rows);
let row_shift = shift * ((index + offset) as f32 / num_rows as f32).powf(1.5);
shift_row(
row,
(row_shift + (seeder.clone().mix(index).finalize::<f32>() - 0.5))
* info.bandwidth_scale,
BoundaryHandling::Constant(0.0),
);
});
}
/// Helper function for generating "snow".
fn row_speckles<R: Rng>(
row: &mut [f32],
rng: &mut R,
intensity: f32,
anisotropy: f32,
bandwidth_scale: f32,
) {
let intensity = intensity as f64;
let anisotropy = anisotropy as f64;
// Transition smoothly from a flat function that always returns `intensity`, to a step function that returns
// 1.0 with a probability of `intensity` and 0.0 with a probability of `1.0 - intensity`. In-between states
// look like S-curves with increasing sharpness.
// As a bonus, the integral of this function over (0, 1) as we transition from 0% to 100% anisotropy is *almost*
// constant, meaning there's approximately the same amount of snow each time.
let logistic_factor = ((rng.gen::<f64>() - intensity)
/ (intensity * (1.0 - intensity) * (1.0 - anisotropy)))
.exp();
let mut line_snow_intensity =
anisotropy / (1.0 + logistic_factor) + intensity * (1.0 - anisotropy);
// At maximum intensity (1.0), the line just gets completely whited out. 0.125 intensity looks more reasonable.
line_snow_intensity *= 0.125;
line_snow_intensity = line_snow_intensity.clamp(0.0, 1.0);
if line_snow_intensity <= 0.0 {
return;
}
// Turn each pixel into "snow" with probability snow_intensity * intensity_scale
// We can simulate the distance between each "snow" pixel with a geometric distribution which avoids having to
// loop over every pixel
let dist = Geometric::new(line_snow_intensity);
let mut pixel_idx = 0usize;
loop {
pixel_idx += rng.sample(&dist);
if pixel_idx >= row.len() {
break;
}
let transient_len: f32 = rng.gen_range(8.0..=64.0) * bandwidth_scale;
let transient_freq = rng.gen_range(transient_len * 3.0..=transient_len * 5.0);
for i in pixel_idx..(pixel_idx + transient_len.ceil() as usize).min(row.len()) {
let x = (i - pixel_idx) as f32;
// Simulate transient with sin(pi*x / 4) * (1 - x/len)^2
row[i] += ((x * PI) / transient_freq).cos()
* (1.0 - x / transient_len).powi(2)
* rng.gen_range(-1.0..2.0);
}
// Make sure we advance the pixel index each time. Our geometric distribution gives us the time between
// successive events, which can be 0 for very high probabilities.
pixel_idx += 1;
}
}
/// Emulate VHS tracking error/noise.
/// TODO: this is inaccurate and doesn't let you control the position of the noise.
/// I need to revamp this at some point.
fn tracking_noise(
yiq: &mut YiqView,
info: &CommonInfo,
num_rows: usize,
wave_intensity: f32,
snow_intensity: f32,
snow_anisotropy: f32,
noise_intensity: f32,
) {
let width = yiq.dimensions.0;
let height = yiq.num_rows();
let mut seeder = Seeder::new(info.seed)
.mix(noise_seeds::TRACKING_NOISE)
.mix(info.frame_num);
let noise_seed = seeder.clone().mix(0).finalize::<i32>();
let offset = seeder.clone().mix(1).finalize::<f32>() * yiq.num_rows() as f32;
seeder = seeder.mix(2);
let shift_noise = NoiseBuilder::gradient_1d_offset(offset, num_rows)
.with_seed(noise_seed)
.with_freq(0.5)
.generate()
.0;
// Handle cases where the number of affected rows exceeds the number of actual rows in the image
let start_row = height.max(num_rows) - num_rows;
let affected_rows = &mut yiq.y[start_row * width..];
let cut_off_rows = if num_rows > height {
num_rows - height
} else {
0
};
affected_rows
.par_chunks_mut(width)
.enumerate()
.for_each(|(index, row)| {
let index = index + cut_off_rows;
// This iterates from the top down. Increase the intensity as we approach the bottom of the picture.
let intensity_scale = index as f32 / num_rows as f32;
shift_row(
row,
shift_noise[index] * intensity_scale * wave_intensity * 0.25 * info.bandwidth_scale,
BoundaryHandling::Constant(0.0),
);
video_noise_line(
row,
&seeder,
index,
0.25 / info.bandwidth_scale,
intensity_scale.powi(2) * noise_intensity * 4.0,
);
row_speckles(
row,
&mut Xoshiro256PlusPlus::seed_from_u64(seeder.clone().mix(index).finalize()),
snow_intensity * intensity_scale.powi(2),
snow_anisotropy,
info.bandwidth_scale,
);
});
}
/// Add random bits of "snow" to an NTSC-encoded signal.
fn snow(yiq: &mut YiqView, info: &CommonInfo, intensity: f32, anisotropy: f32) {
let seeder = Seeder::new(info.seed)
.mix(noise_seeds::SNOW)
.mix(info.frame_num);
yiq.y
.par_chunks_mut(yiq.dimensions.0)
.enumerate()
.for_each(|(index, row)| {
let line_seed = seeder.clone().mix(index);
row_speckles(
row,
&mut Xoshiro256PlusPlus::seed_from_u64(line_seed.finalize()),
intensity,
anisotropy,
info.bandwidth_scale,
);
});
}
/// Offset the chrominance (I and Q) planes horizontally and/or vertically.
/// Note how the horizontal shift is a float (the signal is continuous), but the vertical shift is an int (each scanline
/// is discrete).
fn chroma_delay(yiq: &mut YiqView, info: &CommonInfo, offset: (f32, isize)) {
let horiz_shift = offset.0 * info.bandwidth_scale;
let copy_or_shift = |src: &mut [f32], dst: &mut [f32]| {
if offset.0.abs() == 0.0 {
dst.copy_from_slice(src);
} else {
shift_row_to(src, dst, horiz_shift, BoundaryHandling::Constant(0.0));
}
};
let width = yiq.dimensions.0;
let height = yiq.num_rows();
if offset.1 == 0 {
// Only a horizontal shift is necessary. We can do this in-place easily.
yiq.i
.par_chunks_mut(width)
.zip(yiq.q.par_chunks_mut(width))
.for_each(|(i, q)| {
shift_row(i, horiz_shift, BoundaryHandling::Constant(0.0));
shift_row(q, horiz_shift, BoundaryHandling::Constant(0.0));
});
} else if offset.1 > 0 {
// Some finagling is required to shift vertically. This branch shifts the chroma planes downwards.
let offset = offset.1 as usize;
// Starting from the bottom, copy (or write a horizontally-shifted copy of) each row downwards.
for dst_row_idx in (0..height).rev() {
let (i_src_part, i_dst_part) = yiq.i.split_at_mut(dst_row_idx * width);
let (q_src_part, q_dst_part) = yiq.q.split_at_mut(dst_row_idx * width);
let dst_row_range = 0..width;
let dst_i = &mut i_dst_part[dst_row_range.clone()];
let dst_q = &mut q_dst_part[dst_row_range.clone()];
if dst_row_idx < offset {
dst_i.fill(0.0);
dst_q.fill(0.0);
} else {
let src_row_idx = dst_row_idx - offset;
let src_row_range = src_row_idx * width..(src_row_idx + 1) * width;
let src_i = &mut i_src_part[src_row_range.clone()];
let src_q = &mut q_src_part[src_row_range.clone()];
copy_or_shift(src_i, dst_i);
copy_or_shift(src_q, dst_q);
}
}
} else {
let offset = (-offset.1) as usize;
// Starting from the top, copy (or write a horizontally-shifted copy of) each row upwards.
for dst_row_idx in 0..height {
let (i_dst_part, i_src_part) = yiq.i.split_at_mut((dst_row_idx + 1) * width);
let (q_dst_part, q_src_part) = yiq.q.split_at_mut((dst_row_idx + 1) * width);
let dst_row_range = dst_row_idx * width..(dst_row_idx + 1) * width;
let dst_i = &mut i_dst_part[dst_row_range.clone()];
let dst_q = &mut q_dst_part[dst_row_range.clone()];
if dst_row_idx >= height.max(offset) - offset {
dst_i.fill(0.0);
dst_q.fill(0.0);
} else {
let src_row_range = (offset - 1) * width..offset * width;
let src_i = &mut i_src_part[src_row_range.clone()];
let src_q = &mut q_src_part[src_row_range.clone()];
copy_or_shift(src_i, dst_i);
copy_or_shift(src_q, dst_q);
}
}
}
}
/// Emulate VHS waviness / horizontal shift noise.
fn vhs_edge_wave(yiq: &mut YiqView, info: &CommonInfo, settings: &VHSEdgeWaveSettings) {
let width = yiq.dimensions.0;
let height = yiq.num_rows();
let seeder = Seeder::new(info.seed).mix(noise_seeds::EDGE_WAVE);
let noise_seed: i32 = seeder.clone().mix(0).finalize();
let offset = seeder.mix(1).finalize::<f32>() * yiq.num_rows() as f32;
let noise =
NoiseBuilder::fbm_2d_offset(offset, height, info.frame_num as f32 * settings.speed, 1)
.with_seed(noise_seed)
.with_freq(settings.frequency)
.with_octaves(settings.detail.clamp(1, 5) as u8)
// Yes, they got the lacunarity backwards by making it apply to frequency instead of scale.
// 2.0 *halves* the scale each time because it doubles the frequency.
.with_lacunarity(2.0)
.with_gain(std::f32::consts::FRAC_1_SQRT_2)
.generate()
.0;
for plane in [&mut yiq.y, &mut yiq.i, &mut yiq.q] {
plane
.par_chunks_mut(width)
.enumerate()
.for_each(|(index, row)| {
let shift =
(noise[index] / 0.022) * settings.intensity * 0.5 * info.bandwidth_scale;
shift_row(row, shift, BoundaryHandling::Extend);
})
}
}
/// Drop out the chrominance signal from random lines.
fn chroma_loss(yiq: &mut YiqView, info: &CommonInfo, intensity: f32) {
let width = yiq.dimensions.0;
let height = yiq.num_rows();
let seed = Seeder::new(info.seed)
.mix(noise_seeds::CHROMA_LOSS)
.mix(info.frame_num)
.finalize();
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
// We blank out each row with a probability of `intensity` (0 to 1). Instead of going over each row and checking
// whether to blank out the chroma, use a geometric distribution to simulate that process and tell us which rows
// to blank.
let dist = Geometric::new(intensity as f64);
let mut row_idx = 0usize;
loop {
row_idx += rng.sample(&dist);
if row_idx >= height {
break;
}
let row_range = row_idx * width..(row_idx + 1) * width;
yiq.i[row_range.clone()].fill(0.0);
yiq.q[row_range.clone()].fill(0.0);
row_idx += 1;
}
}
/// Vertically blend each chroma scanline with the one above it, as VHS does.
fn chroma_vert_blend(yiq: &mut YiqView) {
let width = yiq.dimensions.0;
let mut delay_i = vec![0f32; width];
let mut delay_q = vec![0f32; width];
yiq.i
.chunks_mut(width)
.zip(yiq.q.chunks_mut(width))
.for_each(|(i_row, q_row)| {
// TODO: check if this is faster than interleaved (I think the cache locality is better this way)
i_row.iter_mut().enumerate().for_each(|(index, i)| {
let c_i = *i;
*i = (delay_i[index] + c_i) * 0.5;
delay_i[index] = c_i;
});
q_row.iter_mut().enumerate().for_each(|(index, q)| {
let c_q = *q;
*q = (delay_q[index] + c_q) * 0.5;
delay_q[index] = c_q;
});
});
}
impl NtscEffect {
pub fn apply_effect_to_yiq(&self, yiq: &mut YiqView, frame_num: usize) {
let width = yiq.dimensions.0;
let seed = self.random_seed as u32 as u64;
let info = CommonInfo {
seed,
frame_num,
bandwidth_scale: self.bandwidth_scale,
};
let mut scratch_buffer = ScratchBuffer::new(yiq.y.len());
luma_filter(yiq, self.input_luma_filter);
match self.chroma_lowpass_in {
ChromaLowpass::Full => {
composite_chroma_lowpass(yiq, &info);
}
ChromaLowpass::Light => {
composite_chroma_lowpass_lite(yiq, &info);
}
ChromaLowpass::None => {}
};
chroma_into_luma(
yiq,
&info,
self.video_scanline_phase_shift,
self.video_scanline_phase_shift_offset,
50.0,
);
if self.composite_preemphasis > 0.0 {
let preemphasis_filter = make_lowpass(
(315000000.0 / 88.0 / 2.0) * self.bandwidth_scale,
NTSC_RATE * self.bandwidth_scale,
);
filter_plane(
yiq.y,
width,
&preemphasis_filter,
InitialCondition::Zero,
-self.composite_preemphasis,
0,
);
}
if self.composite_noise_intensity > 0.0 {
composite_noise(yiq, &info, 0.25, self.composite_noise_intensity);
}
if self.snow_intensity > 0.0 && self.bandwidth_scale > 0.0 {
snow(yiq, &info, self.snow_intensity * 0.01, self.snow_anisotropy);