-
Notifications
You must be signed in to change notification settings - Fork 1
/
palgen_persune.py
1431 lines (1250 loc) · 56.9 KB
/
palgen_persune.py
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
# palgen NES
# Copyright (C) 2024 Persune
# inspired by PalGen, Copyright (C) 2018 DragWx <https://github.com/DragWx>
# testing out the concepts from https://www.nesdev.org/wiki/NTSC_video#Composite_decoding
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import os, sys
import argparse
import numpy as np
VERSION = "0.15.0"
def parse_argv(argv):
parser=argparse.ArgumentParser(
description="yet another NES palette generator",
epilog="version " + VERSION)
# output options
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="debug messages")
parser.add_argument(
"--skip-plot",
action="store_true",
help="skips showing the palette plot")
parser.add_argument(
"-o",
"--output",
type=str,
help="file output path")
parser.add_argument(
"-f",
"--file-format",
choices=[
".pal uint8",
".pal double",
".pal Jasc",
".gpl",
".png",
".txt HTML hex",
".txt MediaWiki",
".h uint8_t",
],
default=".pal uint8",
help="file output format. default = \".pal uint8\"")
parser.add_argument(
"-e",
"--emphasis",
action="store_true",
help="include emphasis entries")
parser.add_argument(
"-t",
"--test-image",
type=str,
help="use 256x240 uint16 raw binary PPU frame buffer for palette proofreading")
# visualization options
parser.add_argument(
"-r",
"--render-img",
type=str,
help="render views and diagrams as images in docs folder with the provided file extension.")
parser.add_argument(
"-w",
"--waveforms",
action="store_true",
help="view composite waveforms")
parser.add_argument(
"-p",
"--phase-QAM",
action="store_true",
help="view QAM demodulation")
# generation options
parser.add_argument(
"-n",
"--normalize",
type=str,
help="normalize all colors within gamut by scaling values",
choices=[
"scale",
"scale clip negative"
])
parser.add_argument(
"-ppu",
"--ppu",
type=str,
help="PPU chip used for generating colors. default = 2C02",
choices=[
"2C02",
"2C03",
"2C04-0000",
"2C04-0001",
"2C04-0002",
"2C04-0003",
"2C04-0004",
"2C05-99",
"2C07",
],
default = "2C02")
parser.add_argument(
"-c",
"--clip",
type=str,
help="clips out-of-gamut RGB colors",
choices=[
"darken",
"desaturate"
])
# color decoding options
parser.add_argument(
"-bri",
"--brightness",
type = np.float64,
help = "luma brightness delta in IRE units, default = 0.0",
default = 0.0)
parser.add_argument(
"-con",
"--contrast",
type = np.float64,
help = "luma contrast factor, default = 1.0",
default = 1.0)
parser.add_argument(
"-hue",
"--hue",
type = np.float64,
help = "chroma hue angle delta, in degrees, default = 0.0",
default = 0)
parser.add_argument(
"-sat",
"--saturation",
type = np.float64,
help ="chroma saturation factor, default = 1.0",
default = 1)
parser.add_argument(
"-blp",
"--black-point",
type = np.float64,
help = "black point, in IRE units, default = 0 IRE")
parser.add_argument(
"-whp",
"--white-point",
type = np.float64,
help = "white point, in IRE units, default = level $20")
parser.add_argument(
"-gai",
"--gain",
type = np.float64,
help = "gain adjustment to signal before decoding, in IRE units, default = 0.0",
default = 0.0)
parser.add_argument(
"-gam",
"--gamma",
type = np.float64,
help = "if defined, will apply a simple OETF gamma transfer function instead, where the EOTF function is assumed to be gamma 2.2.")
parser.add_argument(
"--delay-line-filter",
action = "store_true",
help = "use 1D delay line comb filter decoding instead of single-line decoding")
parser.add_argument(
"-axs",
"--axis-shift",
type = str,
help = "axis adjustment for R-Y and G-Y like Sony CXA2025AS, default = None",
choices=[
"None",
"CXA2025AS_JP",
"CXA2025AS_US",
"bisqwit_NTSC_1953",
],
default = "None")
parser.add_argument(
"-bsd",
"--burst-saturation-disable",
action = "store_true",
help = "disable using colorburst amplitude as saturation reference")
parser.add_argument(
"-spg",
"--sinusoidal-peak-generation",
action = "store_true",
help = "generate sine waves in composite encoding instead of square waves")
# analog effects options
parser.add_argument(
"-phs",
"--phase-skew",
type = np.float64,
help = "differential phase distortion for composite PPUs, in degrees, default = 0.0",
default = 0)
parser.add_argument(
"-aps",
"--antiemphasis-phase-skew",
type = np.float64,
help = "additonal phase distortion on colors $x2/$x6/$xA for composite PPUs, in degrees, default = 0.0",
default = 0)
parser.add_argument(
"-ela",
"--emphasis-luma-attenuation",
type = np.float64,
help = "additonal luma brightness on colors $x4/$x8/$xC for composite PPUs, in voltage units, default = 0.0",
default = 0)
# colorimetry options
parser.add_argument(
"-rfc",
"--reference-colorspace",
type = str,
help = "use colour.RGB_COLOURSPACES reference colorspace, default = \"SMPTE C\"",
default = 'SMPTE C')
parser.add_argument(
"-dsc",
"--display-colorspace",
type = str,
help = "use colour.RGB_COLOURSPACES display colorspace, default = \"sRGB\"",
default = 'sRGB')
parser.add_argument(
"-cat",
"--chromatic-adaptation-transform",
type = str,
help = "chromatic adaptation transform method, default = None",
default = None)
parser.add_argument(
"-ict",
"--inverse-chromatic-transform",
action="store_true",
help = "invert direction of chromatic adaptation transform method (from display to reference colorspace)")
parser.add_argument(
"-oetf",
"--opto-electronic",
type=str,
help="applies \"colour.models\" color component transform function to use as opto-electronic transform function override",
)
parser.add_argument(
"-eotf",
"--electro-optic",
type=str,
help="applies \"colour.models\" color component transform function to use as electro-optic transform function override",
)
parser.add_argument(
"--opto-electronic-disable",
action = "store_true",
help = "disable converting linear light to linear signal")
parser.add_argument(
"--electro-optic-disable",
action = "store_true",
help = "disable converting linear signal to linear light")
parser.add_argument(
"-cld",
"--colorimetry-disable",
action = "store_true",
help = "disable all colorimetry functions")
# colorimetry reference RGB and whitepoint primaries
parser.add_argument(
"-rpr",
"--reference-primaries-r",
type = np.float64,
nargs=2,
help = "set custom reference color primary R, in CIE xy chromaticity coordinates")
parser.add_argument(
"-rpg",
"--reference-primaries-g",
type = np.float64,
nargs=2,
help = "set custom reference color primary G, in CIE xy chromaticity coordinates")
parser.add_argument(
"-rpb",
"--reference-primaries-b",
type = np.float64,
nargs=2,
help = "set custom reference color primary B, in CIE xy chromaticity coordinates")
parser.add_argument(
"-rpw",
"--reference-primaries-w",
type = np.float64,
nargs=2,
help = "set custom reference whitepoint, in CIE xy chromaticity coordinates")
# colorimetry display RGB and whitepoint primaries
parser.add_argument(
"-dpr",
"--display-primaries-r",
type = np.float64,
nargs=2,
help = "set custom display color primary R, in CIE xy chromaticity coordinates")
parser.add_argument(
"-dpg",
"--display-primaries-g",
type = np.float64,
nargs=2,
help = "set custom display color primary G, in CIE xy chromaticity coordinates")
parser.add_argument(
"-dpb",
"--display-primaries-b",
type = np.float64,
nargs=2,
help = "set custom display color primary B, in CIE xy chromaticity coordinates")
parser.add_argument(
"-dpw",
"--display-primaries-w",
type = np.float64,
nargs=2,
help = "set custom display whitepoint, in CIE xy chromaticity coordinates")
return parser.parse_args(argv[1:])
# matrix function to convert YUV to YIQ and vice-versa
IQ_tilt = np.radians(33)
YUV_YIQ = np.array([
[1, 0, 0],
[0, np.cos(IQ_tilt), np.sin(IQ_tilt)],
[0, -np.sin(IQ_tilt), np.cos(IQ_tilt)]
], np.float64)
# B-Y and R-Y reduction factors
# S170m-2004.pdf: Composite Analog Video Signal NTSC for Studio Applications. Page 16.
BY_rf = 0.492111
RY_rf = 0.877283
# derived from the NTSC base matrix of luminance and color-difference
# S170m-2004.pdf: Composite Analog Video Signal NTSC for Studio Applications. Page 4.
RGB_to_YUV = np.array([
[ 0.299, 0.587, 0.114],
[-0.299*BY_rf, -0.587*BY_rf, 0.886*BY_rf],
[ 0.701*RY_rf, -0.587*RY_rf, -0.114*RY_rf]
], np.float64)
# derived from https://forums.nesdev.org/viewtopic.php?p=172817#p172817
# coefficients shifted up by 6 decimals
YIQ_to_RGB_bisqwit = np.array([
[1, 1.994681 , 0.9915742],
[1, 0.09151351, -0.6334805],
[1, -1.012984 , 1.667217 ]
], np.float64)
RGB_to_YIQ_bisqwit = np.linalg.inv(YIQ_to_RGB_bisqwit)
RGB_to_YUV_bisqwit = np.array([
RGB_to_YIQ_bisqwit[0,:],
((RGB_to_YIQ_bisqwit[2,:]*np.sin(IQ_tilt)) - (RGB_to_YIQ_bisqwit[1,:]*np.cos(IQ_tilt))),
((RGB_to_YIQ_bisqwit[1,:]*np.sin(IQ_tilt)) + (RGB_to_YIQ_bisqwit[2,:]*np.cos(IQ_tilt)))
], np.float64)
YUV_to_RGB_bisqwit = np.linalg.inv(RGB_to_YUV_bisqwit)
# thanks, NewRisingSun!
# Sony CXA2025AS axis offsets from the datasheet
YUV_to_RGB = np.linalg.inv(RGB_to_YUV)
CXA_JP_RY_angle = 95
CXA_JP_RY_gain = 0.78 / BY_rf
CXA_JP_GY_angle = 240
CXA_JP_GY_gain = 0.30 / BY_rf
CXA_US_RY_angle = 112
CXA_US_RY_gain = 0.83 / BY_rf
CXA_US_GY_angle = 252
CXA_US_GY_gain = 0.30 / BY_rf
YUV_to_RGB_CXA_JP = np.array([
[YUV_to_RGB[0,0], np.sin(CXA_JP_RY_angle)*CXA_JP_RY_gain*YUV_to_RGB[0,1], np.cos(CXA_JP_RY_angle)*CXA_JP_RY_gain*YUV_to_RGB[0,2]],
[YUV_to_RGB[1,0], np.sin(CXA_JP_GY_angle)*CXA_JP_GY_gain*YUV_to_RGB[1,1], np.cos(CXA_JP_GY_angle)*CXA_JP_GY_gain*YUV_to_RGB[1,2]],
YUV_to_RGB[2,:]
], np.float64)
YUV_to_RGB_CXA_US = np.array([
[YUV_to_RGB[0,0], np.sin(CXA_US_RY_angle)*CXA_US_RY_gain*YUV_to_RGB[0,1], np.cos(CXA_US_RY_angle)*CXA_US_RY_gain*YUV_to_RGB[0,2]],
[YUV_to_RGB[1,0], np.sin(CXA_US_GY_angle)*CXA_US_GY_gain*YUV_to_RGB[1,1], np.cos(CXA_US_GY_angle)*CXA_US_GY_gain*YUV_to_RGB[1,2]],
YUV_to_RGB[2,:]
], np.float64)
# signal LUTs
# voltage highs and lows
# from https://forums.nesdev.org/viewtopic.php?p=159266#p159266
# signal[4][2][2] $0x-$3x, $x0/$xD, no emphasis/emphasis
signal_table_composite = np.array([
[
[ 0.616, 0.500 ],
[ 0.228, 0.192 ]
],
[
[ 0.840, 0.676 ],
[ 0.312, 0.256 ]
],
[
[ 1.100, 0.896 ],
[ 0.552, 0.448 ]
],
[
[ 1.100, 0.896 ],
[ 0.880, 0.712 ]
]
], np.float64)
# colorburst[2] colorburst low, colorburst high
colorburst_table_composite = np.array([0.148, 0.524], np.float64)
composite_black = signal_table_composite[1, 1, 0]
composite_white = signal_table_composite[3, 0, 0]
# figure plotting for palette preview
# TODO: interactivity
def palette_plot(RGB_buffer,
RGB_uncorrected,
emphasis,
all_emphasis = False,
export_diagrams = False,
export_img = False,
args=None,
s_colorspace = None,
t_colorspace = None):
if (args.skip_plot and not (export_diagrams or export_img)):
return
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import colour.plotting.diagrams
# if emphasis enabled, reshape to single emphasis permutation
if (args.emphasis):
RGB_sub = RGB_buffer.reshape(8,4,16,3)[emphasis]
RGB_sub_raw = RGB_uncorrected.reshape(8,4,16,3)[emphasis]
else:
RGB_sub = RGB_buffer
RGB_sub_raw = RGB_uncorrected
fig = plt.figure(tight_layout=True, dpi=96)
gs = gridspec.GridSpec(2, 2)
ax0 = fig.add_subplot(gs[1, 1])
ax1 = fig.add_subplot(gs[0, 1], projection='polar')
# preview on indexed image (if provided)
if (args.test_image is not None and (all_emphasis or not args.emphasis)):
ax2 = fig.add_subplot(gs[0, 0])
ax3 = fig.add_subplot(gs[1, 0])
with open(args.test_image, mode="rb") as index_file:
index_image = np.reshape(np.frombuffer(index_file.read(), dtype=np.uint16), (240, 256))
preview_image = np.empty([240,256,3], np.float64)
for y in range(index_image.shape[0]):
for x in range(index_image.shape[1]):
preview_image[y,x] = RGB_sub[(index_image[y,x] >> 4), (index_image[y,x] & 0x0F)]
ax3.set_title("Palette preview")
ax3.imshow(preview_image)
if (export_img):
from PIL import Image
image_filename = os.path.splitext(args.test_image)[0]
imageout = Image.fromarray(np.ubyte(np.around(preview_image * 255)))
imageout.save("{0}.png".format(image_filename))
imageout.close()
else:
ax2 = fig.add_subplot(gs[:, 0])
if (export_diagrams):
fig.suptitle('NES palette (emphasis = {0:03b})'.format(emphasis))
else:
fig.suptitle('NES palette')
# colors
ax0.set_title("Color swatches")
ax0.imshow(RGB_sub)
# polar plot
YUV_calc = np.einsum('ij,klj->kli', RGB_to_YUV, RGB_sub, dtype=np.float64)
color_theta = np.arctan2(YUV_calc[:, :, 2], YUV_calc[:, :, 1])
color_r = YUV_calc[:, :, 0]
ax1.set_title("RGB color phase")
ax1.set_yticklabels([])
ax1.axis([0, 2*np.pi, 0, 1])
ax1.scatter(color_theta, color_r, c=np.reshape(RGB_sub,(RGB_sub.shape[0]*RGB_sub.shape[1], 3)), marker=None, s=color_r*500, zorder=3)
# CIE graph
colour.plotting.plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931(
RGB_sub_raw,
colourspace=s_colorspace,
show_whitepoints=False,
scatter_kwargs=dict(c=np.reshape(RGB_sub_raw,(RGB_sub_raw.shape[0]*16, 3)),alpha=0.1),
plot_kwargs=dict(color="gray"),
figure=fig,
axes=ax2,
standalone=False,
show_diagram_colours=False,
show_spectral_locus=True,
spectral_locus_colours='RGB',
transparent_background=False)
colour.plotting.plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931(
RGB_sub,
colourspace=t_colorspace,
show_whitepoints=False,
scatter_kwargs=dict(c=np.reshape(RGB_sub,(RGB_sub.shape[0]*16, 3))),
plot_kwargs=dict(color="red"),
figure=fig,
axes=ax2,
standalone=False,
show_diagram_colours=False,
show_spectral_locus=True,
spectral_locus_colours='RGB',
transparent_background=False)
ax2.set_title("CIE 1931 chromaticity diagram")
ax2.grid(which='both', color='grey', linewidth=0.5, linestyle='-', alpha=0.2)
ax2.axis([0, 1, 0, 1])
ax2.set_aspect('equal', 'box')
fig.set_size_inches(20, 11.25)
if (args.test_image is not None and (all_emphasis or not args.emphasis)):
# only tighten the layout if the palette preview is enabled
fig.tight_layout()
if (export_diagrams):
plt.savefig("docs/palette preview emphasis {0:03}.{1}".format(emphasis, args.render_img))
elif (export_img):
plt.savefig("docs/palette preview.{0}".format(args.render_img))
if not (args.skip_plot):
plt.show()
else:
plt.show()
plt.close()
def composite_QAM_plot(voltage_buffer,
U_comb,
V_comb,
U_decode,
V_decode,
U_buffer,
V_buffer,
buffer_size,
emphasis,
luma,
hue,
sequence_counter,
args=None,
signal_black_point=None,
signal_white_point=None):
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(tight_layout=True)
gs = gridspec.GridSpec(3, 2)
axY = fig.add_subplot(gs[0,0])
axU = fig.add_subplot(gs[1,0])
axV = fig.add_subplot(gs[2,0])
ax1 = fig.add_subplot(gs[:,1], projection='polar')
fig.suptitle("QAM demodulating ${0:02X} emphasis {1:03b}".format((luma<<4 | hue), emphasis))
x = np.arange(0,buffer_size)
Y_avg = np.average(voltage_buffer[0])
U_avg = np.average(U_buffer)
V_avg = np.average(V_buffer)
range_axis = ((signal_white_point / (signal_white_point - signal_black_point)) - signal_black_point) * 140
axY.set_title("Y decoding")
axY.set_ylabel("IRE")
axY.axis([0, buffer_size, -50, range_axis])
axY.plot(x, voltage_buffer[0], 'o-', linewidth=0.7, label='composite signal')
if (args.delay_line_filter):
axY.plot(x, voltage_buffer[1], 'o-', linewidth=0.7, label='composite signal delay')
axY.plot(x, np.full((buffer_size), Y_avg), 'o-', linewidth=0.7, label='Y value = {:< z.3f}'.format(Y_avg))
axY.legend(loc='lower right')
axU.set_title("U decoding")
axU.set_ylabel("IRE")
axU.axis([0, buffer_size, -range_axis, range_axis])
axU.plot(x, U_comb, 'o-', linewidth=0.7, label='raw U signal')
axU.plot(x, U_decode * 140 / 2, 'o-', linewidth=0.7, label='U subcarrier')
axU.plot(x, U_buffer, 'o-', linewidth=0.7, label='demodulated U signal')
axU.plot(x, np.full((buffer_size), U_avg), 'o-', linewidth=0.7, label='U value = {:< z.3f}'.format(U_avg))
axU.legend(loc='lower right')
axV.set_title("V decoding")
axV.set_ylabel("IRE")
axV.axis([0, buffer_size, -range_axis, range_axis])
axV.plot(x, V_comb, 'o-', linewidth=0.7, label='raw V signal')
axV.plot(x, V_decode * 140 / 2, 'o-', linewidth=0.7, label='V subcarrier')
axV.plot(x, V_buffer, 'o-', linewidth=0.7, label='demodulated V signal')
axV.plot(x, np.full((buffer_size), V_avg), 'o-', linewidth=0.7, label='V value = {:< z.3f}'.format(V_avg))
axV.legend(loc='lower right')
color_theta = np.arctan2(V_avg, U_avg)
color_r = np.sqrt(U_avg**2 + V_avg**2)
ax1.axis([0, 2*np.pi, 0, 60])
ax1.set_title("UV Phasor plot")
ax1.scatter(color_theta, color_r)
ax1.vlines(color_theta, 0, color_r)
fig.set_size_inches(16, 9)
if (args.render_img is not None):
plt.savefig("docs/QAM phase {0:03}.{1}".format(sequence_counter, args.render_img), dpi=96)
else:
plt.show()
plt.close()
def composite_waveform_plot(voltage_buffer, emphasis, luma, hue, sequence_counter, args=None):
import matplotlib.pyplot as plt
fig = plt.figure(tight_layout=True)
fig.suptitle("${0:02X} emphasis {1:03b}".format((luma<<4 | hue), emphasis))
ax = fig.subplots()
x = np.arange(0,12)
y = voltage_buffer
ax.axis([0, 12, -50, 140])
ax.set_xlabel("Sample count")
ax.set_ylabel("IRE")
ax.plot(x, y, 'o-', linewidth=0.7)
fig.set_size_inches(16, 9)
if (args.render_img is not None):
plt.savefig("docs/waveform phase {0:03}.{1}".format(sequence_counter, args.render_img), dpi=120)
else:
plt.show()
plt.close()
def normalize_RGB(RGB_buffer, args=None):
def color_clip_darken(RGB_buffer):
for luma in range(RGB_buffer.shape[0]):
for chroma in range(RGB_buffer.shape[1]):
# if any of the RGB channels are greater than 1
if np.any(np.greater(RGB_buffer[luma, chroma], [1.0, 1.0, 1.0])):
# subtract all channels by delta of greatest channel
# algorithm by DragWx
darken_factor = np.max(RGB_buffer[luma, chroma])
RGB_buffer[luma, chroma] /= darken_factor
def color_clip_desaturate(RGB_buffer):
for luma in range(RGB_buffer.shape[0]):
for chroma in range(RGB_buffer.shape[1]):
# if any of the RGB channels are greater than 1
if np.any(np.greater(RGB_buffer[luma, chroma], [1.0, 1.0, 1.0])):
# desaturate that specific color until channels are within range
# algorithm by DragWx
darken_factor = np.max(RGB_buffer[luma, chroma])
YUV_calc = np.matmul(RGB_to_YUV, RGB_buffer[luma, chroma])
RGB_buffer[luma, chroma] -= YUV_calc[0]
RGB_buffer[luma, chroma] /= darken_factor
RGB_buffer[luma, chroma] += YUV_calc[0]
# clip takes priority over normalize
if (args.clip is not None):
match args.clip:
case "darken":
color_clip_darken(RGB_buffer)
case "desaturate":
color_clip_desaturate(RGB_buffer)
elif (args.normalize is not None):
if (args.normalize != "scale clip negative"):
RGB_buffer -= np.amin(RGB_buffer)
RGB_buffer /= np.amax(RGB_buffer)
# clip to 0.0-1.0 to ensure everything is within range
np.clip(RGB_buffer, 0, 1, out=RGB_buffer)
def pixel_codec_composite(YUV_buffer, args=None, signal_black_point=None, signal_white_point=None):
colorburst_phase = 0
next_line_shift = 0
# used for image sequence plotting
sequence_counter = 0
if (args.ppu == "2C07"):
# $x7 == -U - 45 degrees
# will flip to -U + 45 in pal_phase()
colorburst_phase = 7 + 0.5
next_line_shift = 2
else:
# $x8 = -U
colorburst_phase = 8
next_line_shift = 4
colorburst_factor = 6
color_gen_clock_factor = 2
buffer_size = int(colorburst_factor * color_gen_clock_factor)
colorburst_amplitude = 140 * (colorburst_table_composite[1] - colorburst_table_composite[0]) # in IRE
# SMPTE 170M-2004, page 5, section 8.2
# value of 40 IRE based on colorburst p-p amplitude defined in
# SMPTE 170M-2004, page 8, Table 1
colorburst_amp_reference = 40
colorburst_amp_correction = colorburst_amp_reference/colorburst_amplitude
if (args.burst_saturation_disable): colorburst_amp_correction = 1
# 2x due to integral of sin(2*PI*x)^2
saturation_correction = 2 * colorburst_amp_correction
# signal buffers for decoding
# 11111------1
# 2222------22
# 333------333
# 44------4444
# 5------55555
# ------666666
# -----777777-
# ----888888--
# ---999999---
# --AAAAAA----
# -BBBBBB-----
# CCCCCC------
voltage_buffer = np.empty((2, buffer_size), np.float64)
U_buffer = np.empty([buffer_size], np.float64)
V_buffer = np.empty([buffer_size], np.float64)
U_decode = np.empty([buffer_size], np.float64)
V_decode = np.empty([buffer_size], np.float64)
U_comb = np.empty([buffer_size], np.float64)
V_comb = np.empty([buffer_size], np.float64)
def encode_composite(emphasis, luma, hue, wave_phase, sinusoidal_peak_generation, alternate_line=False):
# 2C07 phase alternation
def pal_phase(hue):
if (hue >= 1 and hue <= 12) and (args.ppu == "2C07") and alternate_line:
return (-(hue - 5) % 12)
else: return hue
# waveform generation
def in_color_phase(hue, phase):
return ((pal_phase(hue) + phase) % 12) < 6
#rows $xE-$xF
luma_index = luma;
if (hue >= 0xE):
luma_index = 0x1
# 0 = waveform high; 1 = waveform low
n_wave_level = int(not in_color_phase(hue, wave_phase))
# 1 = emphasis activate
emphasis_level = int(
(((emphasis & 1) and in_color_phase(0xC, wave_phase)) or
((emphasis & 2) and in_color_phase(0x4, wave_phase)) or
((emphasis & 4) and in_color_phase(0x8, wave_phase))) and
(hue < 0xE)
)
# generate sinusoidal waveforms with matching p-p amplitudes
if (sinusoidal_peak_generation):
wave_amp = (signal_table_composite[luma_index, 0, emphasis_level] - signal_table_composite[luma_index, 1, emphasis_level]) / 2
# rows $x0 and $xD
luma_offset = (signal_table_composite[luma_index, 1, emphasis_level] + signal_table_composite[luma_index, 0, emphasis_level]) / 2
if (hue == 0x00):
wave_amp = 0
luma_offset = signal_table_composite[luma_index, 0, emphasis_level]
if (hue >= 0x0D):
wave_amp = 0
luma_offset = signal_table_composite[luma_index, 1, emphasis_level]
return luma_offset + (np.sin((2 * np.pi * (hue+0.5)/12) + (2 * np.pi / 12 * (wave_phase))) * wave_amp)
# rows $x0 and $xD
if (hue == 0x0): n_wave_level = 0
if (hue >= 0xD): n_wave_level = 1
return signal_table_composite[luma_index, n_wave_level, emphasis_level]
for emphasis in range(8):
for luma in range(4):
for hue in range(16):
# initialize buffers to prevent error propagation
voltage_buffer.fill(0)
U_buffer.fill(0)
V_buffer.fill(0)
U_decode.fill(0)
V_decode.fill(0)
U_comb.fill(0)
V_comb.fill(0)
# encode voltages into composite waveform
for wave_phase in range(buffer_size):
voltage_buffer[0, wave_phase] = encode_composite(emphasis, luma, hue, wave_phase, args.sinusoidal_peak_generation,)
# simulate next line by incrementing wave phase and alternating phase
if (args.delay_line_filter):
wave_phase_next = (wave_phase + next_line_shift) % 12
voltage_buffer[1, wave_phase_next] = encode_composite(emphasis, luma, hue, wave_phase_next, args.sinusoidal_peak_generation, alternate_line=True)
# apply analog effects
antiemphasis_column_chroma = (
args.antiemphasis_phase_skew if (
hue == 0x2 or
hue == 0x6 or
hue == 0xA)
else 0)
emphasis_row_luma = (
args.emphasis_luma_attenuation if (
hue == 0x4 or
hue == 0x8 or
hue == 0xC)
else 0)
phase_skew = args.phase_skew * luma
# decode voltage buffer to YUV
# based on SMPTE 170M-2004, page 17, section A.5, equation 10
# N = 0.925(Y) + 7.5 + 0.925*(U)*sin(2*π*f_sc*t) + 0.925*(V)*cos(2*π*f_sc*t)
# scaling factor 0.925 is already accounted for during normalization
# luma pedestal 7.5 is already accounted for during normalization
# shift blanking to 0
voltage_buffer -= composite_black
# convert to IRE
voltage_buffer *= 140
# apply gain
voltage_buffer += args.gain
# decode U and V
# reference is Video Demystified, 5th edition, p450, Figure 9.37
# bandpass UV component
voltage_bandpass = voltage_buffer.copy()
voltage_bandpass[0] -= np.average(voltage_bandpass[0])
voltage_bandpass[1] -= np.average(voltage_bandpass[1])
# comb filter
if (args.delay_line_filter):
U_comb = (voltage_bandpass[0] + voltage_bandpass[1]) / 2
V_comb = (voltage_bandpass[0] - voltage_bandpass[1]) / 2
else:
U_comb = voltage_bandpass[0].copy()
V_comb = voltage_bandpass[0].copy()
# apply hue and saturation in decode wave
t = np.arange(12)
# subcarrier generation is 180 degrees offset
# due to the way the waveform is encoded, the hue is off by an additional 1/2 of a sample
# if the subcarrier moves forward in angle, the resulting hue goes backwards
# hue argument is therefore inverse here
U_decode = np.sin(2 * np.pi / 12 * (t - 1 - colorburst_phase - 0.5) +
np.radians(antiemphasis_column_chroma - phase_skew - args.hue)
) * args.saturation * saturation_correction
V_decode = np.cos(2 * np.pi / 12 * (t - 1 - colorburst_phase - 0.5) +
np.radians(antiemphasis_column_chroma - phase_skew - args.hue)
) * args.saturation * saturation_correction
U_buffer = U_comb * U_decode
V_buffer = V_comb * V_decode
# lowpass UV buffers
YUV_buffer[emphasis, luma, hue, 1] = np.average(U_buffer)
YUV_buffer[emphasis, luma, hue, 2] = np.average(V_buffer)
# decode Y
# also apply brightness and contrast
if (args.delay_line_filter):
YUV_buffer[emphasis, luma, hue, 0] = (np.average(voltage_buffer[0] - voltage_bandpass[0]) + emphasis_row_luma) * args.contrast + args.brightness
else:
YUV_buffer[emphasis, luma, hue, 0] = (np.average(voltage_buffer[0]) + emphasis_row_luma) * args.contrast + args.brightness
# visualize chroma decoding
if (args.debug):
print("${0:02X} emphasis {1:03b}".format((luma<<4 | hue), emphasis) + "\n" + str(voltage_buffer[0]))
if (args.waveforms):
composite_waveform_plot(voltage_buffer[0], emphasis, luma, hue, sequence_counter, args)
if (args.phase_QAM):
composite_QAM_plot(voltage_buffer, U_comb, V_comb, U_decode, V_decode, U_buffer, V_buffer, buffer_size, emphasis, luma, hue, sequence_counter, args, signal_black_point, signal_white_point)
sequence_counter += 1
if not (args.emphasis):
# clip unused emphasis space
YUV_buffer = np.split(YUV_buffer, 8, 0)[0]
break
return YUV_buffer
def pixel_codec_rgb(YUV_buffer, args=None, signal_black_point=None, signal_white_point=None):
signal_table_rgb = np.empty([0x40], np.uint16)
match args.ppu:
case "2C04-0000"|"2C04-0001"|"2C04-0002"|"2C04-0003"|"2C04-0004":
# 2C04 "sorted" PPU palette LUT
# from https://www.nesdev.org/wiki/PPU_palettes#2C04
signal_table_rgb = np.array([
0x333,0x014,0x006,0x326,0x403,0x503,0x510,0x420,0x320,0x120,0x031,0x040,0x022,0x111,0x003,0x020,
0x555,0x036,0x027,0x407,0x507,0x704,0x700,0x630,0x430,0x140,0x040,0x053,0x044,0x222,0x200,0x310,
0x777,0x357,0x447,0x637,0x707,0x737,0x740,0x750,0x660,0x360,0x070,0x276,0x077,0x444,0x000,0x000,
0x777,0x567,0x657,0x757,0x747,0x755,0x764,0x770,0x773,0x572,0x473,0x276,0x467,0x666,0x653,0x760
], np.uint16)
case _:
# RGB PPU palettes LUT
# from https://forums.nesdev.org/viewtopic.php?p=98955#p98955
signal_table_rgb = np.array([
0x333,0x014,0x006,0x326,0x403,0x503,0x510,0x420,0x320,0x120,0x031,0x040,0x022,0x000,0x000,0x000,
0x555,0x036,0x027,0x407,0x507,0x704,0x700,0x630,0x430,0x140,0x040,0x053,0x044,0x000,0x000,0x000,
0x777,0x357,0x447,0x637,0x707,0x737,0x740,0x750,0x660,0x360,0x070,0x276,0x077,0x000,0x000,0x000,
0x777,0x567,0x657,0x757,0x747,0x755,0x764,0x772,0x773,0x572,0x473,0x276,0x467,0x000,0x000,0x000
], np.uint16)
RGB_to_YIQ = np.array([
RGB_to_YUV[0,:],
((RGB_to_YUV[1,:] * np.cos(IQ_tilt)) - (RGB_to_YUV[2,:]*np.sin(IQ_tilt))),
((RGB_to_YUV[1,:] * np.sin(IQ_tilt)) + (RGB_to_YUV[2,:]*np.cos(IQ_tilt)))
], np.float64)
def rgb_oct_triplet_to_float_array(signal_triplet, emphasis):
red = ((signal_triplet & 0xF00) >> 8) if not (emphasis & 0b001) else 7
green = ((signal_triplet & 0x0F0) >> 4) if not (emphasis & 0b010) else 7
blue = ((signal_triplet & 0x00F)) if not (emphasis & 0b100) else 7
return np.array([red, green, blue], np.float64)
# 2C04 LUTs
scramble = np.array(np.arange(0x00, 0x40), np.uint8)
match args.ppu:
case "2C04-0001":
scramble = np.array([
0x35,0x23,0x16,0x22,0x1C,0x09,0x1D,0x15,0x20,0x00,0x27,0x05,0x04,0x28,0x08,0x20,
0x21,0x3E,0x1F,0x29,0x3C,0x32,0x36,0x12,0x3F,0x2B,0x2E,0x1E,0x3D,0x2D,0x24,0x01,
0x0E,0x31,0x33,0x2A,0x2C,0x0C,0x1B,0x14,0x2E,0x07,0x34,0x06,0x13,0x02,0x26,0x2E,
0x2E,0x19,0x10,0x0A,0x39,0x03,0x37,0x17,0x0F,0x11,0x0B,0x0D,0x38,0x25,0x18,0x3A
], np.uint8)
case "2C04-0002":
scramble = np.array([
0x2E,0x27,0x18,0x39,0x3A,0x25,0x1C,0x31,0x16,0x13,0x38,0x34,0x20,0x23,0x3C,0x0B,
0x0F,0x21,0x06,0x3D,0x1B,0x29,0x1E,0x22,0x1D,0x24,0x0E,0x2B,0x32,0x08,0x2E,0x03,
0x04,0x36,0x26,0x33,0x11,0x1F,0x10,0x02,0x14,0x3F,0x00,0x09,0x12,0x2E,0x28,0x20,
0x3E,0x0D,0x2A,0x17,0x0C,0x01,0x15,0x19,0x2E,0x2C,0x07,0x37,0x35,0x05,0x0A,0x2D
], np.uint8)
case "2C04-0003":
scramble = np.array([
0x14,0x25,0x3A,0x10,0x0B,0x20,0x31,0x09,0x01,0x2E,0x36,0x08,0x15,0x3D,0x3E,0x3C,
0x22,0x1C,0x05,0x12,0x19,0x18,0x17,0x1B,0x00,0x03,0x2E,0x02,0x16,0x06,0x34,0x35,
0x23,0x0F,0x0E,0x37,0x0D,0x27,0x26,0x20,0x29,0x04,0x21,0x24,0x11,0x2D,0x2E,0x1F,
0x2C,0x1E,0x39,0x33,0x07,0x2A,0x28,0x1D,0x0A,0x2E,0x32,0x38,0x13,0x2B,0x3F,0x0C
], np.uint8)
case "2C04-0004":
scramble = np.array([
0x18,0x03,0x1C,0x28,0x2E,0x35,0x01,0x17,0x10,0x1F,0x2A,0x0E,0x36,0x37,0x0B,0x39,
0x25,0x1E,0x12,0x34,0x2E,0x1D,0x06,0x26,0x3E,0x1B,0x22,0x19,0x04,0x2E,0x3A,0x21,
0x05,0x0A,0x07,0x02,0x13,0x14,0x00,0x15,0x0C,0x3D,0x11,0x0F,0x0D,0x38,0x2D,0x24,
0x33,0x20,0x08,0x16,0x3F,0x2B,0x20,0x3C,0x2E,0x27,0x23,0x31,0x29,0x32,0x2C,0x09
], np.uint8)
for emphasis in range(8):
for luma in range(4):
for hue in range(16):
color_byte = (luma << 4) | hue
# decode palette LUT to RGB
YUV_buffer[emphasis, luma, hue] = rgb_oct_triplet_to_float_array(
signal_table_rgb[scramble[color_byte]],
emphasis
) / 7
# convert to IRE scale so that i don't have to complicate black/white points
YUV_buffer[emphasis, luma, hue] *= 100
# apply gain
YUV_buffer[emphasis, luma, hue] += args.gain
# encode RGB to YIQ for hue and saturation adjustment
YUV_buffer[emphasis, luma, hue] = np.matmul(RGB_to_YIQ, YUV_buffer[emphasis, luma, hue])
# Titler functionality
if (args.ppu == "2C05-99"):
# reduce Q component by half
YUV_buffer[emphasis, luma, hue, 2] *= 0.5
# apply brightness and contrast
YUV_buffer[emphasis, luma, hue, 0] += args.brightness
YUV_buffer[emphasis, luma, hue, 0] *= args.contrast
# apply hue
YUV_buffer[emphasis, luma, hue, 1] = (
(YUV_buffer[emphasis, luma, hue, 1] * np.cos(np.radians(args.hue))) -
(YUV_buffer[emphasis, luma, hue, 2] * np.sin(np.radians(args.hue)))
)
YUV_buffer[emphasis, luma, hue, 2] = (
(YUV_buffer[emphasis, luma, hue, 1] * np.sin(np.radians(args.hue))) +
(YUV_buffer[emphasis, luma, hue, 2] * np.cos(np.radians(args.hue)))
)
# apply saturation
YUV_buffer[emphasis, luma, hue, 1] *= args.saturation
YUV_buffer[emphasis, luma, hue, 2] *= args.saturation
# convert to YUV for later decoding
YUV_buffer[emphasis, luma, hue] = np.matmul(YUV_YIQ, YUV_buffer[emphasis, luma, hue])
if not (args.emphasis):