forked from ramapcsx2/gbs-control
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gbs-control.ino
10813 lines (9843 loc) · 418 KB
/
gbs-control.ino
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
#include "ntsc_240p.h"
#include "pal_240p.h"
#include "ntsc_720x480.h"
#include "pal_768x576.h"
#include "ntsc_1280x720.h"
#include "ntsc_1280x1024.h"
#include "ntsc_1920x1080.h"
#include "ntsc_downscale.h"
#include "pal_1280x720.h"
#include "pal_1280x1024.h"
#include "pal_1920x1080.h"
#include "pal_downscale.h"
#include "presetMdSection.h"
#include "presetDeinterlacerSection.h"
#include "presetHdBypassSection.h"
#include "ofw_RGBS.h"
#include "options.h"
#include "slot.h"
#include <Wire.h>
#include "tv5725.h"
#include "osd.h"
#include "SSD1306Wire.h"
#include "images.h"
#define HAVE_BUTTONS 0
#define USE_NEW_OLED_MENU 1
static inline void writeBytes(uint8_t slaveRegister, uint8_t *values, uint8_t numValues);
const uint8_t *loadPresetFromSPIFFS(byte forVideoMode);
SSD1306Wire display(0x3c, D2, D1); //inits I2C address & pins for OLED
const int pin_clk = 14; //D5 = GPIO14 (input of one direction for encoder)
const int pin_data = 13; //D7 = GPIO13 (input of one direction for encoder)
const int pin_switch = 0; //D3 = GPIO0 pulled HIGH, else boot fail (middle push button for encoder)
#if USE_NEW_OLED_MENU
#include "OLEDMenuImplementation.h"
#include "OSDManager.h"
OLEDMenuManager oledMenu(&display);
OSDManager osdManager;
volatile OLEDMenuNav oledNav = OLEDMenuNav::IDLE;
volatile uint8_t rotaryIsrID = 0;
#else
String oled_menu[4] = {"Resolutions", "Presets", "Misc.", "Current Settings"};
String oled_Resolutions[7] = {"1280x960", "1280x1024", "1280x720", "1920x1080", "480/576", "Downscale", "Pass-Through"};
String oled_Presets[8] = {"1", "2", "3", "4", "5", "6", "7", "Back"};
String oled_Misc[4] = {"Reset GBS", "Restore Factory", "-----Back"};
int oled_menuItem = 1;
int oled_subsetFrame = 0;
int oled_selectOption = 0;
int oled_page = 0;
int oled_lastCount = 0;
volatile int oled_encoder_pos = 0;
volatile int oled_main_pointer = 0; // volatile vars change done with ISR
volatile int oled_pointer_count = 0;
volatile int oled_sub_pointer = 0;
#endif
#include <ESP8266WiFi.h>
// ESPAsyncTCP and ESPAsyncWebServer libraries by me-no-dev
// download (green "Clone or download" button) and extract to Arduino libraries folder
// Windows: "Documents\Arduino\libraries" or full path: "C:\Users\rama\Documents\Arduino\libraries"
// https://github.com/me-no-dev/ESPAsyncTCP
// https://github.com/me-no-dev/ESPAsyncWebServer
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "FS.h"
#include <DNSServer.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h> // mDNS library for finding gbscontrol.local on the local network
#include <ArduinoOTA.h>
// PersWiFiManager library by Ryan Downing
// https://github.com/r-downing/PersWiFiManager
// included in project root folder to allow modifications within limitations of the Arduino framework
// See 3rdparty/PersWiFiManager for unmodified source and license
#include "PersWiFiManager.h"
// WebSockets library by Markus Sattler
// https://github.com/Links2004/arduinoWebSockets
// included in src folder to allow header modifications within limitations of the Arduino framework
// See 3rdparty/WebSockets for unmodified source and license
#include "src/WebSockets.h"
#include "src/WebSocketsServer.h"
// Optional:
// ESP8266-ping library to aid debugging WiFi issues, install via Arduino library manager
//#define HAVE_PINGER_LIBRARY
#ifdef HAVE_PINGER_LIBRARY
#include <Pinger.h>
#include <PingerResponse.h>
unsigned long pingLastTime;
Pinger pinger; // pinger global object to aid debugging WiFi issues
#endif
typedef TV5725<GBS_ADDR> GBS;
static unsigned long lastVsyncLock = millis();
// Si5351mcu library by Pavel Milanes
// https://github.com/pavelmc/Si5351mcu
// included in project root folder to allow modifications within limitations of the Arduino framework
// See 3rdparty/Si5351mcu for unmodified source and license
#include "src/si5351mcu.h"
Si5351mcu Si;
#define THIS_DEVICE_MASTER
#ifdef THIS_DEVICE_MASTER
const char *ap_ssid = "gbscontrol";
const char *ap_password = "qqqqqqqq";
// change device_hostname_full and device_hostname_partial to rename the device
// (allows 2 or more on the same network)
// new: only use _partial throughout, comply to standards
const char *device_hostname_full = "gbscontrol.local";
const char *device_hostname_partial = "gbscontrol"; // for MDNS
//
static const char ap_info_string[] PROGMEM =
"(WiFi): AP mode (SSID: gbscontrol, pass 'qqqqqqqq'): Access 'gbscontrol.local' in your browser";
static const char st_info_string[] PROGMEM =
"(WiFi): Access 'http://gbscontrol:80' or 'http://gbscontrol.local' (or device IP) in your browser";
#else
const char *ap_ssid = "gbsslave";
const char *ap_password = "qqqqqqqq";
const char *device_hostname_full = "gbsslave.local";
const char *device_hostname_partial = "gbsslave"; // for MDNS
//
static const char ap_info_string[] PROGMEM =
"(WiFi): AP mode (SSID: gbsslave, pass 'qqqqqqqq'): Access 'gbsslave.local' in your browser";
static const char st_info_string[] PROGMEM =
"(WiFi): Access 'http://gbsslave:80' or 'http://gbsslave.local' (or device IP) in your browser";
#endif
AsyncWebServer server(80);
DNSServer dnsServer;
WebSocketsServer webSocket(81);
//AsyncWebSocket webSocket("/ws");
PersWiFiManager persWM(server, dnsServer);
#define DEBUG_IN_PIN D6 // marked "D12/MISO/D6" (Wemos D1) or D6 (Lolin NodeMCU)
// SCL = D1 (Lolin), D15 (Wemos D1) // ESP8266 Arduino default map: SCL
// SDA = D2 (Lolin), D14 (Wemos D1) // ESP8266 Arduino default map: SDA
#define LEDON \
pinMode(LED_BUILTIN, OUTPUT); \
digitalWrite(LED_BUILTIN, LOW)
#define LEDOFF \
digitalWrite(LED_BUILTIN, HIGH); \
pinMode(LED_BUILTIN, INPUT)
// fast ESP8266 digitalRead (21 cycles vs 77), *should* work with all possible input pins
// but only "D7" and "D6" have been tested so far
#define digitalRead(x) ((GPIO_REG_READ(GPIO_IN_ADDRESS) >> x) & 1)
// feed the current measurement, get back the moving average
uint8_t getMovingAverage(uint8_t item)
{
static const uint8_t sz = 16;
static uint8_t arr[sz] = {0};
static uint8_t pos = 0;
arr[pos] = item;
if (pos < (sz - 1)) {
pos++;
} else {
pos = 0;
}
uint16_t sum = 0;
for (uint8_t i = 0; i < sz; i++) {
sum += arr[i];
}
return sum >> 4; // for array size 16
}
struct MenuAttrs
{
static const int8_t shiftDelta = 4;
static const int8_t scaleDelta = 4;
static const int16_t vertShiftRange = 300;
static const int16_t horizShiftRange = 400;
static const int16_t vertScaleRange = 100;
static const int16_t horizScaleRange = 130;
static const int16_t barLength = 100;
};
typedef MenuManager<GBS, MenuAttrs> Menu;
/// Video processing mode, loaded into register GBS_PRESET_ID by applyPresets()
/// and read to rto->presetID by doPostPresetLoadSteps(). Shown on web UI.
enum PresetID : uint8_t {
PresetHdBypass = 0x21,
PresetBypassRGBHV = 0x22,
};
struct runTimeOptions rtos;
struct runTimeOptions *rto = &rtos;
struct userOptions uopts;
struct userOptions *uopt = &uopts;
struct adcOptions adcopts;
struct adcOptions *adco = &adcopts;
String slotIndexMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~()!*:,";
char serialCommand; // Serial / Web Server commands
char userCommand; // Serial / Web Server commands
static uint8_t lastSegment = 0xFF; // GBS segment for direct access
//uint8_t globalDelay; // used for dev / debug
#if defined(ESP8266)
// serial mirror class for websocket logs
class SerialMirror : public Stream
{
size_t write(const uint8_t *data, size_t size)
{
if (ESP.getFreeHeap() > 20000) {
webSocket.broadcastTXT(data, size);
} else {
webSocket.disconnect();
}
Serial.write(data, size);
return size;
}
size_t write(const char *data, size_t size)
{
if (ESP.getFreeHeap() > 20000) {
webSocket.broadcastTXT(data, size);
} else {
webSocket.disconnect();
}
Serial.write(data, size);
return size;
}
size_t write(uint8_t data)
{
if (ESP.getFreeHeap() > 20000) {
webSocket.broadcastTXT(&data, 1);
} else {
webSocket.disconnect();
}
Serial.write(data);
return 1;
}
size_t write(char data)
{
if (ESP.getFreeHeap() > 20000) {
webSocket.broadcastTXT(&data, 1);
} else {
webSocket.disconnect();
}
Serial.write(data);
return 1;
}
int available()
{
return 0;
}
int read()
{
return -1;
}
int peek()
{
return -1;
}
void flush() {}
};
SerialMirror SerialM;
#else
#define SerialM Serial
#endif
#include "framesync.h"
//
// Sync locking tunables/magic numbers
//
struct FrameSyncAttrs
{
static const uint8_t debugInPin = DEBUG_IN_PIN;
static const uint32_t lockInterval = 100 * 16.70; // every 100 frames
static const int16_t syncCorrection = 2; // Sync correction in scanlines to apply when phase lags target
static const int32_t syncTargetPhase = 90; // Target vsync phase offset (output trails input) in degrees
// to debug: syncTargetPhase = 343 lockInterval = 15 * 16
};
typedef FrameSyncManager<GBS, FrameSyncAttrs> FrameSync;
void externalClockGenResetClock()
{
if (!rto->extClockGenDetected) {
return;
}
fsDebugPrintf("externalClockGenResetClock()\n");
uint8_t activeDisplayClock = GBS::PLL648_CONTROL_01::read();
if (activeDisplayClock == 0x25)
rto->freqExtClockGen = 40500000;
else if (activeDisplayClock == 0x45)
rto->freqExtClockGen = 54000000;
else if (activeDisplayClock == 0x55)
rto->freqExtClockGen = 64800000;
else if (activeDisplayClock == 0x65)
rto->freqExtClockGen = 81000000;
else if (activeDisplayClock == 0x85)
rto->freqExtClockGen = 108000000;
else if (activeDisplayClock == 0x95)
rto->freqExtClockGen = 129600000;
else if (activeDisplayClock == 0xa5)
rto->freqExtClockGen = 162000000;
else if (activeDisplayClock == 0x35)
rto->freqExtClockGen = 81000000; // clock unused
else if (activeDisplayClock == 0)
rto->freqExtClockGen = 81000000; // no preset loaded
else if (!rto->outModeHdBypass) {
SerialM.print(F("preset display clock: 0x"));
SerialM.println(activeDisplayClock, HEX);
}
// problem: around 108MHz the library seems to double the clock
// maybe there are regs to check for this and resetPLL
if (rto->freqExtClockGen == 108000000) {
Si.setFreq(0, 87000000);
delay(1); // quick fix
}
// same thing it seems at 40500000
if (rto->freqExtClockGen == 40500000) {
Si.setFreq(0, 48500000);
delay(1); // quick fix
}
Si.setFreq(0, rto->freqExtClockGen);
GBS::PAD_CKIN_ENZ::write(0); // 0 = clock input enable (pin40)
FrameSync::clearFrequency();
SerialM.print(F("clock gen reset: "));
SerialM.println(rto->freqExtClockGen);
}
void externalClockGenSyncInOutRate()
{
fsDebugPrintf("externalClockGenSyncInOutRate()\n");
if (!rto->extClockGenDetected) {
return;
}
if (GBS::PAD_CKIN_ENZ::read() != 0) {
return;
}
if (rto->outModeHdBypass) {
return;
}
if (GBS::PLL648_CONTROL_01::read() != 0x75) {
return;
}
float sfr = getSourceFieldRate(0);
if (sfr < 47.0f || sfr > 86.0f) {
SerialM.print(F("sync skipped sfr wrong: "));
SerialM.println(sfr);
return;
}
float ofr = getOutputFrameRate();
if (ofr < 47.0f || ofr > 86.0f) {
SerialM.print(F("sync skipped ofr wrong: "));
SerialM.println(ofr);
return;
}
uint32_t old = rto->freqExtClockGen;
FrameSync::initFrequency(ofr, old);
setExternalClockGenFrequencySmooth((sfr / ofr) * rto->freqExtClockGen);
int32_t diff = rto->freqExtClockGen - old;
SerialM.print(F("source Hz: "));
SerialM.print(sfr, 5);
SerialM.print(F(" new out: "));
SerialM.print(getOutputFrameRate(), 5);
SerialM.print(F(" clock: "));
SerialM.print(rto->freqExtClockGen);
SerialM.print(F(" ("));
SerialM.print(diff >= 0 ? "+" : "");
SerialM.print(diff);
SerialM.println(F(")"));
delay(1);
}
void externalClockGenDetectAndInitialize()
{
const uint8_t xtal_cl = 0xD2; // 10pF, other choices are 8pF (0x92) and 6pF (0x52) NOTE: Per AN619, the low bytes should be written 0b010010
// MHz: 27, 32.4, 40.5, 54, 64.8, 81, 108, 129.6, 162
rto->freqExtClockGen = 81000000;
rto->extClockGenDetected = 0;
if (uopt->disableExternalClockGenerator) {
SerialM.println(F("ExternalClockGenerator disabled, skipping detection"));
return;
}
uint8_t retVal = 0;
Wire.beginTransmission(SIADDR);
retVal = Wire.endTransmission();
if (retVal != 0) {
return;
}
Wire.beginTransmission(SIADDR);
Wire.write(0); // Device Status
Wire.endTransmission();
size_t bytes_read = Wire.requestFrom((uint8_t)SIADDR, (size_t)1, false);
if (bytes_read == 1) {
retVal = Wire.read();
if ((retVal & 0x80) == 0) {
// SYS_INIT indicates device is ready.
rto->extClockGenDetected = 1;
} else {
return;
}
} else {
return;
}
Si.init(25000000L); // many Si5351 boards come with 25MHz crystal; 27000000L for one with 27MHz
Wire.beginTransmission(SIADDR);
Wire.write(183); // XTAL_CL
Wire.write(xtal_cl);
Wire.endTransmission();
Si.setPower(0, SIOUT_6mA);
Si.setFreq(0, rto->freqExtClockGen);
Si.disable(0);
}
static inline void writeOneByte(uint8_t slaveRegister, uint8_t value)
{
writeBytes(slaveRegister, &value, 1);
}
static inline void writeBytes(uint8_t slaveRegister, uint8_t *values, uint8_t numValues)
{
if (slaveRegister == 0xF0 && numValues == 1) {
lastSegment = *values;
} else
GBS::write(lastSegment, slaveRegister, values, numValues);
}
void copyBank(uint8_t *bank, const uint8_t *programArray, uint16_t *index)
{
for (uint8_t x = 0; x < 16; ++x) {
bank[x] = pgm_read_byte(programArray + *index);
(*index)++;
}
}
boolean videoStandardInputIsPalNtscSd()
{
if (rto->videoStandardInput == 1 || rto->videoStandardInput == 2) {
return true;
}
return false;
}
void zeroAll()
{
// turn processing units off first
writeOneByte(0xF0, 0);
writeOneByte(0x46, 0x00); // reset controls 1
writeOneByte(0x47, 0x00); // reset controls 2
// zero out entire register space
for (int y = 0; y < 6; y++) {
writeOneByte(0xF0, (uint8_t)y);
for (int z = 0; z < 16; z++) {
uint8_t bank[16];
for (int w = 0; w < 16; w++) {
bank[w] = 0;
// exceptions
//if (y == 5 && z == 0 && w == 2) {
// bank[w] = 0x51; // 5_02
//}
//if (y == 5 && z == 5 && w == 6) {
// bank[w] = 0x01; // 5_56
//}
//if (y == 5 && z == 5 && w == 7) {
// bank[w] = 0xC0; // 5_57
//}
}
writeBytes(z * 16, bank, 16);
}
}
}
void loadHdBypassSection()
{
uint16_t index = 0;
uint8_t bank[16];
writeOneByte(0xF0, 1);
for (int j = 3; j <= 5; j++) { // start at 0x30
copyBank(bank, presetHdBypassSection, &index);
writeBytes(j * 16, bank, 16);
}
}
void loadPresetDeinterlacerSection()
{
uint16_t index = 0;
uint8_t bank[16];
writeOneByte(0xF0, 2);
for (int j = 0; j <= 3; j++) { // start at 0x00
copyBank(bank, presetDeinterlacerSection, &index);
writeBytes(j * 16, bank, 16);
}
}
void loadPresetMdSection()
{
uint16_t index = 0;
uint8_t bank[16];
writeOneByte(0xF0, 1);
for (int j = 6; j <= 7; j++) { // start at 0x60
copyBank(bank, presetMdSection, &index);
writeBytes(j * 16, bank, 16);
}
bank[0] = pgm_read_byte(presetMdSection + index);
bank[1] = pgm_read_byte(presetMdSection + index + 1);
bank[2] = pgm_read_byte(presetMdSection + index + 2);
bank[3] = pgm_read_byte(presetMdSection + index + 3);
writeBytes(8 * 16, bank, 4); // MD section ends at 0x83, not 0x90
}
// programs all valid registers (the register map has holes in it, so it's not straight forward)
// 'index' keeps track of the current preset data location.
void writeProgramArrayNew(const uint8_t *programArray, boolean skipMDSection)
{
uint16_t index = 0;
uint8_t bank[16];
uint8_t y = 0;
//GBS::PAD_SYNC_OUT_ENZ::write(1);
//GBS::DAC_RGBS_PWDNZ::write(0); // no DAC
//GBS::SFTRST_MEM_FF_RSTZ::write(0); // stop mem fifos
FrameSync::cleanup();
// should only be possible if previously was in RGBHV bypass, then hit a manual preset switch
if (rto->videoStandardInput == 15) {
rto->videoStandardInput = 0;
}
rto->outModeHdBypass = 0; // the default at this stage
if (GBS::ADC_INPUT_SEL::read() == 0) {
//if (rto->inputIsYpBpR == 0) SerialM.println("rto->inputIsYpBpR was 0, fixing to 1");
rto->inputIsYpBpR = 1; // new: update the var here, allow manual preset loads
} else {
//if (rto->inputIsYpBpR == 1) SerialM.println("rto->inputIsYpBpR was 1, fixing to 0");
rto->inputIsYpBpR = 0;
}
uint8_t reset46 = GBS::RESET_CONTROL_0x46::read(); // for keeping these as they are now
uint8_t reset47 = GBS::RESET_CONTROL_0x47::read();
for (; y < 6; y++) {
writeOneByte(0xF0, (uint8_t)y);
switch (y) {
case 0:
for (int j = 0; j <= 1; j++) { // 2 times
for (int x = 0; x <= 15; x++) {
if (j == 0 && x == 4) {
// keep DAC off
if (rto->useHdmiSyncFix) {
bank[x] = pgm_read_byte(programArray + index) & ~(1 << 0);
} else {
bank[x] = pgm_read_byte(programArray + index);
}
} else if (j == 0 && x == 6) {
bank[x] = reset46;
} else if (j == 0 && x == 7) {
bank[x] = reset47;
} else if (j == 0 && x == 9) {
// keep sync output off
if (rto->useHdmiSyncFix) {
bank[x] = pgm_read_byte(programArray + index) | (1 << 2);
} else {
bank[x] = pgm_read_byte(programArray + index);
}
} else {
// use preset values
bank[x] = pgm_read_byte(programArray + index);
}
index++;
}
writeBytes(0x40 + (j * 16), bank, 16);
}
copyBank(bank, programArray, &index);
writeBytes(0x90, bank, 16);
break;
case 1:
for (int j = 0; j <= 2; j++) { // 3 times
copyBank(bank, programArray, &index);
if (j == 0) {
bank[0] = bank[0] & ~(1 << 5); // clear 1_00 5
bank[1] = bank[1] | (1 << 0); // set 1_01 0
bank[12] = bank[12] & 0x0f; // clear 1_0c upper bits
bank[13] = 0; // clear 1_0d
}
writeBytes(j * 16, bank, 16);
}
if (!skipMDSection) {
loadPresetMdSection();
if (rto->syncTypeCsync)
GBS::MD_SEL_VGA60::write(0); // EDTV possible
else
GBS::MD_SEL_VGA60::write(1); // VGA 640x480 more likely
GBS::MD_HD1250P_CNTRL::write(rto->medResLineCount); // patch med res support
}
break;
case 2:
loadPresetDeinterlacerSection();
break;
case 3:
for (int j = 0; j <= 7; j++) { // 8 times
copyBank(bank, programArray, &index);
//if (rto->useHdmiSyncFix) {
// if (j == 0) {
// bank[0] = bank[0] | (1 << 0); // 3_00 0 sync lock
// }
// if (j == 1) {
// bank[10] = bank[10] | (1 << 4); // 3_1a 4 frame lock
// }
//}
writeBytes(j * 16, bank, 16);
}
// blank out VDS PIP registers, otherwise they can end up uninitialized
for (int x = 0; x <= 15; x++) {
writeOneByte(0x80 + x, 0x00);
}
break;
case 4:
for (int j = 0; j <= 5; j++) { // 6 times
copyBank(bank, programArray, &index);
writeBytes(j * 16, bank, 16);
}
break;
case 5:
for (int j = 0; j <= 6; j++) { // 7 times
for (int x = 0; x <= 15; x++) {
bank[x] = pgm_read_byte(programArray + index);
if (index == 322) { // s5_02 bit 6+7 = input selector (only bit 6 is relevant)
if (rto->inputIsYpBpR)
bitClear(bank[x], 6);
else
bitSet(bank[x], 6);
}
if (index == 323) { // s5_03 set clamps according to input channel
if (rto->inputIsYpBpR) {
bitClear(bank[x], 2); // G bottom clamp
bitSet(bank[x], 1); // R mid clamp
bitSet(bank[x], 3); // B mid clamp
} else {
bitClear(bank[x], 2); // G bottom clamp
bitClear(bank[x], 1); // R bottom clamp
bitClear(bank[x], 3); // B bottom clamp
}
}
//if (index == 324) { // s5_04 reset(0) for ADC REF init
// bank[x] = 0x00;
//}
if (index == 352) { // s5_20 always force to 0x02 (only SP_SOG_P_ATO)
bank[x] = 0x02;
}
if (index == 375) { // s5_37
if (videoStandardInputIsPalNtscSd()) {
bank[x] = 0x6b;
} else {
bank[x] = 0x02;
}
}
if (index == 382) { // s5_3e
bitSet(bank[x], 5); // SP_DIS_SUB_COAST = 1
}
if (index == 407) { // s5_57
bitSet(bank[x], 0); // SP_NO_CLAMP_REG = 1
}
index++;
}
writeBytes(j * 16, bank, 16);
}
break;
}
}
// scaling RGBHV mode
if (uopt->preferScalingRgbhv && rto->isValidForScalingRGBHV) {
GBS::GBS_OPTION_SCALING_RGBHV::write(1);
rto->videoStandardInput = 3;
}
}
void activeFrameTimeLockInitialSteps()
{
// skip if using external clock gen
if (rto->extClockGenDetected) {
SerialM.println(F("Active FrameTime Lock enabled, adjusting external clock gen frequency"));
return;
}
// skip when out mode = bypass
if (rto->presetID != PresetHdBypass && rto->presetID != PresetBypassRGBHV) {
SerialM.print(F("Active FrameTime Lock enabled, disable if display unstable or stays blank! Method: "));
if (uopt->frameTimeLockMethod == 0) {
SerialM.println(F("0 (vtotal + VSST)"));
}
if (uopt->frameTimeLockMethod == 1) {
SerialM.println(F("1 (vtotal only)"));
}
if (GBS::VDS_VS_ST::read() == 0) {
// VS_ST needs to be at least 1, so method 1 can decrease it when needed (but currently only increases VS_ST)
// don't force this here, instead make sure to have all presets follow the rule (easier dev)
SerialM.println(F("Warning: Check VDS_VS_ST!"));
}
}
}
void resetInterruptSogSwitchBit()
{
GBS::INT_CONTROL_RST_SOGSWITCH::write(1);
GBS::INT_CONTROL_RST_SOGSWITCH::write(0);
}
void resetInterruptSogBadBit()
{
GBS::INT_CONTROL_RST_SOGBAD::write(1);
GBS::INT_CONTROL_RST_SOGBAD::write(0);
}
void resetInterruptNoHsyncBadBit()
{
GBS::INT_CONTROL_RST_NOHSYNC::write(1);
GBS::INT_CONTROL_RST_NOHSYNC::write(0);
}
void setResetParameters()
{
SerialM.println("<reset>");
rto->videoStandardInput = 0;
rto->videoIsFrozen = false;
rto->applyPresetDoneStage = 0;
rto->presetVlineShift = 0;
rto->sourceDisconnected = true;
rto->outModeHdBypass = 0;
rto->clampPositionIsSet = 0;
rto->coastPositionIsSet = 0;
rto->phaseIsSet = 0;
rto->continousStableCounter = 0;
rto->noSyncCounter = 0;
rto->isInLowPowerMode = false;
rto->currentLevelSOG = 5;
rto->thisSourceMaxLevelSOG = 31; // 31 = auto sog has not (yet) run
rto->failRetryAttempts = 0;
rto->HPLLState = 0;
rto->motionAdaptiveDeinterlaceActive = false;
rto->scanlinesEnabled = false;
rto->syncTypeCsync = false;
rto->isValidForScalingRGBHV = false;
rto->medResLineCount = 0x33; // 51*8=408
rto->osr = 0;
rto->useHdmiSyncFix = 0;
rto->notRecognizedCounter = 0;
adco->r_gain = 0;
adco->g_gain = 0;
adco->b_gain = 0;
// clear temp storage
GBS::ADC_UNUSED_64::write(0);
GBS::ADC_UNUSED_65::write(0);
GBS::ADC_UNUSED_66::write(0);
GBS::ADC_UNUSED_67::write(0);
GBS::GBS_PRESET_CUSTOM::write(0);
GBS::GBS_PRESET_ID::write(0);
GBS::GBS_OPTION_SCALING_RGBHV::write(0);
GBS::GBS_OPTION_PALFORCED60_ENABLED::write(0);
// set minimum IF parameters
GBS::IF_VS_SEL::write(1);
GBS::IF_VS_FLIP::write(1);
GBS::IF_HSYNC_RST::write(0x3FF);
GBS::IF_VB_ST::write(0);
GBS::IF_VB_SP::write(2);
// could stop ext clock gen output here?
FrameSync::cleanup();
GBS::OUT_SYNC_CNTRL::write(0); // no H / V sync out to PAD
GBS::DAC_RGBS_PWDNZ::write(0); // disable DAC
GBS::ADC_TA_05_CTRL::write(0x02); // 5_05 1 // minor SOG clamp effect
GBS::ADC_TEST_04::write(0x02); // 5_04
GBS::ADC_TEST_0C::write(0x12); // 5_0c 1 4
GBS::ADC_CLK_PA::write(0); // 5_00 0/1 PA_ADC input clock = PLLAD CLKO2
GBS::ADC_SOGEN::write(1);
GBS::SP_SOG_MODE::write(1);
GBS::ADC_INPUT_SEL::write(1); // 1 = RGBS / RGBHV adc data input
GBS::ADC_POWDZ::write(1); // ADC on
setAndUpdateSogLevel(rto->currentLevelSOG);
GBS::RESET_CONTROL_0x46::write(0x00); // all units off
GBS::RESET_CONTROL_0x47::write(0x00);
GBS::GPIO_CONTROL_00::write(0x67); // most GPIO pins regular GPIO
GBS::GPIO_CONTROL_01::write(0x00); // all GPIO outputs disabled
GBS::DAC_RGBS_PWDNZ::write(0); // disable DAC (output)
GBS::PLL648_CONTROL_01::write(0x00); // VCLK(1/2/4) display clock // needs valid for debug bus
GBS::PAD_CKIN_ENZ::write(0); // 0 = clock input enable (pin40)
GBS::PAD_CKOUT_ENZ::write(1); // clock output disable
GBS::IF_SEL_ADC_SYNC::write(1); // ! 1_28 2
GBS::PLLAD_VCORST::write(1); // reset = 1
GBS::PLL_ADS::write(1); // When = 1, input clock is from ADC ( otherwise, from unconnected clock at pin 40 )
GBS::PLL_CKIS::write(0); // PLL use OSC clock
GBS::PLL_MS::write(2); // fb memory clock can go lower power
GBS::PAD_CONTROL_00_0x48::write(0x2b); //disable digital inputs, enable debug out pin
GBS::PAD_CONTROL_01_0x49::write(0x1f); //pad control pull down/up transistors on
loadHdBypassSection(); // 1_30 to 1_55
loadPresetMdSection(); // 1_60 to 1_83
setAdcParametersGainAndOffset();
GBS::SP_PRE_COAST::write(9); // was 0x07 // need pre / poast to allow all sources to detect
GBS::SP_POST_COAST::write(18); // was 0x10 // ps2 1080p 18
GBS::SP_NO_COAST_REG::write(0); // can be 1 in some soft reset situations, will prevent sog vsync decoding << really?
GBS::SP_CS_CLP_ST::write(32); // define it to something at start
GBS::SP_CS_CLP_SP::write(48);
GBS::SP_SOG_SRC_SEL::write(0); // SOG source = ADC
GBS::SP_EXT_SYNC_SEL::write(0); // connect HV input ( 5_20 bit 3 )
GBS::SP_NO_CLAMP_REG::write(1);
GBS::PLLAD_ICP::write(0); // lowest charge pump current
GBS::PLLAD_FS::write(0); // low gain (have to deal with cold and warm startups)
GBS::PLLAD_5_16::write(0x1f);
GBS::PLLAD_MD::write(0x700);
resetPLL(); // cycles PLL648
delay(2);
resetPLLAD(); // same for PLLAD
GBS::PLL_VCORST::write(1); // reset on
GBS::PLLAD_CONTROL_00_5x11::write(0x01); // reset on
resetDebugPort();
//GBS::RESET_CONTROL_0x47::write(0x16);
GBS::RESET_CONTROL_0x46::write(0x41); // new 23.07.19
GBS::RESET_CONTROL_0x47::write(0x17); // new 23.07.19 (was 0x16)
GBS::INTERRUPT_CONTROL_01::write(0xff); // enable interrupts
GBS::INTERRUPT_CONTROL_00::write(0xff); // reset irq status
GBS::INTERRUPT_CONTROL_00::write(0x00);
GBS::PAD_SYNC_OUT_ENZ::write(0); // sync output enabled, will be low (HC125 fix)
rto->clampPositionIsSet = 0; // some functions override these, so make sure
rto->coastPositionIsSet = 0;
rto->phaseIsSet = 0;
rto->continousStableCounter = 0;
serialCommand = '@';
userCommand = '@';
}
void OutputComponentOrVGA()
{
// TODO replace with rto->isCustomPreset?
boolean isCustomPreset = GBS::GBS_PRESET_CUSTOM::read();
if (uopt->wantOutputComponent) {
SerialM.println(F("Output Format: Component"));
GBS::VDS_SYNC_LEV::write(0x80); // 0.25Vpp sync (leave more room for Y)
GBS::VDS_CONVT_BYPS::write(1); // output YUV
GBS::OUT_SYNC_CNTRL::write(0); // no H / V sync out to PAD
} else {
GBS::VDS_SYNC_LEV::write(0);
GBS::VDS_CONVT_BYPS::write(0); // output RGB
GBS::OUT_SYNC_CNTRL::write(1); // H / V sync out enable
}
if (!isCustomPreset) {
if (rto->inputIsYpBpR == true) {
applyYuvPatches();
} else {
applyRGBPatches();
}
}
}
void applyComponentColorMixing()
{
GBS::VDS_Y_GAIN::write(0x64); // 3_35
GBS::VDS_UCOS_GAIN::write(0x19); // 3_36
GBS::VDS_VCOS_GAIN::write(0x19); // 3_37
GBS::VDS_Y_OFST::write(0xfe); // 3_3a
GBS::VDS_U_OFST::write(0x01); // 3_3b
}
void toggleIfAutoOffset()
{
if (GBS::IF_AUTO_OFST_EN::read() == 0) {
// and different ADC offsets
GBS::ADC_ROFCTRL::write(0x40);
GBS::ADC_GOFCTRL::write(0x42);
GBS::ADC_BOFCTRL::write(0x40);
// enable
GBS::IF_AUTO_OFST_EN::write(1);
GBS::IF_AUTO_OFST_PRD::write(0); // 0 = by line, 1 = by frame
} else {
if (adco->r_off != 0 && adco->g_off != 0 && adco->b_off != 0) {
GBS::ADC_ROFCTRL::write(adco->r_off);
GBS::ADC_GOFCTRL::write(adco->g_off);
GBS::ADC_BOFCTRL::write(adco->b_off);
}
// adco->r_off = 0: auto calibration on boot failed, leave at current values
GBS::IF_AUTO_OFST_EN::write(0);
GBS::IF_AUTO_OFST_PRD::write(0); // 0 = by line, 1 = by frame
}
}
// blue only mode: t0t44t1 t0t44t4
void applyYuvPatches()
{
GBS::ADC_RYSEL_R::write(1); // midlevel clamp red
GBS::ADC_RYSEL_B::write(1); // midlevel clamp blue
GBS::ADC_RYSEL_G::write(0); // gnd clamp green
GBS::DEC_MATRIX_BYPS::write(1); // ADC
GBS::IF_MATRIX_BYPS::write(1);
if (GBS::GBS_PRESET_CUSTOM::read() == 0) {
// colors
GBS::VDS_Y_GAIN::write(0x80); // 3_25
GBS::VDS_UCOS_GAIN::write(0x1c); // 3_26
GBS::VDS_VCOS_GAIN::write(0x29); // 3_27
GBS::VDS_Y_OFST::write(0xFE);
GBS::VDS_U_OFST::write(0x03);
GBS::VDS_V_OFST::write(0x03);
if (rto->videoStandardInput >= 5 && rto->videoStandardInput <= 7) {
// todo: Rec. 709 (vs Rec. 601 used normally
// needs this on VDS and HDBypass
}
}
// if using ADC auto offset for yuv input / rgb output
//GBS::ADC_AUTO_OFST_EN::write(1);
//GBS::VDS_U_OFST::write(0x36); //3_3b
//GBS::VDS_V_OFST::write(0x4d); //3_3c
if (uopt->wantOutputComponent) {
applyComponentColorMixing();
}
}
// blue only mode: t0t44t1 t0t44t4
void applyRGBPatches()
{
GBS::ADC_RYSEL_R::write(0); // gnd clamp red
GBS::ADC_RYSEL_B::write(0); // gnd clamp blue
GBS::ADC_RYSEL_G::write(0); // gnd clamp green
GBS::DEC_MATRIX_BYPS::write(0); // 5_1f 2 = 1 for YUV / 0 for RGB << using DEC matrix
GBS::IF_MATRIX_BYPS::write(1);
if (GBS::GBS_PRESET_CUSTOM::read() == 0) {
// colors
GBS::VDS_Y_GAIN::write(0x80); // 0x80 = 0
GBS::VDS_UCOS_GAIN::write(0x1c);
GBS::VDS_VCOS_GAIN::write(0x29); // 0x27 when using IF matrix, 0x29 for DEC matrix
GBS::VDS_Y_OFST::write(0x00); // 0
GBS::VDS_U_OFST::write(0x00); // 2
GBS::VDS_V_OFST::write(0x00); // 2
}
if (uopt->wantOutputComponent) {
applyComponentColorMixing();
}
}
/// Write ADC gain registers, and save in adco->r_gain to properly transfer it
/// across loading presets or passthrough.
void setAdcGain(uint8_t gain) {
// gain is actually range, increasing it dims the image.
GBS::ADC_RGCTRL::write(gain);
GBS::ADC_GGCTRL::write(gain);
GBS::ADC_BGCTRL::write(gain);
// Save gain for applying preset. (Gain affects passthrough presets, and
// loading a passthrough preset loads from adco but doesn't save to it.)
adco->r_gain = gain;
adco->g_gain = gain;
adco->b_gain = gain;
}
void setAdcParametersGainAndOffset()
{
GBS::ADC_ROFCTRL::write(0x40);
GBS::ADC_GOFCTRL::write(0x40);
GBS::ADC_BOFCTRL::write(0x40);