summaryrefslogtreecommitdiff
path: root/src/encoder.c
blob: 64c28fe590b3fca8e583a3b433e965d0b534b746 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#include <stdlib.h>
/*
 * encoder.c - CX23416 encoder MBOX command layer and setup sequences
 *
 * Part of mpegcap.
 *
 * The CX23416 exposes a 32-bit "MBOX" register window at memory address
 * 0x44.  Commands are issued by writing a 16-word block there, setting
 * the DRIVER_DONE|DRIVER_BUSY bits in word 0, then polling word 0 until
 * FIRMWARE_DONE is set.
 */
#include <stdio.h>
#include <string.h>
#include <time.h>

#if defined(_WIN32)
#include <windows.h>
#endif

#include "pvrusb2.h"

#define MBOX_WORDS 16
#define MBOX_CMD_WORDS 12   /* words actually written before the "go" */

static void usleep100(void)
{
#if defined(_WIN32)
	Sleep(1);
#else
	struct timespec ts = { 0, 100000L };
	nanosleep(&ts, NULL);
#endif
}

/* ================================================================== */
/* Raw MBOX access                                                     */
/* ================================================================== */

int pvr2_mbox_write(pvr2_dev *p, uint32_t addr, const uint32_t *data, int count)
{
	uint8_t buf[1 + 7 * 8];
	int pos = 0;   /* index into data[] */
	int addr_cur = (int)addr;

	while (count > 0) {
		int next = count > 8 ? 8 : count;
		int i;

		buf[0] = FX2CMD_MEM_WRITE_DWORD;
		for (i = 0; i < next; i++) {
			uint32_t d = data[pos];
			buf[1 + 7 * i + 0] = d & 0xff;
			buf[1 + 7 * i + 1] = (d >> 8) & 0xff;
			buf[1 + 7 * i + 2] = (d >> 16) & 0xff;
			buf[1 + 7 * i + 3] = (d >> 24) & 0xff;
			buf[1 + 7 * i + 4] = (addr_cur >> 16) & 0xff;
			buf[1 + 7 * i + 5] = (addr_cur >> 8) & 0xff;
			buf[1 + 7 * i + 6] = addr_cur & 0xff;
			pos++;
			addr_cur++;
			count--;
		}
		if (bulk_cmd_out(p, buf, 7 * next + 1) < 0)
			return -1;
	}
	return 0;
}

int pvr2_mbox_read(pvr2_dev *p, uint32_t addr, uint32_t *data, int count)
{
	int done = 0;
	int addr_cur = (int)addr;

	while (done < count) {
		int next = (count - done) >= 16 ? 16 : 1;
		uint8_t buf[8];
		uint8_t in[64];
		int n, j;

		memset(buf, 0, sizeof(buf));
		buf[0] = next == 16 ? FX2CMD_MEM_READ_64BYTES : FX2CMD_MEM_READ_DWORD;
		buf[5] = (addr_cur >> 16) & 0xff;
		buf[6] = (addr_cur >> 8) & 0xff;
		buf[7] = addr_cur & 0xff;
		if (bulk_cmd_out(p, buf, 8) < 0)
			return -1;
		n = bulk_cmd_in(p, in, next * 4 + 8);
		if (n < next * 4)
			return -1;
		for (j = 0; j < next; j++)
			data[done + j] = (uint32_t)in[j * 4 + 0] |
				((uint32_t)in[j * 4 + 1] << 8) |
				((uint32_t)in[j * 4 + 2] << 16) |
				((uint32_t)in[j * 4 + 3] << 24);
		done += next;
		addr_cur += next;
	}
	return 0;
}

/* ================================================================== */
/* Encoder commands                                                    */
/* ================================================================== */

static void mkcmd(uint32_t *data, uint32_t cmd, const uint32_t *para, int size)
{
	int i = 0;
	data[i++] = 0;
	data[i++] = cmd;
	data[i++] = 0;
	data[i++] = 0x00060000;   /* timeout */
	for (; i < MBOX_WORDS; i++) {
		if (size > 0) {
			data[i] = *para++;
			size--;
		} else {
			data[i] = 0;
		}
	}
}

int pvr2_enc_cmd(pvr2_dev *p, uint32_t cmd, const uint32_t *args, int nargs)
{
	uint32_t data[MBOX_WORDS];
	uint32_t stat = 0;
	int i;

	mkcmd(data, cmd, args, nargs);

	if (pvr2_mbox_write(p, CX_MBOX_BASE, data, MBOX_CMD_WORDS) < 0)
		return -1;

	/* "go": DRIVER_DONE | DRIVER_BUSY */
	{
		uint32_t go = CX_MBOX_DRIVER_DONE | CX_MBOX_DRIVER_BUSY;
		if (pvr2_mbox_write(p, CX_MBOX_BASE, &go, 1) < 0)
			return -1;
	}

	/* poll FIRMWARE_DONE */
	for (i = 0; i < 1000; i++) {
		if (pvr2_mbox_read(p, CX_MBOX_BASE, &stat, 1) < 0)
			return -1;
		if (stat & CX_MBOX_FIRMWARE_DONE)
			break;
		usleep100();
	}
	if (!(stat & CX_MBOX_FIRMWARE_DONE)) {
		fprintf(stderr, "encoder command 0x%02x timed out\n", cmd);
		return -1;
	}

	/* return to idle */
	{
		uint32_t zero = 0;
		pvr2_mbox_write(p, CX_MBOX_BASE, &zero, 1);
	}
	return 0;
}

int pvr2_enc_get_version(pvr2_dev *p, uint32_t *ver)
{
	if (pvr2_enc_cmd(p, CX2341X_ENC_GET_VERSION, NULL, 0) < 0)
		return -1;
	if (pvr2_mbox_read(p, CX_MBOX_BASE + 4, ver, 1) < 0)
		return -1;
	return 0;
}

int pvr2_enc_ping(pvr2_dev *p)
{
	return pvr2_enc_cmd(p, CX2341X_ENC_PING_FW, NULL, 0);
}

/*
 * pvr2_enc_clear_flag - read-modify-write the encoder status word at
 * MBOX 0x48, clearing the given bits.
 *
 * The official driver does this in FUN_0001dd93 (called with 0x40000000
 * right after SET_AUDIO_PROPERTIES): it reads MBOX word 0x48 and clears
 * bit 30.  That bit gates the encoder's audio path.
 */
int pvr2_enc_clear_flag(pvr2_dev *p, uint32_t bits)
{
	uint32_t v;

	if (pvr2_mbox_read(p, 0x48, &v, 1) < 0)
		return -1;
	v &= ~bits;
	if (pvr2_mbox_write(p, 0x48, &v, 1) < 0)
		return -1;
	return 0;
}

/* ================================================================== */
/* Encoder setup sequences                                             */
/* ================================================================== */

int pvr2_encoder_preconfig(pvr2_dev *p)
{
	uint32_t para[8];
#define CMD(c, n) do { if (pvr2_enc_cmd(p, (c), para, (n)) < 0) \
		fprintf(stderr, "preconfig cmd 0x%02x failed\n", (c)); } while (0)

	para[0] = 3; para[1] = 1; para[2] = 0; para[3] = 0;
	CMD(CX2341X_ENC_MISC, 4);
	para[0] = 8; para[1] = 0; para[2] = 0; para[3] = 0;
	CMD(CX2341X_ENC_MISC, 4);
	para[0] = 0; para[1] = 3; para[2] = 0; para[3] = 0;
	CMD(CX2341X_ENC_MISC, 4);
	para[0] = 15; para[1] = 0; para[2] = 0; para[3] = 0;
	CMD(CX2341X_ENC_MISC, 4);
	para[0] = 4; para[1] = 1;
	CMD(CX2341X_ENC_MISC, 2);
#undef CMD
	return 0;
}

int vsync_lines = 0x140;   /* SET_NUM_VSYNC_LINES: buffer depth */

int pvr2_encoder_config(pvr2_dev *p, int sample_rate)
{
	uint32_t para[8];
	int errs = 0;
#define CMD(c, n) do { if (pvr2_enc_cmd(p, (c), para, (n)) < 0) { \
		fprintf(stderr, "config cmd 0x%02x failed\n", (c)); errs++; } } while (0)

	/*
	 * SET_OUTPUT_PORT takes TWO ports: param[0] = video, param[1] = audio.
	 * The INF pins OutType=10 for this device (param[0] = 1), and this tool
	 * has always sent param[1] = 0.  The Windows driver sends **[1, 2]**
	 * (docs/xp-init-sequence.txt: cmd 0xbb, args 1,2,0,0,0,0, the very first
	 * encoder command of its session), i.e. it enables an audio output port
	 * that this tool leaves at 0.  That is the only audio-specific argument
	 * that differs between the two stacks.
	 *   OUTTYPE=<n>       video port only (historical, default 1)
	 *   OUTPORT=<v>,<a>   both ports; e.g. OUTPORT=1,2 = the driver's value
	 */
	{
		const char *e = getenv("OUTPORT");
		const char *o = getenv("OUTTYPE");
		unsigned int vid = o ? (unsigned int)strtoul(o, NULL, 0) : 1;
		unsigned int aud = 0;
		if (e)
			sscanf(e, "%u,%u", &vid, &aud);
		para[0] = vid; para[1] = aud;
	}
	CMD(CX2341X_ENC_SET_OUTPUT_PORT, 2);

	/*
	 * ENCDNR=1 sends the four DNR/coring commands the Windows driver puts
	 * in its early set, right after SET_OUTPUT_PORT (capture #18-21):
	 *   0x9b = [2,0,0,0]  0x9f = [1,255,0,255]
	 *   0x9d = [0,0,0,0]  0x9f = [255,0,255,0]
	 * This tool never sends 0x9b or 0x9d at all and sends 0x9f only under
	 * AUDCMD, so the pair has never been exercised here.  (AUDCMD already
	 * carries the driver's *late* set, which sits after SET_AUDIO_PROP.)
	 */
	if (getenv("ENCDNR")) {
		para[0] = 2; para[1] = 0; para[2] = 0; para[3] = 0;
		CMD(0x9b, 4);
		para[0] = 1; para[1] = 255; para[2] = 0; para[3] = 255;
		CMD(0x9f, 4);
		para[0] = 0; para[1] = 0; para[2] = 0; para[3] = 0;
		CMD(0x9d, 4);
		para[0] = 255; para[1] = 0; para[2] = 255; para[3] = 0;
		CMD(0x9f, 4);
	}

	/*
	 * ENCMISC=1 sends the six CX2341X_ENC_MISC calls the Windows driver
	 * issues just before SET_NUM_VSYNC_LINES (capture #30-35):
	 *   MISC(5,0) MISC(3,1) MISC(8,0) MISC(4,1) MISC(0,3) MISC(15,0)
	 * This tool only ever sent MISC(12) (the documented audio-interface
	 * reset), so these subcommands have never been tried here.
	 */
	if (getenv("ENCMISC")) {
		static const uint32_t m[][2] = {
			{ 5, 0 }, { 3, 1 }, { 8, 0 },
			{ 4, 1 }, { 0, 3 }, { 15, 0 },
		};
		size_t k;
		for (k = 0; k < sizeof(m) / sizeof(m[0]); k++) {
			para[0] = m[k][0]; para[1] = m[k][1];
			para[2] = 0; para[3] = 0;
			CMD(CX2341X_ENC_MISC, 4);
		}
	}

	para[0] = 7; para[1] = 0x0190;
	CMD(CX2341X_ENC_SET_PGM_INDEX_INFO, 2);

	/* Frame-buffer depth.  The stock 0x140 (320 lines) makes the encoder
	 * hold ~1.5 s of video before it starts emitting, which shows up as
	 * playback lag.  Smaller values shorten that window. */
	para[0] = vsync_lines; para[1] = vsync_lines;
	CMD(CX2341X_ENC_SET_NUM_VSYNC_LINES, 2);

	para[0] = 0; para[1] = 0; para[2] = 0x10000000; para[3] = 0xffffffff;
	CMD(CX2341X_ENC_SET_EVENT_NOTIFY, 4);

	para[0] = 0;   /* NTSC 29.97 */
	CMD(CX2341X_ENC_SET_FRAME_RATE, 1);

	para[0] = 480; para[1] = 720;   /* NTSC 720x480 */
	CMD(CX2341X_ENC_SET_FRAME_SIZE, 2);

	para[0] = 2;   /* 4:3 */
	CMD(CX2341X_ENC_SET_ASPECT_RATIO, 1);

	/*
	 * The Windows driver does not send a single "disable" word here; it
	 * walks the VBI line table, two commands per line (#132-177):
	 *   SET_VBI_LINE[0x80000000|n, 0,0,0,0] then SET_VBI_LINE[n, 0,0,0,0]
	 * for n = 1..23 (the 0x80000000 form is the "line number valid" bit).
	 * VBISWEEP=1 replays that; without it the historical single call below
	 * is kept.
	 */
	if (getenv("VBISWEEP")) {
		unsigned int n;
		for (n = 1; n <= 23; n++) {
			para[0] = 0x80000000u | n;
			para[1] = 0; para[2] = 0; para[3] = 0; para[4] = 0;
			CMD(CX2341X_ENC_SET_VBI_LINE, 5);
			para[0] = n;
			para[1] = 0; para[2] = 0; para[3] = 0; para[4] = 0;
			CMD(CX2341X_ENC_SET_VBI_LINE, 5);
		}
	} else {
		para[0] = 0xffffffff; para[1] = 0; para[2] = 0;
		para[3] = 0; para[4] = 0;
		CMD(CX2341X_ENC_SET_VBI_LINE, 5);
	}

	para[0] = 0;   /* program stream (MPEG-PS) */
	{
		/* STREAMTYPE=10 = DVD stream, which is what the Windows
		 * driver actually sets (USB capture, docs/NOTES.md). */
		const char *e = getenv("STREAMTYPE");
		if (e)
			para[0] = (uint32_t)strtoul(e, NULL, 0);
	}
	CMD(CX2341X_ENC_SET_STREAM_TYPE, 1);

	/*
	 * SET_AUDIO_ID (0x89) assigns the *transport stream ID* of the
	 * encoded audio stream (cx2341x-devel: "Assigns the transport stream
	 * ID of the encoded audio stream").  It is NOT an audio input
	 * selector -- the comment here used to claim it selected the audio
	 * input, which is wrong, and no sweep of its value can change the
	 * input.  It only matters for transport-stream output; it stays 0
	 * because that is what the reference uses.
	 */
	para[0] = 0;
	CMD(CX2341X_ENC_SET_AUDIO_ID, 1);

	/*
	 * CX2341X_ENC_SET_BIT_RATE, per the API documentation:
	 *   Param[0] 0=variable bitrate, 1=constant bitrate
	 *   Param[1] average bitrate in bits per second
	 *   Param[2] peak bitrate in bits per second, DIVIDED BY 400
	 *   Param[3] mux bitrate / 400 (0)
	 *   Param[4] rate control VBR padding (0)
	 *   Param[5] VBV buffer (unused)
	 *
	 * ★ These two fields used to be the wrong way round: the peak was
	 * sent in Param[1] and the average/400 in Param[2], i.e. the encoder
	 * was told "average 6 Mbit/s, peak 4 Mbit/s" -- a peak below the
	 * average, which is contradictory.  The rate controller then pinned
	 * the quantiser at its coarsest value (measured: quantiser_scale_code
	 * reaching 31 on I, P and B slices at the stock 4 Mbit/s) and the
	 * picture showed blocking / mosaic.  Linux's cx2341x.c sends
	 * [mode, video_bitrate, video_bitrate_peak / 400, 0, 0]; this now
	 * matches that order.  Verify with scripts/mpgqual.py.
	 *
	 * The official driver's INF pins Bitrate=4000000, BitratePeak=6000000.
	 */
	{
		const char *e;
		uint32_t br = 4000000, bp = 6000000;
		uint32_t mux = 0;            /* 0 = auto (old behaviour) */
		if ((e = getenv("BR")) != NULL)
			br = (uint32_t)strtoul(e, NULL, 0);
		if ((e = getenv("BRPEAK")) != NULL)
			bp = (uint32_t)strtoul(e, NULL, 0);
		/*
		 * ★ MUX=<bits/s> sets Param[3] (mux bitrate / 400).
		 *
		 * MEASURED 2026-10-15: with Param[3]=0 the encoder emits
		 * pack headers whose mux_rate field reads 15.75 Mbit/s
		 * while the stream actually runs ~6.2 Mbit/s.  The SCR
		 * clock then advances per-pack as if the data rate were
		 * 15.75 Mbit/s, i.e. SCR runs at ~0.36x wall time while
		 * PTS runs at true 29.97 fps.  A player that slaves its
		 * clock to SCR sees its buffer fill ~2.5x faster than
		 * SCR-time and keeps buffering -- that was the growing
		 * multi-second LIVE LAG (and the old "Incorrect SCR
		 * timing in advance" VLC warnings).  Setting the mux rate
		 * to the real total (video avg + audio + overhead) makes
		 * SCR track wall time and the live edge stays ~0.3 s.
		 */
		/*
		 * ★ MUX=<bits/s> sets the program mux rate so the SCR clock
		 * runs at wall time (see the measurement note below).
		 * Units measured on hardware: the pack header's mux_rate
		 * field comes out at param3 * 800 bit/s (asking for
		 * 7,000,000 with /400 gave a 14,000,400 field), so the
		 * divisor here is 800, not 400.
		 */
		if ((e = getenv("MUX")) != NULL)
			mux = (uint32_t)strtoul(e, NULL, 0);
		para[0] = 0;              /* variable bitrate */
		para[1] = br;             /* average bitrate, bits/s */
		para[2] = bp / 400;       /* peak bitrate / 400 */
		para[3] = mux / 800;      /* mux rate: param3*800 = field */
		para[4] = 0; para[5] = 0;
	}
	CMD(CX2341X_ENC_SET_BIT_RATE, 6);

	para[0] = 0x0f; para[1] = 0x03;
	CMD(CX2341X_ENC_SET_GOP_PROPERTIES, 2);

	para[0] = 0x00;
	CMD(CX2341X_ENC_SET_3_2_PULLDOWN, 1);

	para[0] = 0x00;
	CMD(CX2341X_ENC_SET_GOP_CLOSURE, 1);

	/* Audio properties.  The working reference (pvrusb2_capture.py)
	 * uses the mpegcapt-style value 0x40b8|N.  The official driver uses
	 * 0xe9, but on this device 0xe9 alone did not produce audio and the
	 * 0x40b8 form is the known-good one, so use it. */
	/*
	 * Two forms are in circulation.  pvrusb2_capture.py, and so the
	 * mpegcapt lineage this code started from, uses 0x40b8 | N with N
	 * selecting the sample rate.  The official I-O DATA Windows driver
	 * uses a plain 0xe9 instead.  AUDIOPROP picks between them, because
	 * neither has produced audio here so far and the codec is only just
	 * being initialised - the encoder's idea of what the audio format is
	 * may be the missing piece.
	 */
	{
		const char *ap = getenv("AUDIOPROP");
		/*
		 * The INF's SamplingRate is 2, which selects 44.1 kHz on this
		 * part, and AudioOutputMode/AudioCRC are both 0.
		 */
		if ((ap = getenv("AUDIOPROP")) != NULL)
			para[0] = (uint32_t)strtoul(ap, NULL, 0);
		else switch (sample_rate) {
		case 32000: para[0] = 0x40b8 | 2; break;
		case 44100: para[0] = 0x40b8 | 0; break;
		case 48000:
		default:    para[0] = 0x40b8 | 1; break;
		}
	}
	CMD(CX2341X_ENC_SET_AUDIO_PROP, 1);

	/*
	 * Three commands the Windows driver sends immediately after
	 * SET_AUDIO_PROPERTIES, which are NOT in the cx2341x API list
	 * (they sit between SET_ASPECT_RATIO 0x99 and SET_SPATIAL_FILTER
	 * 0xa1).  Captured values:
	 *   0x9b = [2, 0, 0, 0]
	 *   0x9f = [0, 0, 255, 0]
	 *   0x9d = [0, 0, 0, 0]
	 *   0x9f = [0, 0, 255, 0]      (repeated)
	 * They arrive right after the audio properties, so they are the
	 * prime suspects for "the encoder needs to be told there is audio".
	 * AUDCMD=1 sends them.
	 */
	if (getenv("AUDCMD")) {
		para[0] = 2; para[1] = 0; para[2] = 0; para[3] = 0;
		CMD(0x9b, 4);
		para[0] = 0; para[1] = 0; para[2] = 255; para[3] = 0;
		CMD(0x9f, 4);
		para[0] = 0; para[1] = 0; para[2] = 0; para[3] = 0;
		CMD(0x9d, 4);
		para[0] = 0; para[1] = 0; para[2] = 255; para[3] = 0;
		CMD(0x9f, 4);
	}

	para[0] = 1; para[1] = 1;
	{
		/* SPATIAL=<a>,<b>: the driver sends 3,1 (capture). */
		const char *e = getenv("SPATIAL");
		if (e) {
			unsigned int a = 1, b = 1;
			sscanf(e, "%u,%u", &a, &b);
			para[0] = a; para[1] = b;
		}
	}
	CMD(CX2341X_ENC_SET_SPATIAL_FILTER, 2);

	CMD(CX2341X_ENC_INITIALIZE_INPUT, 0);

	/*
	 * CX2341X_ENC_MISC command 12 = "reset audio interface after channel
	 * change or input switch (has no argument).  Needed for the cx2584x,
	 * not needed for the mspx4xx, but it doesn't seem to do any harm
	 * calling it regardless."  (cx2341x-devel, CX2341X_ENC_MISC)
	 *
	 * This unit's decoder is a CX25837 -- cx2583x family, the same
	 * serial-audio-interface design the note calls out -- and neither
	 * this tool nor pvrusb2 (whose ENC_MISC list this file mirrors) ever
	 * sends it.  It is the only documented encoder-side command that
	 * touches the audio *interface* rather than the audio format, so it
	 * is the first thing to try for "the encoder never sees the ADC".
	 *
	 * AUDIORESET selects the shape:
	 *   0 = do not send it
	 *   1 = MISC(12,0,0,0)   (default; MISC is a 4-word command)
	 *   2 = MISC(12)         ("has no argument")
	 *   3 = MISC(12,0)       (command + value)
	 * Commands 13 (set audio volume delay) and 14 (set audio delay) are
	 * also exposed via AUDIODELAY=<13|14>:<value> for completeness.
	 */
	{
		const char *ar = getenv("AUDIORESET");
		int mode = ar ? atoi(ar) : 1;
		if (mode == 1) {
			para[0] = 12; para[1] = 0; para[2] = 0; para[3] = 0;
			CMD(CX2341X_ENC_MISC, 4);
		} else if (mode == 2) {
			para[0] = 12;
			CMD(CX2341X_ENC_MISC, 1);
		} else if (mode == 3) {
			para[0] = 12; para[1] = 0;
			CMD(CX2341X_ENC_MISC, 2);
		}
	}
	{
		const char *ad = getenv("AUDIODELAY");
		if (ad) {
			int which = atoi(ad);
			const char *colon = strchr(ad, ':');
			uint32_t v = colon ? (uint32_t)strtoul(colon + 1, NULL, 0) : 0;
			if (which == 13 || which == 14) {
				para[0] = (uint32_t)which; para[1] = v;
				para[2] = 0; para[3] = 0;
				CMD(CX2341X_ENC_MISC, 4);
			}
		}
	}
#undef CMD
	return errs ? -1 : 0;
}

int pvr2_encoder_start(pvr2_dev *p)
{
	return pvr2_encoder_start_ex(p, 0, 0x13);   /* MPEG */
}

/*
 * pvr2_encoder_start_ex - start capture with an explicit (type, subtype).
 *   MPEG  : type=0, subtype=0x13
 *   raw YUV (HM12): type=1, subtype=0x11   (see cx2341x-uapi docs)
 */
int pvr2_encoder_start_ex(pvr2_dev *p, uint32_t captype, uint32_t subtype)
{
	uint32_t para[8];
	int r;
	int skip_mute = (getenv("NOSTARTMUTE") != NULL);

	/*
	 * ★ The Windows driver sends NEITHER 0xd9 (MUTE_VIDEO) nor 0xda
	 * (MUTE_AUDIO): the pcap's full command census over four start/stop
	 * cycles is 0x81/0x82/0x8f/0x91/0x95/0x97/0x99/0x9b/0x9d/0x9f/0xa1/
	 * 0xb1/0xb7/0xb9/0xbb/0xbd/0xc5/0xc7/0xcd/0xd5/0xd6/0xdc and nothing
	 * else -- both are absent.  This tool has always sent them just before
	 * START_CAPTURE, so NOSTARTMUTE=1 skips the pair to match.
	 */
	if (!skip_mute) {
		para[0] = 0;
		r = pvr2_enc_cmd(p, CX2341X_ENC_MUTE_VIDEO, para, 1);
		if (r < 0)
			fprintf(stderr, "mute video failed\n");
	}

	/*
	 * Audio mute.  MUTE_AUDIO=1 asks the encoder to produce a *silent*
	 * mpeg audio stream (cx2341x-devel: "1=audio muted (produces silent
	 * mpeg audio stream)").  That is a control measurement, not a
	 * feature: if audio PES start appearing with mute on and the count
	 * is 0 with mute off, the encoder's audio path works and the problem
	 * is upstream (the ADC / I2S input); if the count is 0 either way,
	 * the encoder is not emitting audio PES at all.
	 */
	{
		const char *mu = getenv("MUTEAUDIO");
		if (!skip_mute) {
			para[0] = mu ? (uint32_t)strtoul(mu, NULL, 0) : 0;
			r = pvr2_enc_cmd(p, CX2341X_ENC_MUTE_AUDIO, para, 1);
			if (r < 0)
				fprintf(stderr, "unmute audio failed\n");
		}
	}

	para[0] = captype; para[1] = subtype;
	r = pvr2_enc_cmd(p, CX2341X_ENC_START_CAPTURE, para, 2);
	if (r < 0) {
		fprintf(stderr, "encoder start failed\n");
		return -1;
	}
	fprintf(stderr, "CX23416 encoder started (captype=%u subtype=0x%x)\n",
	       captype, subtype);
	return 0;
}

/*
 * pvr2_encoder_stop - CX2341X_ENC_STOP_CAPTURE (0x82).
 *
 * ★ This call was MISSING entirely (the header defined the command but no
 * code ever sent it): every run just stopped reading USB and closed, so the
 * encoder was never told to end the capture.  Both references do send it:
 *
 *   vendor pcap (4 start/stop cycles): 0x81 [0,19,..] ... 0x82 [1,0,19,..]
 *     i.e. when=1 (stop now), type=0 (MPEG), subtype=0x13
 *   yacxm cxm_stop_encoder(): CXM_FW_CMD_END_CAPTURE (0x82) with
 *     parameters[0] = mpeg ? 0 : 1   ("when": 0 = end of GOP, 1 = now),
 *     parameters[1] = type, parameters[2] = subtype -- and then waits up to
 *     1 s for the EOS interrupt.
 *
 * Symptom this fixes: after an MPEG run, switching to raw/YUV left the
 * encoder holding its previous state/buffer, so the new run appeared to
 * "stop on the previous buffer".  Sending the stop with the SAME
 * (type, subtype) the capture was started with returns the encoder to idle
 * before the next mode change.
 *
 * when: 0 = stop at end of GOP (MPEG, graceful), 1 = stop immediately.
 * STOPENV=<0|1> overrides "when" for experiments.
 */
int pvr2_encoder_stop(pvr2_dev *p, uint32_t captype, uint32_t subtype,
		      uint32_t when)
{
	uint32_t para[3];
	const char *e = getenv("STOPENV");
	int r, tries;

	if (e)
		when = (uint32_t)strtoul(e, NULL, 0);
	para[0] = when; para[1] = captype; para[2] = subtype;
	/*
	 * Retry: in raw mode the firmware holds ~1.5 s of HM12 frames, so the
	 * mailbox handshake can time out (pvr2_enc_cmd polls ~100 ms) while
	 * the encoder is busy flushing.  A FAILED stop leaves the encoder
	 * running, which is exactly the state that makes the next mode change
	 * come up stuck, so it is worth three tries.
	 */
	for (r = -1, tries = 0; tries < 3; tries++) {
		r = pvr2_enc_cmd(p, CX2341X_ENC_STOP_CAPTURE, para, 3);
		if (r == 0)
			break;
		{
			struct timespec ts = { 0, 200000000L };
			nanosleep(&ts, NULL);
		}
	}
	fprintf(stderr, "CX23416 encoder stop (0x82) when=%u captype=%u "
		"subtype=0x%x -> %s\n", when, captype, subtype,
		r < 0 ? "FAILED" : "ok");
	return r;
}

/* ================================================================== */
/* CX25843 (cx2583x family) decoder initialisation                     */
/* ================================================================== */

/* Read-modify-write a single decoder register (and_or helper).
 * mask/val are taken as unsigned int so that constructs like ~0xc0 are
 * not truncated to a byte (which would turn ~0xc0 into 0x3f). */
static int cx2584x_and_or(pvr2_dev *p, uint16_t reg, unsigned int mask,
			  unsigned int val)
{
	uint8_t v;
	if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, reg, &v, 1) < 0)
		return -1;
	v = (uint8_t)((v & ~(uint8_t)mask) | ((uint8_t)val & (uint8_t)mask));
	return pvr2_i2c_write(p, CX2584X_I2C_ADDR, reg, &v, 1);
}

/*
 * cx25836_initialize - datasheet startup, page 3-77 of the CX25836/43
 * datasheet.  Ported from the Linux cx25840 driver's cx25836_initialize().
 *
 * The cx2583x family does NOT need the microcontroller firmware image
 * (v4l-cx25840.fw); only the cx25840/41/44/45 do.  The cx2583x bring-up
 * is this short register sequence, which starts the internal DLL used for
 * the video/audio clock tree.
 */
int pvr2_cx2584x_init(pvr2_dev *p)
{
	/* 2. reset toggle */
	if (cx2584x_and_or(p, 0x000, ~0x01, 0x01) < 0) return -1;
	if (cx2584x_and_or(p, 0x000, ~0x01, 0x00) < 0) return -1;
	/* 3a. */
	if (cx2584x_and_or(p, 0x15a, ~0x70, 0x00) < 0) return -1;
	/* 3b. */
	if (cx2584x_and_or(p, 0x15b, ~0x1e, 0x06) < 0) return -1;
	/* 3c. */
	if (cx2584x_and_or(p, 0x159, ~0x02, 0x02) < 0) return -1;
	/* 3d. short delay */
	{
		struct timespec ts = { 0, 10000000L };  /* 10 ms */
		nanosleep(&ts, NULL);
	}
	/* 3e. */
	if (cx2584x_and_or(p, 0x159, ~0x02, 0x00) < 0) return -1;
	/* 3f. */
	if (cx2584x_and_or(p, 0x159, ~0xc0, 0xc0) < 0) return -1;
	/* 3g. */
	if (cx2584x_and_or(p, 0x159, ~0x01, 0x00) < 0) return -1;
	if (cx2584x_and_or(p, 0x159, ~0x01, 0x01) < 0) return -1;
	/* 3h. */
	if (cx2584x_and_or(p, 0x15b, ~0x1e, 0x10) < 0) return -1;

	return 0;
}

/*
 * cx2584x_input_change - follow steps 8c/8d of section 3.16 of the
 * CX25840 datasheet, plus the audio-standard setup.
 *
 * Ported from the Linux cx25840 driver's input_change().  For NTSC the
 * video mode must be set (0x402, 0x49f, 0x401) and the audio carrier
 * standard chosen.  This device is a Japanese model (BTSC vs EIAJ
 * matters), so 0x808 is programmed with the EIAJ value (0xf7) which is
 * what the Linux driver uses for V4L2_STD_NTSC_M_JP.
 */
int pvr2_cx2584x_input_change(pvr2_dev *p, int japan_audio)
{
	uint8_t d;

	/* 8c: video mode */
	d = 0x04; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0402, &d, 1);
	d = 0x14; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x049f, &d, 1);
	cx2584x_and_or(p, 0x0401, ~0x60, 0x00);
	cx2584x_and_or(p, 0x0401, ~0x60, 0x60);

	/*
	 * Audio standard.  On the cx2583x family the driver deliberately
	 * does NOT touch 0x810/0x808-style audio DSP registers (it causes
	 * audio drop-out on cx25840/41), but the audio carrier must still be
	 * selected.  The decoder mutes audio until 0x810 bit0 is set; for
	 * NTSC the carrier byte goes into 0x808 and the subcarrier into
	 * 0x80b.
	 *   0xf7 = EIAJ (Japan)   0xf6 = BTSC (US)
	 */
	cx2584x_and_or(p, 0x0810, ~0x01, 0x01);
	d = japan_audio ? 0xf7 : 0xf6;
	pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0808, &d, 1);
	d = 0x00;
	pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x080b, &d, 1);

	return 0;
}

/* ================================================================== */
/* Video decoder (CX25843) input selection + audio PLL                 */
/* ================================================================== */

/*
 * pvr2_video_input - select the video input, matching the Linux cx25840
 * driver's cx25840_video_input() encoding of register 0x0103 and 0x0401.
 *
 * 0x0103 layout (base 0xf0):
 *   bits 0-3: luma input  (0..7 -> In1..In8)
 *   bits 4-5: chroma input (from In4..In7 / In7..In8)  [S-Video]
 *   bits 6-7: audio input (In4..In8)
 * Register 0x0401 bits 1-2 select the input MODE: 0=composite, 2=S-Video,
 * 6=component.
 *
 * ★ RZ2 CORRECTION (2026-10-15, measured from the vendor pcap): the yellow
 * RCA (composite) is NOT on In4.  The vendor's capture sequence writes
 * 0x103 = 0xe1 with 0x401 = 0xf2, i.e. CH1 = In2, CH2 = In6, MODE = Y/C.
 * The board routes the composite jack to In2 (CH1) + In6 (CH2) and the
 * decoder runs in Y/C mode.  Our old default (0x103 = 0xf3 = CH1 = In4,
 * CH2 = None, composite mode) put luma on the wrong pin and no chroma at
 * all, which is exactly "colour missing + crawling dots".  The old comment
 * claiming "0xf3 gives full colour" was wrong (it was verified on a
 * different symptom, never against the vendor's 0xe1).
 *
 * mode 0 = S-Video, index selects the chroma input (0..4 above);
 * mode 1 = composite, index is In1..In8 (0xf0 + index - 1).
 */
/*
 * ★ Input switching, from the CX25836/7 datasheet (Table 3-13 / 3-14):
 *   0x401 INPUT_MODE (bits 2:1) = 00 Composite Video/Audio (ADC1=CVBS,
 *   ADC2=Audio) | 01 Y/C, S-Video (ADC1=Luma, ADC2=Chroma) | 11 Y/Pb/Pr.
 *   Writing INPUT_MODE triggers the AFE auto-config (Table 3-14): the
 *   0x105/0x106 AFE fields (CLAMP_EN_CHx etc.) are then set BY THE CHIP.
 *   The vendor writes 0x105 = 0xdd in every session of the pcap, composite
 *   and Y/C alike -- the Y/C auto-config value -- which is consistent with
 *   the RCA being routed through the NEC pair (uPD64031A ADC+clamp ->
 *   uPD64084GC 3-D Y/C separation) and arriving at the decoder as a Y/C
 *   pair on In2 (luma) / In6 (chroma).
 *
 * ★ The vendor's input-switch sequence, measured (pcap, repeated at every
 * session start):
 *     0x103 = 0x11   (luma In2)      with 0x401 still 0xf0 (composite)
 *     0x103 = 0xd0   (luma In1, chroma In5)   <- intermediate step
 *     0x401 = 0xf2   (INPUT_MODE = 01, Y/C -> AFE auto-config)
 *     0x103 = 0xe1   (luma In2, chroma In6)   <- final state
 *     0x103 = 0xe1   (repeated)
 * INPUTSEQ=0 skips the two intermediate steps (diagnostics / A-B).
 */
static void input_switch_seq(pvr2_dev *p)
{
	uint8_t v, mode;
	struct timespec ts = { 0, 20000000L };   /* 20 ms settle */

	fprintf(stderr, "input switch (vendor sequence): 0x103=0x11 (composite) "
		"-> 0x103=0xd0 -> 0x401=0xf2 (Y/C) -> 0x103=0xe1\n");
	/* 1. composite mode first (INPUT_MODE = 00) */
	if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1) == 0) {
		mode &= (uint8_t)~0x06;
		pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1);
	}
	v = 0x11;
	pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
	nanosleep(&ts, NULL);
	/* 2. intermediate luma/chroma step */
	v = 0xd0;
	pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
	nanosleep(&ts, NULL);
	/* 3. switch to Y/C (INPUT_MODE = 01); the chip auto-configures the
	 *    AFE on this write */
	if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1) == 0) {
		mode = (uint8_t)((mode & (uint8_t)~0x06) | 0x02);
		pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1);
	}
	nanosleep(&ts, NULL);
	/* 4. final pin pair (the caller re-writes 0x103 with the rest) */
	v = 0xe1;
	pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
	nanosleep(&ts, NULL);
}

int pvr2_video_input_sel(pvr2_dev *p, int mode, int index)
{
	uint8_t val, d, reg103;

	if (mode == 0) {                       /* S-Video */
		/*
		 * ★ MEASURED 2026-10-25 with a recorder in the S jack: the S
		 * jack is luma In1 + chroma In5, i.e. 0x103 = 0xd0.
		 *
		 * Evidence, not inference:
		 *  - 0x103=0xd0 gives a real picture (a film played on the
		 *    recorder); 0xc3, the value this table used to send,
		 *    gives a dead-flat black frame.
		 *  - General Status 2 (0x040e) reads 0x7d for luma In1 and
		 *    only 0x00-0x09 for In2..In8: 0x7d is VPRES|AGC_LOCK|
		 *    CSC_LOCK|VLOCK|HLOCK, so In1 is the only pin carrying a
		 *    video signal with sync.  A null reading on the others is
		 *    "no signal", not "pin absent".
		 *  - The chroma plane confirms the C pin: with chroma on In5
		 *    the raw U/V planes carry signal (U sd 9.85, |dU| 1.29);
		 *    with In6/In7/In8 they are exactly 128.00, sd 0.00 - dead.
		 *  - It is also the datasheet's canonical Y1/C1 pair
		 *    (CX25836/7 Table 3-5: Y1 -> CH{1}_SRC 000, C1 ->
		 *    CH{2}_SRC 01).
		 *
		 * The old table {0xc3,0xd3,0xe3,0x33,0x73} had luma pinned to
		 * In4 and was never measured with anything in the jack; 0xc3
		 * in particular puts CH{2} on the SAME pin as CH{1}
		 * (CH{2}_SRC 00 = CVBS4/Y4), which cannot be an S-Video pair.
		 *
		 * Only chroma In5 is measured; the other three are the
		 * datasheet's remaining C inputs, kept for experiments.
		 */
		static const uint8_t svid[4] = { 0xd0, 0xe0, 0x30, 0x70 };
		static const int    cpin[4] = { 5, 6, 7, 8 };
		if (index < 0) index = 0;
		if (index > 3) index = 3;
		reg103 = svid[index];
		fprintf(stderr, "video input: S-Video luma In1 + chroma In%d "
			"(0x103=0x%02x, Y/C mode)%s\n", cpin[index], reg103,
			index == 0 ? "" : " - chroma pin not measured");
	} else {                               /* composite */
		/*
		 * ★ RZ2: the composite jack is CH1=In2 + CH2=In6 in Y/C
		 * mode (0x103 = 0xe1, 0x401 bits1-2 = 01).  -I still
		 * overrides everything for experiments.
		 */
		const char *ri = getenv("VIDIN");
		if (ri) {
			reg103 = (uint8_t)strtoul(ri, NULL, 0);
		} else {
			reg103 = 0xe1;
			/* reproduce the driver's composite -> Y/C switch
			 * (INPUTSEQ=0 skips it) */
			if (!getenv("INPUTSEQ"))
				input_switch_seq(p);
		}
		fprintf(stderr, "video input: composite via the NEC pair "
			"(In2+In6, 0x103=0x%02x, Y/C mode)\n", reg103);
	}
	/*
	 * Bits 6-7 of 0x0103 select the audio input (In4..In8).  They are
	 * left at whatever the base 0xf0..0xf7 value carries, which is 0 -
	 * and with no audio input selected the ADC never sees a signal, so
	 * no audio PES can appear no matter what the clock registers say.
	 * AIN=<n> overrides it: 0..4 -> In4..In8.
	 */
	{
		const char *ain = getenv("AIN");
		if (ain) {
			int n = atoi(ain);
			if (n < 0) n = 0;
			if (n > 4) n = 4;
			reg103 = (uint8_t)((reg103 & 0x3f) | (n << 6));
			fprintf(stderr, "audio input: In%d (0x103 bits6-7 = "
				"%d, 0x103=0x%02x)\n", 4 + n, n, reg103);
		}
	}
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &reg103, 1) < 0)
		return -1;

	/* Video Mode Control 2 (reg 0x0401): bits 1-2 = input mode.
	 * ★ RZ2 composite also runs in Y/C mode (vendor writes 0xf2). */
	if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &val, 1) < 0)
		return -1;
	d = (val & ~0x06) | 0x02;
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &d, 1) < 0)
		return -1;

	/*
	 * AFE Control 2 (0x0105).  ★ The vendor writes 0xdd here in EVERY
	 * session of the pcap -- the composite (RCA) one included -- and 0xdd
	 * is the Y/C auto-config value (bits 3:1 = 110, CLAMP_EN_CH2 set).
	 * That is the AFE setting that matches a signal arriving as Y/C from
	 * the NEC pair, which is what the RCA jack actually is on this board.
	 * The old code cleared bits 3:1 for composite (0xd1), i.e. configured
	 * the AFE for a raw CVBS input that never reaches the decoder.
	 * AFE105=<hex> overrides.
	 */
	{
		const char *e = getenv("AFE105");
		d = e ? (uint8_t)strtoul(e, NULL, 0) : 0xdd;
	}
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0105, &d, 1) < 0)
		return -1;

	/*
	 * ★ Vertical blanking delay (0x0474) AND the 656 blanking (0x0477),
	 * measured 2026-10-25.  These two must move together.
	 *
	 * The top of the captured picture carried the source's VBI waveform:
	 * a fixed row of white dashes (the user's "上によくわからない線"),
	 * with rows 0/1 byte-identical frame to frame, row 2 nearly so and
	 * row 3 carrying the changing data.
	 *
	 * 0x0474 is the delay from vertical reset to the start of active
	 * video, and one count = one output row: 20 -> rows 0-3 are VBI,
	 * 21 -> row 0 blank ... 24 -> all four blanked.
	 *
	 * ★ But raising 0x0474 ALONE makes the top WORSE, not better: the
	 * datasheet (5-77) says V656BLANK_CNT "must = vblank_cnt + 0x04 to
	 * have vblank and v656blank line up", and 0x0477 is what sets the
	 * V-bit the ENCODER reads off the 656 bus.  Move only 0x0474 and the
	 * encoder still considers those rows active video, so it keeps
	 * whatever the ADC reports: Y=1 and chroma 141/116, which renders as
	 * the user's "ピンクと緑の線" (Y=1,U=V=141 -> dark magenta;
	 * Y=16,U=V=116 -> green).
	 *
	 * Measured pairs (0x0474, 0x0477), raw y4m, top rows of luma plane:
	 *   20,24  Y 54,54,39,47  chroma neutral   <- VBI dashes, old
	 *   24,24  Y  1, 1, 1, 1  sat 254          <- pink/green (broken pair)
	 *   24,26  Y  1, 1,16,16  sat 180          <- half fixed
	 *   24,28  Y 16,16,16,16  sat   4          <- clean, picture in place
	 *   24,30  Y 16,16,16,16  sat  10          <- clean but window slid
	 * So 24/28 it is: the film's letterbox edge moves from row 14 to row 10
	 * only because the window now really starts at NTSC line 21 instead of
	 * line 17, and the source's bottom letterbox becomes visible too.
	 *
	 * Do not use the vendor table's 26: it blanks two rows of real picture,
	 * invisible on a letterboxed film and wrong on a full-frame source.
	 * VBLANK=<n> overrides both (0 = leave the decoder alone, for A/B).
	 */
	{
		const char *e = getenv("VBLANK");
		uint8_t v = e ? (uint8_t)strtoul(e, NULL, 0) : 0x18;
		if (v) {
			uint8_t b656 = (uint8_t)(v + 4);
			pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0474, &v, 1);
			pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0477, &b656, 1);
		}
	}
	(void)val;

	return 0;
}

int pvr2_video_input(pvr2_dev *p, int composite)
{
	return pvr2_video_input_sel(p, composite ? 1 : 0, composite ? 5 : 0);
}

int pvr2_audio_init(pvr2_dev *p, int sample_rate)
{
	uint8_t buf[8];
	uint32_t pll_frac;
	uint8_t pll_int, pll_post;
	uint8_t pin12;

	fprintf(stderr, "audio sampling rate: %d Hz\n", sample_rate);
	switch (sample_rate) {
	case 32000:
		/*
		 * Two sets of values exist for 32 kHz and they disagree:
		 *   pvr2_audio_init   post=0x1e  frac=0x012a0869
		 *   official driver   post=0x10  frac=0x01bb39ee
		 * 44.1 and 48 kHz agree between the two, 32 kHz is the odd
		 * one out, which is why 32 kHz is the rate to test against
		 * the driver table.  PLLDIV32 selects between them.
		 */
		if (getenv("PLLDIV32")) {
			pll_int = 0x06; pll_post = 0x10;
			pll_frac = 0x01bb39ee;
			fprintf(stderr, "  32 kHz PLL: using the official "
				"driver values (post=0x10 frac=0x01bb39ee)\n");
		} else {
			pll_int = 0x08; pll_post = 0x1e;
			pll_frac = 0x012a0869;
			fprintf(stderr, "  32 kHz PLL: using pvr2_audio_init "
				"values (post=0x1e frac=0x012a0869)\n");
		}
		break;
	case 44100:
		pll_int = 0x09; pll_post = 0x18; pll_frac = 0x00ec6bd6;
		break;
	case 48000:
	default:
		pll_int = 0x0a; pll_post = 0x18; pll_frac = 0x0098d6e5;
		break;
	}

	/* Aux PLL (reg 0x0108, 4 bytes) */
	buf[0] = 0x0f;
	buf[1] = 0x04;
	buf[2] = pll_int;
	buf[3] = pll_post;
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0108, buf, 4) < 0)
		return -1;

	/* Aux PLL fractional (reg 0x0110, 4 bytes) */
	buf[0] = pll_frac & 0xff;
	buf[1] = (pll_frac >> 8) & 0xff;
	buf[2] = (pll_frac >> 16) & 0xff;
	buf[3] = (pll_frac >> 24) & 0xff;
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0110, buf, 4) < 0)
		return -1;

	/* Pin Configuration 12 (reg 0x0127) */
	pin12 = (1 << 6) | (uint8_t)(256.0 / 384.0 * pll_post);
	if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0127, &pin12, 1) < 0)
		return -1;

	/* Pin control: 0x0118 selects the audio serial-output mode.  The
	 * 0x0115/0x0116 enable bits are ORed in by the caller after this
	 * function so they are not clobbered here. */
	{
		uint8_t d;
		d = 0x02; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0118, &d, 1);
	}

	return 0;
}

/* ================================================================== */
/* Streaming                                                           */
/* ================================================================== */

int pvr2_streaming_on(pvr2_dev *p)
{
	uint8_t cmd = FX2CMD_STREAMING_ON;
	return pvr2_simple_cmd(p, cmd, NULL, 0);
}

int pvr2_streaming_off(pvr2_dev *p)
{
	uint8_t cmd = FX2CMD_STREAMING_OFF;
	return pvr2_simple_cmd(p, cmd, NULL, 0);
}