-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPCMF1SimulatorApp.java
More file actions
2446 lines (2157 loc) · 110 KB
/
Copy pathPCMF1SimulatorApp.java
File metadata and controls
2446 lines (2157 loc) · 110 KB
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
import org.jcodec.api.FrameGrab;
import org.jcodec.api.SequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.model.Rational;
import org.jcodec.scale.AWTUtil;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.prefs.Preferences;
/**
* Main application class for the Sony PCM-F1 STC-007 Hardware Simulator.
* This system provides a graphical UI and processing backend for encoding
* 16-bit PCM digital audio
* into a black-and-white analog-style video signal compliant with the 1981 EIAJ
* STC-007 standard,
* as well as decoding that video stream back into real-time audio playback
* while handling VHS-era
* data dropout corrections natively.
*/
public class PCMF1SimulatorApp extends JFrame {
private VideoPanel videoPanel = new VideoPanel();
private VUMeterPanel vuLeft = new VUMeterPanel("L");
private VUMeterPanel vuRight = new VUMeterPanel("R");
private JLabel lblStatus = new JLabel("Status: Ready");
private JButton btnPause = new JButton("Pause");
private JButton btnRestart = new JButton("Restart");
private volatile boolean isRunning = false;
private volatile boolean isPaused = false;
private String activeStatusText = "";
private File currentDecodeFile = null;
private JComboBox<String> cmbFormat = new JComboBox<>(new String[] { "NTSC", "PAL" });
private JComboBox<String> cmbEncoder = new JComboBox<>(new String[] { "JCodec", "FFmpeg" });
private JComboBox<String> cmbProtocol = new JComboBox<>(new String[] { "PCM-F1", "PCM-48K" });
private int crcErrors = 0;
private int correctionsP = 0;
private int lostBlocks = 0;
private int qLosses = 0;
private byte[] audioBuffer = new byte[32768]; // Shared audio buffer to reduce GC pressure
private JCheckBox chkSB = new JCheckBox("SB");
private Thread activeCaptureThread = null;
private Thread activeDecodeThread = null;
private void stopCurrentEngineConnections() {
isRunning = false;
isPaused = false;
if (activeTargetLine != null) {
activeTargetLine.stop();
activeTargetLine.close();
}
if (activeDataLine != null) {
activeDataLine.stop();
activeDataLine.close();
}
if (activeCaptureThread != null && activeCaptureThread.isAlive()) {
try {
activeCaptureThread.join(500);
} catch (Exception ignored) {
}
}
if (activeDecodeThread != null && activeDecodeThread.isAlive()) {
try {
activeDecodeThread.join(500);
} catch (Exception ignored) {
}
}
}
// New playback controls
private JComboBox<String> cmbOutputDevice = new JComboBox<>();
private javax.sound.sampled.Mixer.Info[] outputMixers;
private SourceDataLine activeDataLine = null;
private TargetDataLine activeTargetLine = null;
private float currentVolume = 0.0f; // dB
// True STC-007 Constants
private static final int BITS_PER_LINE = 137;
private static final int WIDTH = 720; // 720 pixels NTSC broadcast standard
private static final int HEIGHT = 526; // Emulating full 525-line NTSC system
private static final int BIT_WIDTH = 5; // Revert to fixed block width
private static final int PIXEL_OFFSET = ((WIDTH - (BITS_PER_LINE * BIT_WIDTH)) / 2) + 1; // Center payload
private static final int VBLANK_LINES = 17; // Lines skipped for VHS head sync
private static final int DATA_LINES_PER_FIELD = 245; // Exactly 245 data lines per field as per STC-007 Spec
private static final int DATA_LINES_PER_FRAME = DATA_LINES_PER_FIELD * 2; // 490 total data lines per frame
// PCM-48K Constants
private static final int PCM48_BITS_PER_LINE = 152;
private static final int PCM48_BIT_WIDTH = 4;
private static final int PCM48_PIXEL_OFFSET = ((WIDTH - (PCM48_BITS_PER_LINE * PCM48_BIT_WIDTH)) / 2) + 1;
private static final int PCM48_AUDIO_LINES = 400;
private static final int PCM48_VBLANK_LINES = 40;
private static final int PCM48_SAMPLES_PER_LINE = 8;
private static final int PCM48_SAMPLES_PER_FRAME = PCM48_SAMPLES_PER_LINE * PCM48_AUDIO_LINES;
private String extractedMetadata = "PCM-48K-V1.0";
public PCMF1SimulatorApp() {
setTitle("Sony PCM-F1 Simulator v1.3.11 -- 4/23/2026");
setSize(1000, 700);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new BorderLayout());
JPanel vuPanel = new JPanel(new GridLayout(1, 2, 5, 0));
vuPanel.add(vuLeft);
vuPanel.add(vuRight);
centerPanel.add(vuPanel, BorderLayout.WEST);
centerPanel.add(videoPanel, BorderLayout.CENTER);
add(centerPanel, BorderLayout.CENTER);
JPanel controlPanel = new JPanel(new GridLayout(2, 1, 0, 5));
JPanel actionPanel = new JPanel();
JButton btnSave = new JButton("Encode Audio");
JButton btnOpen = new JButton("Decode Audio");
JButton btnSimulate = new JButton("Test (440Hz)");
JButton btnRealtime = new JButton("Realtime");
actionPanel.add(new JLabel("Protocol:"));
actionPanel.add(cmbProtocol);
actionPanel.add(new JLabel("Encoder:"));
actionPanel.add(cmbEncoder);
actionPanel.add(new JLabel("Format:"));
actionPanel.add(cmbFormat);
actionPanel.add(btnSave);
actionPanel.add(btnOpen);
actionPanel.add(btnSimulate);
actionPanel.add(btnRealtime);
actionPanel.add(chkSB);
chkSB.setToolTipText("Show Safe Boundary (TV viewable area)");
JPanel playbackPanel = new JPanel();
JButton btnVolDown = new JButton("Vol -");
JButton btnVolUp = new JButton("Vol +");
JButton btnStop = new JButton("Stop");
JButton btnExit = new JButton("Exit");
populateMixers();
playbackPanel.add(new JLabel("Audio Device:"));
playbackPanel.add(cmbOutputDevice);
playbackPanel.add(btnVolDown);
playbackPanel.add(btnVolUp);
playbackPanel.add(btnPause);
playbackPanel.add(btnRestart);
playbackPanel.add(btnStop);
playbackPanel.add(btnExit);
controlPanel.add(actionPanel);
controlPanel.add(playbackPanel);
add(controlPanel, BorderLayout.SOUTH);
btnVolDown.addActionListener(e -> adjustVolume(-3.0f));
btnVolUp.addActionListener(e -> adjustVolume(3.0f));
JPanel topPanel = new JPanel();
topPanel.add(lblStatus);
add(topPanel, BorderLayout.NORTH);
btnSave.addActionListener(e -> saveVideo());
btnOpen.addActionListener(e -> openVideo());
btnSimulate.addActionListener(e -> quickTest());
btnRealtime.addActionListener(e -> startRealtimeCapture());
btnPause.addActionListener(e -> {
if (isRunning) {
isPaused = !isPaused;
btnPause.setText(isPaused ? "Resume" : "Pause");
if (isPaused) {
activeStatusText = lblStatus.getText();
lblStatus.setText("Status: Paused...");
} else {
lblStatus.setText(activeStatusText);
}
}
});
btnRestart.addActionListener(e -> {
if (currentDecodeFile != null) {
btnRestart.setEnabled(false);
isRunning = false; // Kill old thread
isPaused = false;
btnPause.setText("Pause");
lblStatus.setText("Status: Restarting...");
new Thread(() -> {
try {
Thread.sleep(200);
} catch (Exception ignored) {
} // Wait for cleanup
SwingUtilities.invokeLater(() -> {
startDecoding(currentDecodeFile);
btnRestart.setEnabled(true);
});
}).start();
}
});
btnStop.addActionListener(e -> {
stopCurrentEngineConnections();
btnPause.setText("Pause");
lblStatus.setText("Status: Stopped");
vuLeft.reset();
vuRight.reset();
});
btnExit.addActionListener(e -> System.exit(0));
// Auto-restart Realtime capture if the device is changed while running
cmbOutputDevice.addActionListener(e -> {
boolean isRealtimeActive = lblStatus.getText().contains("Realtime Capture") ||
activeStatusText.contains("Realtime Capture");
if (isRunning && isRealtimeActive) {
startRealtimeCapture();
}
});
chkSB.addActionListener(e -> {
videoPanel.showSB = chkSB.isSelected();
videoPanel.repaint();
});
setVisible(true);
}
/**
* Discovers all available system audio devices and populates the Device
* dropdown menu with mixers that support hardware audio playback or recording.
* Prefixes the name with [IN] for recording devices and [OUT] for playback
* devices. Devices that ambiguously report both are excluded.
* NOTE: macOS CoreAudio is notoriously bad at reporting capabilities to Java.
* If the OS is Mac, all devices are unconditionally listed.
*/
private void populateMixers() {
ArrayList<Mixer.Info> outMixers = new ArrayList<>();
cmbOutputDevice.addItem("System Default");
outMixers.add(null);
boolean isMac = System.getProperty("os.name").toLowerCase().contains("mac");
for (Mixer.Info info : AudioSystem.getMixerInfo()) {
if (info.getName().startsWith("Port")) {
continue;
}
if (isMac) {
outMixers.add(info);
cmbOutputDevice.addItem(info.getName());
continue;
}
Mixer mixer = AudioSystem.getMixer(info);
// Check if it supports SourceDataLine (playback) or TargetDataLine (recording)
Line.Info[] playInfos = mixer.getSourceLineInfo();
Line.Info[] recInfos = mixer.getTargetLineInfo();
// Exclude devices that report supporting both (often problematic aggregators)
if (playInfos.length > 0 && recInfos.length > 0) {
continue;
}
if (playInfos.length > 0 || recInfos.length > 0) {
outMixers.add(info);
String label = "";
if (playInfos.length > 0) {
label = "[OUT] ";
} else if (recInfos.length > 0) {
label = "[IN] ";
}
cmbOutputDevice.addItem(label + info.getName());
}
}
outputMixers = outMixers.toArray(new Mixer.Info[0]);
}
/**
* Adjusts the current playback volume by a specific decibel increment.
*
* @param delta the amount of decibels to add or subtract from the current level
*/
private void adjustVolume(float delta) {
currentVolume += delta;
applyVolume();
}
/**
* Applies the tracked volume level securely to the active hardware audio line,
* ensuring it clamps properly to the minimum and maximum capabilities of the
* device.
*/
private void applyVolume() {
if (activeDataLine != null && activeDataLine.isOpen()) {
if (activeDataLine.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
FloatControl gainControl = (FloatControl) activeDataLine.getControl(FloatControl.Type.MASTER_GAIN);
currentVolume = Math.max(gainControl.getMinimum(), Math.min(gainControl.getMaximum(), currentVolume));
gainControl.setValue(currentVolume);
}
}
}
/**
* Generates a 1-minute 440Hz test sine wave and instantly routes it to the
* PCM-F1 encoder,
* bypassing the need for a user-provided input WAV file.
*/
private void quickTest() {
File file = new File("test_output_pcmf1.mp4");
encodeSimulatedAudio(file);
}
/**
* Spawns a file selection dialog requesting an input audio file (WAV, FLAC,
* MP3, etc.),
* and automatically directs it to the encoder pipeline to generate a Sony
* PCM-F1 encoded MP4.
*/
private void saveVideo() {
Preferences prefs = Preferences.userNodeForPackage(PCMF1SimulatorApp.class);
String lastDir = prefs.get("lastOpenedDir", null);
JFileChooser openChooser = new JFileChooser(lastDir);
openChooser.setFileFilter(
new FileNameExtensionFilter("Audio Files (*.wav, *.flac, *.mp3, *.m4a)", "wav", "flac", "mp3", "m4a"));
openChooser.setDialogTitle("Select Input Audio File For Encoding");
if (openChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
return;
File audioFile = openChooser.getSelectedFile();
prefs.put("lastOpenedDir", audioFile.getParent());
String path = audioFile.getAbsolutePath();
int dotIndex = path.lastIndexOf('.');
if (dotIndex > 0) {
path = path.substring(0, dotIndex) + ".mp4";
} else {
path += ".mp4";
}
File outFile = new File(path);
encodeAudioToVideo(audioFile, outFile);
}
/**
* Spawns a background thread to safely parse the headers of a raw 16-bit stereo
* WAV file,
* extracting its samples into memory, handling fallback RIFF parsing if
* necessary, or dynamically shelling out to FFmpeg to natively decode
* FLAC, MP3, or M4A compressed audio files directly into memory, and
* ultimately passing the clean binary array into the video conversion loop.
*
* @param audioFile the source audio file to read
* @param outFile the destination .mp4 file to write the STC-007 video to
*/
private void encodeAudioToVideo(File audioFile, File outFile) {
new Thread(() -> {
try {
isRunning = true;
isPaused = false;
SwingUtilities.invokeLater(() -> btnPause.setText("Pause"));
lblStatus.setText("Status: Reading Audio file...");
byte[] bytes = null;
boolean isBigEndian = false;
boolean isPal = cmbFormat.getSelectedIndex() == 1;
boolean isPcm48 = cmbProtocol.getSelectedIndex() == 1;
final float targetSampleRate = isPcm48 ? 48000.0f : (isPal ? 44100.0f : 44056.0f);
float currentSampleRate = targetSampleRate; // Tracks the actual rate of the loaded bytes
String fileName = audioFile.getName().toLowerCase();
if (fileName.endsWith(".wav")) {
try {
AudioInputStream originalStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat originalFormat = originalStream.getFormat();
currentSampleRate = originalFormat.getSampleRate();
isBigEndian = originalFormat.isBigEndian();
bytes = originalStream.readAllBytes();
originalStream.close();
} catch (Exception e) {
// Fallback to manual RIFF parsing if AudioSystem dislikes some header metadata
// (Extensible, etc)
lblStatus.setText("Status: AudioSystem rejected file, attempting manual WAV parse...");
try (java.io.RandomAccessFile raf = new java.io.RandomAccessFile(audioFile, "r")) {
byte[] header = new byte[12];
raf.readFully(header);
if (header[0] != 'R' || header[1] != 'I' || header[2] != 'F' || header[3] != 'F' ||
header[8] != 'W' || header[9] != 'A' || header[10] != 'V' || header[11] != 'E') {
throw new Exception("Fallback Parser: File is not a valid RIFF WAVE format.");
}
while (raf.getFilePointer() < raf.length() - 8) {
byte[] chunkIdBytes = new byte[4];
raf.readFully(chunkIdBytes);
String chunkId = new String(chunkIdBytes);
int chunkSize = Integer.reverseBytes(raf.readInt());
if (chunkSize < 0)
chunkSize = 0;
if (chunkId.equals("fmt ")) {
short audioFormat = Short.reverseBytes(raf.readShort());
short channels = Short.reverseBytes(raf.readShort());
currentSampleRate = (float) Integer.reverseBytes(raf.readInt());
raf.skipBytes(6); // Skip byteRate (4), blockAlign (2)
short bitsPerSample = Short.reverseBytes(raf.readShort());
// 1 = Standard PCM, 65534 (0xFFFE) = WAVE_FORMAT_EXTENSIBLE
if ((audioFormat != 1 && (audioFormat & 0xFFFF) != 65534) || channels != 2
|| bitsPerSample != 16) {
throw new Exception(
"Fallback Parser: Must be uncompressed 16-bit stereo PCM. Got format="
+ (audioFormat & 0xFFFF) + " channels=" + channels + " bits="
+ bitsPerSample);
}
if (chunkSize > 16)
raf.skipBytes(chunkSize - 16);
} else if (chunkId.equals("data")) {
bytes = new byte[chunkSize];
raf.readFully(bytes);
isBigEndian = false; // Standard WAV is little endian PCM
break;
} else {
raf.skipBytes(chunkSize);
}
}
if (bytes == null)
throw new Exception("Fallback Parser: No 'data' audio chunk found in WAV.");
}
}
} else {
// It's a FLAC, MP3, or M4A (or other FFmpeg-supported format)
lblStatus.setText("Status: Native Shelling to FFmpeg for highly-compressed audio decode...");
ProcessBuilder pb = new ProcessBuilder(
"ffmpeg", "-y", "-i", audioFile.getAbsolutePath(),
"-f", "s16le", "-ac", "2", "-ar", String.valueOf((int) targetSampleRate), "-");
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
java.io.InputStream is = p.getInputStream();
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int read;
while ((read = is.read(buf)) != -1) {
baos.write(buf, 0, read);
}
p.waitFor();
if (p.exitValue() != 0) {
throw new Exception("FFmpeg encountered an error decoding the " + fileName + " file.");
}
bytes = baos.toByteArray();
isBigEndian = false; // s16le guarantees Little Endian
}
if (bytes != null && currentSampleRate != targetSampleRate) {
try {
AudioFormat sourceFormat = new AudioFormat(currentSampleRate, 16, 2, true, isBigEndian);
java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(bytes);
AudioInputStream sourceStream = new AudioInputStream(bais, sourceFormat,
bytes.length / sourceFormat.getFrameSize());
AudioFormat targetFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
targetSampleRate,
16,
2,
4,
targetSampleRate,
false);
AudioInputStream resampledStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
bytes = resampledStream.readAllBytes();
currentSampleRate = targetSampleRate;
isBigEndian = false;
} catch (Exception resampleEx) {
resampleEx.printStackTrace();
// If resampling fails, we'll proceed with original bytes but duration will be
// off
}
}
int totalSamples = bytes.length / 2; // shorts
short[] audio = new short[totalSamples];
for (int i = 0; i < totalSamples; i++) {
if (isBigEndian) {
audio[i] = (short) (((bytes[i * 2] & 0xFF) << 8) | (bytes[i * 2 + 1] & 0xFF));
} else {
audio[i] = (short) (((bytes[i * 2 + 1] & 0xFF) << 8) | (bytes[i * 2] & 0xFF));
}
}
double durationSeconds = 0;
if (currentSampleRate > 0 && bytes != null) {
durationSeconds = (bytes.length / 4.0) / currentSampleRate;
}
int hours = (int) (durationSeconds / 3600);
int minutes = (int) ((durationSeconds % 3600) / 60);
int seconds = (int) (durationSeconds % 60);
String playtime = String.format("%02d:%02d:%02d", hours, minutes, seconds);
String audioInfo = String.format("%s - %.2f MB [%s]", audioFile.getName(),
audioFile.length() / (1024.0 * 1024.0), playtime);
lblStatus.setText("Status: Encoding... " + audioInfo);
runEncoderLoop(audio, outFile, audioInfo);
} catch (Exception ex) {
ex.printStackTrace();
lblStatus.setText("Error: " + ex.getMessage());
} finally {
SwingUtilities.invokeLater(() -> {
vuLeft.setValue(0);
vuRight.setValue(0);
});
}
}).start();
}
/**
* Spawns a background thread that calculates and generates 1 minute of a 440Hz
* sine wave,
* routing it directly into the STC-007 video generation pipeline.
*
* @param file the destination .mp4 file to write the simulated audio to
*/
private void encodeSimulatedAudio(File file) {
new Thread(() -> {
try {
isRunning = true;
isPaused = false;
SwingUtilities.invokeLater(() -> btnPause.setText("Pause"));
boolean isPcm48 = cmbProtocol.getSelectedIndex() == 1;
boolean isPal = cmbFormat.getSelectedIndex() == 1;
int sampleRate = isPcm48 ? 48000 : (isPal ? 44100 : 44056);
String labelInfo = "Simulated 1m 440Hz Sine (" + (isPcm48 ? "PCM-48K" : (isPal ? "PAL" : "NTSC")) + ")";
lblStatus.setText("Status: Encoding... " + labelInfo);
// Sony PCM-F1 uses 44.056 kHz for NTSC, 44.1 kHz for PAL (x2 for Stereo
// Left/Right interleaved)
int totalSamples = 60 * sampleRate * 2;
short[] audio = new short[totalSamples];
for (int i = 0; i < audio.length; i++) {
audio[i] = (short) (Math.sin(2 * Math.PI * i * 440 / sampleRate) * 16000);
}
runEncoderLoop(audio, file, labelInfo);
} catch (Exception ex) {
ex.printStackTrace();
lblStatus.setText("Error: " + ex.getMessage());
} finally {
SwingUtilities.invokeLater(() -> {
vuLeft.setValue(0);
vuRight.setValue(0);
});
}
}).start();
}
/**
* Captures audio directly from the selected microphone or line-in device using
* a TargetDataLine,
* converting raw byte streams immediately into short data to continuously feed
* the
* realtime graphical STC-007 display. Audio is not saved to disk.
*/
private void startRealtimeCapture() {
stopCurrentEngineConnections();
activeCaptureThread = new Thread(() -> {
try {
isRunning = true;
isPaused = false;
SwingUtilities.invokeLater(() -> btnPause.setText("Pause"));
boolean isPcm48 = cmbProtocol.getSelectedIndex() == 1;
boolean isPal = cmbFormat.getSelectedIndex() == 1;
int sampleRate = isPcm48 ? 48000 : (isPal ? 44100 : 44056);
lblStatus.setText(
"Status: Realtime Capture (" + (isPcm48 ? "PCM-48K" : (isPal ? "PAL" : "NTSC")) + ")...");
AudioFormat format = new AudioFormat(sampleRate, 16, 2, true, false); // Little-endian
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
boolean isMonoCapture = false;
try {
int selectedMixerIndex = cmbOutputDevice.getSelectedIndex();
Mixer mixer = null;
if (selectedMixerIndex > 0 && selectedMixerIndex < outputMixers.length) {
mixer = AudioSystem.getMixer(outputMixers[selectedMixerIndex]);
}
boolean success = false;
for (int channels : new int[] { 2, 1 }) {
for (int sr : new int[] { sampleRate, 44100, 48000 }) {
try {
format = new AudioFormat(sr, 16, channels, true, false);
info = new DataLine.Info(TargetDataLine.class, format);
if (mixer != null) {
activeTargetLine = (TargetDataLine) mixer.getLine(info);
} else {
activeTargetLine = (TargetDataLine) AudioSystem.getLine(info);
}
activeTargetLine.open(format); // Unrestricted OS buffer size
success = true;
isMonoCapture = (channels == 1);
if (sr != sampleRate || channels != 2) {
System.out.println(
"Hardware accepted fallback: " + sr + "Hz, " + channels + " channel(s)");
}
break;
} catch (Exception eFallback) {
// Line unavailable or format unsupported, try next parameter set
}
}
if (success)
break;
}
if (!success) {
throw new IllegalArgumentException("No supported format found for capture device.");
}
activeTargetLine.start();
} catch (IllegalArgumentException e) {
e.printStackTrace(); // Log diagnostic information to the host terminal
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(this,
"The selected Audio Device does not support capturing audio.\nPlease select a device marked with [IN].",
"Unsupported Input Device", JOptionPane.ERROR_MESSAGE);
lblStatus.setText("Status: Ready");
btnPause.setText("Pause");
});
return; // Terminate thread gracefully
}
// 6 audio short samples (12 bytes) make up exactly 1 STC-007 Horizontal
// Scanline.
// STC-007 has exactly 490 data lines per frame (DATA_LINES_PER_FRAME).
int samplesPerFrame = isPcm48 ? PCM48_SAMPLES_PER_FRAME : (isPal ? 2940 : 2936);
int bytesPerFrame = samplesPerFrame * 2; // 2 bytes per sample
byte[] captureBuffer = new byte[isMonoCapture ? bytesPerFrame / 2 : bytesPerFrame];
// Track 112 previous lines dynamically to satisfy the 16-line Interleave Matrix
short[] interleaveMatrix = new short[(DATA_LINES_PER_FRAME + 112) * 8];
for (int i = 0; i < interleaveMatrix.length; i++)
interleaveMatrix[i] = -1;
long startTime = System.currentTimeMillis();
long totalBytesRecorded = 0;
int frameCount = 0;
while (isRunning) {
while (isPaused && isRunning) {
Thread.sleep(50);
}
if (!isRunning)
break;
// Strictly block and accumulate exactly one frame's worth of data
int bytesRead = 0;
while (bytesRead < captureBuffer.length && isRunning) {
int read = activeTargetLine.read(captureBuffer, bytesRead, captureBuffer.length - bytesRead);
if (read > 0) {
bytesRead += read;
}
}
if (bytesRead == captureBuffer.length) {
totalBytesRecorded += (isMonoCapture ? bytesRead * 2 : bytesRead);
int shortCount = bytesRead / 2;
short[] audioChunk = new short[isMonoCapture ? shortCount * 2 : shortCount];
for (int i = 0; i < shortCount; i++) {
// Little Endian extract
short sample = (short) (((captureBuffer[i * 2 + 1] & 0xFF) << 8)
| (captureBuffer[i * 2] & 0xFF));
if (isMonoCapture) {
audioChunk[i * 2] = sample;
audioChunk[i * 2 + 1] = sample;
} else {
audioChunk[i] = sample;
}
}
runEncoderFrame(audioChunk, interleaveMatrix, frameCount++, isPal, totalBytesRecorded,
startTime);
}
}
} catch (Exception ex) {
ex.printStackTrace();
lblStatus.setText("Error: Capture device failed - " + ex.getMessage());
} finally {
if (activeTargetLine != null) {
activeTargetLine.stop();
activeTargetLine.close();
}
SwingUtilities.invokeLater(() -> {
vuLeft.setValue(0);
vuRight.setValue(0);
lblStatus.setText("Status: Capture Stopped");
});
}
});
activeCaptureThread.start();
}
/**
* Receives a single frame's worth of streaming PCM audio dynamically over time,
* mathematically interleaves it through the sliding 16-line delay matrices,
* draws the exact STC-007 graphical bit representations, and blasts it straight
* to the UI VideoPanel at ~30FPS. Entirely memory resident.
*/
private void runEncoderFrame(short[] audioChunk, short[] interleaveMatrix, int f, boolean isPal,
long totalBytesRecorded, long startTime) {
if (cmbProtocol.getSelectedIndex() == 1) {
runEncoderFramePCM48(audioChunk, f, totalBytesRecorded, startTime);
return;
}
int blocksInChunk = audioChunk.length / 6;
int maxAmpL = 0;
int maxAmpR = 0;
// Shift the interleave matrix down to flush the oldest frame
// We rendered the first 'blocksInChunk' lines of the matrix last frame.
// So bring everything down.
System.arraycopy(interleaveMatrix, blocksInChunk * 8, interleaveMatrix, 0,
interleaveMatrix.length - (blocksInChunk * 8));
// Blank out the tail
for (int i = interleaveMatrix.length - (blocksInChunk * 8); i < interleaveMatrix.length; i++) {
interleaveMatrix[i] = -1;
}
// Fill STC-007 Delay Matrix arrays for THIS frame's new audio payload
for (int n = 0; n < blocksInChunk; n++) {
short l1 = audioChunk[n * 6 + 0], r1 = audioChunk[n * 6 + 1];
short l2 = audioChunk[n * 6 + 2], r2 = audioChunk[n * 6 + 3];
short l3 = audioChunk[n * 6 + 4], r3 = audioChunk[n * 6 + 5];
// Update VU Levels
maxAmpL = Math.max(maxAmpL, Math.max(Math.abs(l1), Math.max(Math.abs(l2), Math.abs(l3))));
maxAmpR = Math.max(maxAmpR, Math.max(Math.abs(r1), Math.max(Math.abs(r2), Math.abs(r3))));
// MSB 14 bits for Words 1-6
short w1 = (short) ((l1 >> 2) & 0x3FFF);
short w2 = (short) ((r1 >> 2) & 0x3FFF);
short w3 = (short) ((l2 >> 2) & 0x3FFF);
short w4 = (short) ((r2 >> 2) & 0x3FFF);
short w5 = (short) ((l3 >> 2) & 0x3FFF);
short w6 = (short) ((r3 >> 2) & 0x3FFF);
// Word 7 (P Parity)
short p = (short) (w1 ^ w2 ^ w3 ^ w4 ^ w5 ^ w6);
// Word 8 (Q Parity repurposed for 16-bit expansion)
short q = (short) (((l1 & 3) << 12) | ((r1 & 3) << 10) | ((l2 & 3) << 8) | ((r2 & 3) << 6)
| ((l3 & 3) << 4) | ((r3 & 3) << 2));
// Distribute to lines with 16-line delay (112 offset max)
int pushIndex = interleaveMatrix.length - (blocksInChunk * 8) - (112 * 8) + (n * 8);
if (pushIndex < 0)
pushIndex = 0; // Guard
interleaveMatrix[pushIndex + 0] = w1;
interleaveMatrix[pushIndex + (16 * 8) + 1] = w2;
interleaveMatrix[pushIndex + (32 * 8) + 2] = w3;
interleaveMatrix[pushIndex + (48 * 8) + 3] = w4;
interleaveMatrix[pushIndex + (64 * 8) + 4] = w5;
interleaveMatrix[pushIndex + (80 * 8) + 5] = w6;
interleaveMatrix[pushIndex + (96 * 8) + 6] = p;
interleaveMatrix[pushIndex + (112 * 8) + 7] = q;
}
// --- Render UI Image ---
// Write the STC-007 black and white bytes directly into the Image's raster
// memory.
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
byte[] pixels = ((java.awt.image.DataBufferByte) bi.getRaster().getDataBuffer()).getData();
int lineIdxFirstField = 0;
int lineIdxSecondField = lineIdxFirstField + DATA_LINES_PER_FIELD;
boolean[] bits = new boolean[137];
for (int field = 0; field < 2; field++) {
int startDataIdx = (field == 0) ? lineIdxFirstField : lineIdxSecondField;
int dataCounter = 0;
for (int fieldY = 0; fieldY < HEIGHT / 2; fieldY++) {
if (fieldY < VBLANK_LINES || fieldY >= VBLANK_LINES + DATA_LINES_PER_FIELD + 1)
continue;
int y = fieldY * 2 + field;
// Clear hoisted row for safety
for (int z = 0; z < bits.length; z++)
bits[z] = false;
// 1. Data Sync Signal (4 bits: 0101) - 2 white strips
for (int i = 0; i < 4; i++) {
bits[i] = (i % 2 != 0);
}
// 2. White Reference Signal (5 bits: 11110) - big white strip on right
for (int i = 132; i < 136; i++)
bits[i] = true;
bits[136] = false;
if (fieldY == VBLANK_LINES) {
// Sony Control Word (Line 1 of active video)
for (int w = 0; w < 7; w++) {
for (int b = 0; b < 14; b++) {
bits[4 + (w * 14) + b] = ((0x3333 >> (13 - b)) & 1) == 1;
}
}
int crc = crc16CCITT(bits, 4, 98);
for (int b = 0; b < 16; b++) {
bits[102 + b] = ((crc >> (15 - b)) & 1) == 1;
}
// Render Control Q-Word (Word 8) after the CRC
for (int b = 0; b < 14; b++) {
bits[118 + b] = ((0x3333 >> (13 - b)) & 1) == 1;
}
} else {
// 3. Audio Data Words
int lineIdx = startDataIdx + dataCounter;
dataCounter++;
boolean hasData = false;
// Render Words 1-6 and Word 7 (Parity)
for (int w = 0; w < 7; w++) {
short word = (lineIdx * 8 + w) < interleaveMatrix.length ? interleaveMatrix[lineIdx * 8 + w]
: -1;
if (word != -1) {
hasData = true;
for (int b = 0; b < 14; b++) {
bits[4 + (w * 14) + b] = ((word >> (13 - b)) & 1) == 1;
}
}
}
if (hasData) {
// 4. CRC-16 over the 98 data bits (Words 1-7)
int crc = crc16CCITT(bits, 4, 98);
for (int b = 0; b < 16; b++) {
bits[102 + b] = ((crc >> (15 - b)) & 1) == 1;
}
}
// Render Word 8 (Q-Word)
short qWord = (lineIdx * 8 + 7) < interleaveMatrix.length ? interleaveMatrix[lineIdx * 8 + 7] : -1;
if (qWord != -1) {
for (int b = 0; b < 14; b++) {
bits[118 + b] = ((qWord >> (13 - b)) & 1) == 1;
}
}
}
// Draw Line natively into the backend byte[] array
int startOffset = y * WIDTH + PIXEL_OFFSET;
for (int b = 0; b < 137; b++) {
byte color = (byte) (bits[b] ? 255 : 0);
int bitOffset = startOffset + (b * BIT_WIDTH);
for (int pw = 0; pw < BIT_WIDTH; pw++) {
pixels[bitOffset + pw] = color;
}
}
}
}
final int pFrame = f;
final int fmMaxL = maxAmpL;
final int fmMaxR = maxAmpR;
final long loopElapsed = System.currentTimeMillis() - startTime;
double currentKbps = (totalBytesRecorded * 8.0 / 1000.0) / (loopElapsed / 1000.0);
if (Double.isNaN(currentKbps) || Double.isInfinite(currentKbps))
currentKbps = 0;
final double safeKbps = currentKbps;
SwingUtilities.invokeLater(() -> {
videoPanel.setImage(bi);
double fps = (double) pFrame / (loopElapsed / 1000.0);
if (Double.isNaN(fps) || Double.isInfinite(fps))
fps = 0.0;
lblStatus.setText(String.format("Status: Realtime Capture [%.1f fps / %.1f kbps]", fps, safeKbps));
vuLeft.setValue(fmMaxL);
vuRight.setValue(fmMaxR);
});
}
private void runEncoderFramePCM48(short[] audioChunk, int f, long totalBytesRecorded, long startTime) {
int maxAmpL = 0, maxAmpR = 0;
int currentFrameId = f % 16;
for (int i = 0; i < audioChunk.length; i += 2) {
maxAmpL = Math.max(maxAmpL, Math.abs(audioChunk[i]));
if (i + 1 < audioChunk.length)
maxAmpR = Math.max(maxAmpR, Math.abs(audioChunk[i + 1]));
}
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
byte[] pixels = ((java.awt.image.DataBufferByte) bi.getRaster().getDataBuffer()).getData();
// Scrolling Metadata Implementation
String scrollSource = "PCM-48K REALTIME CAPTURE | ";
int scrollOffset = (f / 5) % scrollSource.length();
String meta = (scrollSource + scrollSource).substring(scrollOffset, scrollOffset + 16);
for (int y = 0; y < HEIGHT; y++) {
boolean[] bits = new boolean[PCM48_BITS_PER_LINE];
boolean hasPayload = false;
if (y >= PCM48_VBLANK_LINES && y < PCM48_VBLANK_LINES + PCM48_AUDIO_LINES) {
int lineIdx = y - PCM48_VBLANK_LINES;
int lineAudioStart = lineIdx * PCM48_SAMPLES_PER_LINE;
bits[0] = false;
bits[1] = true;
bits[2] = false;
bits[3] = true;
for (int b = 0; b < 4; b++)
bits[4 + b] = ((currentFrameId >> (3 - b)) & 1) == 1;
for (int w = 0; w < 8; w++) {
short val = (lineAudioStart + w < audioChunk.length) ? audioChunk[lineAudioStart + w] : 0;
for (int b = 0; b < 16; b++)
bits[8 + (w * 16) + b] = ((val >> (15 - b)) & 1) == 1;
}
int crc = crc16CCITT(bits, 4, 132);
for (int b = 0; b < 16; b++)
bits[136 + b] = ((crc >> (15 - b)) & 1) == 1;
hasPayload = true;
} else if (y >= 20 && y <= 29) {
bits[0] = false;
bits[1] = true;
bits[2] = false;
bits[3] = true;
for (int c = 0; c < 16; c++) {
char ch = (c < meta.length()) ? meta.charAt(c) : ' ';
for (int b = 0; b < 8; b++)
bits[8 + (c * 8) + b] = ((ch >> (7 - b)) & 1) == 1;
}
int crc = crc16CCITT(bits, 4, 132);
for (int b = 0; b < 16; b++)
bits[136 + b] = ((crc >> (15 - b)) & 1) == 1;
hasPayload = true;
} else if (y >= 450 && y <= 455) {
int barW = (maxAmpL * (PCM48_BITS_PER_LINE * PCM48_BIT_WIDTH)) / 32768;
for (int x = 0; x < barW && (PCM48_PIXEL_OFFSET + x < WIDTH); x++)
pixels[y * WIDTH + PCM48_PIXEL_OFFSET + x] = (byte) 255;
} else if (y >= 460 && y <= 465) {
int barW = (maxAmpR * (PCM48_BITS_PER_LINE * PCM48_BIT_WIDTH)) / 32768;
for (int x = 0; x < barW && (PCM48_PIXEL_OFFSET + x < WIDTH); x++)
pixels[y * WIDTH + PCM48_PIXEL_OFFSET + x] = (byte) 255;
}
if (hasPayload) {
int startOffset = y * WIDTH + PCM48_PIXEL_OFFSET;
for (int b = 0; b < PCM48_BITS_PER_LINE; b++) {
byte color = (byte) (bits[b] ? 255 : 0);
for (int pw = 0; pw < PCM48_BIT_WIDTH; pw++) {
int pIdx = startOffset + (b * PCM48_BIT_WIDTH) + pw;
if (pIdx >= 0 && pIdx < pixels.length)
pixels[pIdx] = color;
}
}
}
}
final int pFrame = f;
final int fmMaxL = maxAmpL;
final int fmMaxR = maxAmpR;
final long loopElapsed = System.currentTimeMillis() - startTime;
double currentKbps = (totalBytesRecorded * 8.0 / 1000.0) / ((loopElapsed + 1) / 1000.0);
if (Double.isNaN(currentKbps) || Double.isInfinite(currentKbps))
currentKbps = 0;
final double safeKbps = currentKbps;
SwingUtilities.invokeLater(() -> {
videoPanel.setImage(bi);
double fps = (double) pFrame / ((loopElapsed + 1) / 1000.0);
if (Double.isNaN(fps) || Double.isInfinite(fps))
fps = 0.0;
lblStatus.setText(String.format("Status: Realtime PCM-48K [%.1f fps / %.1f kbps]", fps, safeKbps));
vuLeft.setValue(fmMaxL);
vuRight.setValue(fmMaxR);
});
}
/**
* Core encoding loop that transforms a raw 16-bit stereo audio sample array
* into a sequence of
* STC-007 compliant video frames, natively writing them to an MP4 sequence.