-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStubCodecMediaEngine.java
More file actions
772 lines (712 loc) · 37.2 KB
/
StubCodecMediaEngine.java
File metadata and controls
772 lines (712 loc) · 37.2 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
package me.tamkungz.codecmedia.internal;
import java.awt.Desktop;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import me.tamkungz.codecmedia.CodecMediaEngine;
import me.tamkungz.codecmedia.CodecMediaException;
import me.tamkungz.codecmedia.internal.audio.mp3.Mp3Codec;
import me.tamkungz.codecmedia.internal.audio.mp3.Mp3Parser;
import me.tamkungz.codecmedia.internal.audio.mp3.Mp3ProbeInfo;
import me.tamkungz.codecmedia.internal.audio.ogg.OggCodec;
import me.tamkungz.codecmedia.internal.audio.ogg.OggParser;
import me.tamkungz.codecmedia.internal.audio.ogg.OggProbeInfo;
import me.tamkungz.codecmedia.internal.audio.wav.WavCodec;
import me.tamkungz.codecmedia.internal.audio.wav.WavParser;
import me.tamkungz.codecmedia.internal.audio.wav.WavProbeInfo;
import me.tamkungz.codecmedia.internal.convert.ConversionHub;
import me.tamkungz.codecmedia.internal.convert.ConversionRequest;
import me.tamkungz.codecmedia.internal.convert.DefaultConversionHub;
import me.tamkungz.codecmedia.internal.image.bmp.BmpParser;
import me.tamkungz.codecmedia.internal.image.bmp.BmpProbeInfo;
import me.tamkungz.codecmedia.internal.image.heif.HeifParser;
import me.tamkungz.codecmedia.internal.image.heif.HeifProbeInfo;
import me.tamkungz.codecmedia.internal.image.jpeg.JpegParser;
import me.tamkungz.codecmedia.internal.image.jpeg.JpegProbeInfo;
import me.tamkungz.codecmedia.internal.image.png.PngParser;
import me.tamkungz.codecmedia.internal.image.png.PngProbeInfo;
import me.tamkungz.codecmedia.internal.image.tiff.TiffParser;
import me.tamkungz.codecmedia.internal.image.tiff.TiffProbeInfo;
import me.tamkungz.codecmedia.internal.image.webp.WebpParser;
import me.tamkungz.codecmedia.internal.image.webp.WebpProbeInfo;
import me.tamkungz.codecmedia.internal.video.mp4.Mp4Codec;
import me.tamkungz.codecmedia.internal.video.mp4.Mp4Parser;
import me.tamkungz.codecmedia.internal.video.mp4.Mp4ProbeInfo;
import me.tamkungz.codecmedia.internal.video.mov.MovCodec;
import me.tamkungz.codecmedia.internal.video.mov.MovParser;
import me.tamkungz.codecmedia.internal.video.mov.MovProbeInfo;
import me.tamkungz.codecmedia.internal.video.webm.WebmCodec;
import me.tamkungz.codecmedia.internal.video.webm.WebmParser;
import me.tamkungz.codecmedia.internal.video.webm.WebmProbeInfo;
import me.tamkungz.codecmedia.model.ConversionResult;
import me.tamkungz.codecmedia.model.ExtractionResult;
import me.tamkungz.codecmedia.model.MediaType;
import me.tamkungz.codecmedia.model.Metadata;
import me.tamkungz.codecmedia.model.PlaybackResult;
import me.tamkungz.codecmedia.model.ProbeResult;
import me.tamkungz.codecmedia.model.StreamInfo;
import me.tamkungz.codecmedia.model.StreamKind;
import me.tamkungz.codecmedia.model.ValidationResult;
import me.tamkungz.codecmedia.options.AudioExtractOptions;
import me.tamkungz.codecmedia.options.ConversionOptions;
import me.tamkungz.codecmedia.options.PlaybackOptions;
import me.tamkungz.codecmedia.options.ValidationOptions;
/**
* Temporary stub implementation to bootstrap API integration.
*/
public final class StubCodecMediaEngine implements CodecMediaEngine {
private static final long STRICT_VALIDATION_MAX_BYTES = 32L * 1024L * 1024L;
private final ConversionHub conversionHub = new DefaultConversionHub();
@Override
public ProbeResult get(Path input) throws CodecMediaException {
return probe(input);
}
@Override
public ProbeResult probe(Path input) throws CodecMediaException {
ensureExists(input);
String extension = extractExtension(input);
try {
long size = Files.size(input);
byte[] bytes = Files.readAllBytes(input);
if ("mp3".equals(extension) || isLikelyMp3(bytes)) {
if (bytes.length >= 4) {
try {
Mp3ProbeInfo info = Mp3Codec.decode(bytes, input);
return new ProbeResult(
input,
"audio/mpeg",
"mp3",
MediaType.AUDIO,
info.durationMillis(),
List.of(new StreamInfo(0, StreamKind.AUDIO, info.codec(), info.bitrateKbps(), info.sampleRate(), info.channels(), null, null, null)),
Map.of(
"sizeBytes", String.valueOf(size),
"bitrateMode", info.bitrateMode().name()
)
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for partial/empty temporary files.
}
}
return new ProbeResult(input, "audio/mpeg", "mp3", MediaType.AUDIO, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("ogg".equals(extension) || isLikelyOgg(bytes)) {
OggProbeInfo info = OggCodec.decode(bytes, input);
return new ProbeResult(
input,
"audio/ogg",
"ogg",
MediaType.AUDIO,
info.durationMillis(),
List.of(new StreamInfo(0, StreamKind.AUDIO, info.codec(), info.bitrateKbps(), info.sampleRate(), info.channels(), null, null, null)),
Map.of(
"sizeBytes", String.valueOf(size),
"bitrateMode", info.bitrateMode().name()
)
);
}
if ("wav".equals(extension) || WavParser.isLikelyWav(bytes)) {
try {
WavProbeInfo info = WavCodec.decode(bytes, input);
return new ProbeResult(
input,
"audio/wav",
"wav",
MediaType.AUDIO,
info.durationMillis(),
List.of(new StreamInfo(0, StreamKind.AUDIO, "pcm", info.bitrateKbps(), info.sampleRate(), info.channels(), null, null, null)),
Map.of("sizeBytes", String.valueOf(size), "bitrateMode", info.bitrateMode().name())
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "audio/wav", "wav", MediaType.AUDIO, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("png".equals(extension) || PngParser.isLikelyPng(bytes)) {
try {
PngProbeInfo info = PngParser.parse(bytes);
return new ProbeResult(
input,
"image/png",
"png",
MediaType.IMAGE,
null,
List.of(new StreamInfo(0, StreamKind.VIDEO, "png", null, null, null, info.width(), info.height(), null)),
Map.of(
"sizeBytes", String.valueOf(size),
"bitDepth", String.valueOf(info.bitDepth()),
"colorType", String.valueOf(info.colorType())
)
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "image/png", "png", MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("jpg".equals(extension) || "jpeg".equals(extension) || JpegParser.isLikelyJpeg(bytes)) {
String outputExt = "jpeg".equals(extension) ? "jpeg" : "jpg";
try {
JpegProbeInfo info = JpegParser.parse(bytes);
return new ProbeResult(
input,
"image/jpeg",
outputExt,
MediaType.IMAGE,
null,
List.of(new StreamInfo(0, StreamKind.VIDEO, "jpeg", null, null, null, info.width(), info.height(), null)),
Map.of(
"sizeBytes", String.valueOf(size),
"bitsPerSample", String.valueOf(info.bitsPerSample()),
"channels", String.valueOf(info.channels())
)
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "image/jpeg", outputExt, MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("webp".equals(extension) || WebpParser.isLikelyWebp(bytes)) {
try {
WebpProbeInfo info = WebpParser.parse(bytes);
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
if (info.bitDepth() != null) {
tags.put("bitDepth", String.valueOf(info.bitDepth()));
}
return new ProbeResult(
input,
"image/webp",
"webp",
MediaType.IMAGE,
null,
List.of(new StreamInfo(0, StreamKind.VIDEO, "webp", null, null, null, info.width(), info.height(), null)),
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "image/webp", "webp", MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("bmp".equals(extension) || BmpParser.isLikelyBmp(bytes)) {
try {
BmpProbeInfo info = BmpParser.parse(bytes);
return new ProbeResult(
input,
"image/bmp",
"bmp",
MediaType.IMAGE,
null,
List.of(new StreamInfo(0, StreamKind.VIDEO, "bmp", null, null, null, info.width(), info.height(), null)),
Map.of(
"sizeBytes", String.valueOf(size),
"bitsPerPixel", String.valueOf(info.bitsPerPixel())
)
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "image/bmp", "bmp", MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("tif".equals(extension) || "tiff".equals(extension) || TiffParser.isLikelyTiff(bytes)) {
String outputExt = "tiff".equals(extension) ? "tiff" : "tif";
try {
TiffProbeInfo info = TiffParser.parse(bytes);
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
if (info.bitDepth() != null) {
tags.put("bitDepth", String.valueOf(info.bitDepth()));
}
return new ProbeResult(
input,
"image/tiff",
outputExt,
MediaType.IMAGE,
null,
List.of(new StreamInfo(0, StreamKind.VIDEO, "tiff", null, null, null, info.width(), info.height(), null)),
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "image/tiff", outputExt, MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("heic".equals(extension) || "heif".equals(extension) || "avif".equals(extension) || HeifParser.isLikelyHeif(bytes)) {
String outputExt = "heif".equals(extension) ? "heif" : "heic";
if ("avif".equals(extension)) {
outputExt = "avif";
}
String mimeType = "image/" + outputExt;
try {
HeifProbeInfo info = HeifParser.parse(bytes);
String majorBrand = info.majorBrand();
if ("avif".equals(majorBrand) || "avis".equals(majorBrand)) {
outputExt = "avif";
mimeType = "image/avif";
}
java.util.List<StreamInfo> streams = List.of();
if (info.width() != null && info.height() != null) {
streams = List.of(new StreamInfo(0, StreamKind.VIDEO, outputExt, null, null, null, info.width(), info.height(), null));
}
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
tags.put("majorBrand", majorBrand);
if (info.bitDepth() != null) {
tags.put("bitDepth", String.valueOf(info.bitDepth()));
}
return new ProbeResult(
input,
mimeType,
outputExt,
MediaType.IMAGE,
null,
streams,
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, mimeType, outputExt, MediaType.IMAGE, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("mov".equals(extension) || MovParser.isLikelyMov(bytes)) {
try {
MovProbeInfo info = MovCodec.decode(bytes, input);
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
if (info.majorBrand() != null && !info.majorBrand().isBlank()) {
tags.put("majorBrand", info.majorBrand());
}
if (info.videoCodec() != null && !info.videoCodec().isBlank()) {
tags.put("videoCodec", info.videoCodec());
}
if (info.audioCodec() != null && !info.audioCodec().isBlank()) {
tags.put("audioCodec", info.audioCodec());
}
java.util.ArrayList<StreamInfo> streams = new java.util.ArrayList<>();
if (info.width() != null && info.height() != null && info.width() > 0 && info.height() > 0) {
streams.add(new StreamInfo(0, StreamKind.VIDEO, info.videoCodec() != null ? info.videoCodec() : "unknown", null, null, null, info.width(), info.height(), info.frameRate()));
}
if (info.sampleRate() != null && info.channels() != null && info.sampleRate() > 0 && info.channels() > 0) {
streams.add(new StreamInfo(
streams.size(),
StreamKind.AUDIO,
info.audioCodec() != null ? info.audioCodec() : "unknown",
null,
info.sampleRate(),
info.channels(),
null,
null,
null
));
}
return new ProbeResult(
input,
"video/quicktime",
"mov",
MediaType.VIDEO,
info.durationMillis(),
List.copyOf(streams),
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "video/quicktime", "mov", MediaType.VIDEO, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("mp4".equals(extension) || "m4a".equals(extension) || Mp4Parser.isLikelyMp4(bytes)) {
String outputExt = "m4a".equals(extension) ? "m4a" : "mp4";
String mimeType = "m4a".equals(outputExt) ? "audio/mp4" : "video/mp4";
MediaType mediaType = "m4a".equals(outputExt) ? MediaType.AUDIO : MediaType.VIDEO;
try {
Mp4ProbeInfo info = Mp4Codec.decode(bytes, input);
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
if (info.majorBrand() != null && !info.majorBrand().isBlank()) {
tags.put("majorBrand", info.majorBrand());
}
List<StreamInfo> streams;
if (mediaType == MediaType.VIDEO && info.width() != null && info.height() != null && info.width() > 0 && info.height() > 0) {
streams = List.of(new StreamInfo(0, StreamKind.VIDEO, "h264/unknown", null, null, null, info.width(), info.height(), null));
} else {
streams = List.of();
}
return new ProbeResult(
input,
mimeType,
outputExt,
mediaType,
info.durationMillis(),
streams,
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, mimeType, outputExt, mediaType, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
if ("webm".equals(extension) || WebmParser.isLikelyWebm(bytes)) {
try {
WebmProbeInfo info = WebmCodec.decode(bytes, input);
java.util.LinkedHashMap<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("sizeBytes", String.valueOf(size));
if (info.videoCodec() != null && !info.videoCodec().isBlank()) {
tags.put("videoCodec", info.videoCodec());
}
if (info.audioCodec() != null && !info.audioCodec().isBlank()) {
tags.put("audioCodec", info.audioCodec());
}
java.util.ArrayList<StreamInfo> streams = new java.util.ArrayList<>();
if (info.width() != null && info.height() != null && info.width() > 0 && info.height() > 0) {
streams.add(new StreamInfo(0, StreamKind.VIDEO, info.videoCodec() != null ? info.videoCodec() : "unknown", null, null, null, info.width(), info.height(), info.frameRate()));
}
if (info.sampleRate() != null && info.channels() != null && info.sampleRate() > 0 && info.channels() > 0) {
streams.add(new StreamInfo(
streams.size(),
StreamKind.AUDIO,
info.audioCodec() != null ? info.audioCodec() : "unknown",
null,
info.sampleRate(),
info.channels(),
null,
null,
null
));
}
return new ProbeResult(
input,
"video/webm",
"webm",
MediaType.VIDEO,
info.durationMillis(),
List.copyOf(streams),
tags
);
} catch (CodecMediaException ignored) {
// Fall back to extension-only probe for malformed/partial files.
}
return new ProbeResult(input, "video/webm", "webm", MediaType.VIDEO, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
}
String mimeType = switch (extension) {
case "mp4" -> "video/mp4";
case "mov" -> "video/quicktime";
case "webm" -> "video/webm";
case "m4a" -> "audio/mp4";
case "mp3" -> "audio/mpeg";
case "ogg" -> "audio/ogg";
case "wav" -> "audio/wav";
case "png" -> "image/png";
case "jpg", "jpeg" -> "image/jpeg";
case "webp" -> "image/webp";
case "bmp" -> "image/bmp";
case "tif", "tiff" -> "image/tiff";
case "heic" -> "image/heic";
case "heif" -> "image/heif";
case "avif" -> "image/avif";
default -> "application/octet-stream";
};
MediaType mediaType = switch (extension) {
case "mp4", "mov", "webm" -> MediaType.VIDEO;
case "m4a", "mp3", "ogg", "wav" -> MediaType.AUDIO;
case "png", "jpg", "jpeg", "webp", "bmp", "tif", "tiff", "heic", "heif", "avif" -> MediaType.IMAGE;
default -> MediaType.UNKNOWN;
};
return new ProbeResult(input, mimeType, extension, mediaType, null, List.of(), Map.of("sizeBytes", String.valueOf(size)));
} catch (IOException e) {
throw new CodecMediaException("Failed to probe file: " + input, e);
}
}
@Override
public Metadata readMetadata(Path input) throws CodecMediaException {
ensureExists(input);
ProbeResult probe = probe(input);
Map<String, String> entries = new LinkedHashMap<>();
entries.put("mimeType", probe.mimeType());
entries.put("extension", probe.extension());
entries.put("mediaType", probe.mediaType().name());
Path sidecar = metadataSidecarPath(input);
if (Files.exists(sidecar)) {
Properties properties = new Properties();
try (InputStream in = Files.newInputStream(sidecar)) {
properties.load(in);
} catch (IOException e) {
throw new CodecMediaException("Failed to read metadata sidecar: " + sidecar, e);
}
for (String key : properties.stringPropertyNames()) {
entries.putIfAbsent(key, properties.getProperty(key));
}
}
return new Metadata(entries);
}
@Override
public void writeMetadata(Path input, Metadata metadata) throws CodecMediaException {
ensureExists(input);
if (metadata == null || metadata.entries() == null) {
throw new CodecMediaException("Metadata is required");
}
for (Map.Entry<String, String> entry : metadata.entries().entrySet()) {
if (entry.getKey() == null || entry.getKey().isBlank()) {
throw new CodecMediaException("Metadata key must not be null/blank");
}
if (entry.getValue() == null) {
throw new CodecMediaException("Metadata value must not be null for key: " + entry.getKey());
}
}
Path sidecar = metadataSidecarPath(input);
Properties properties = new Properties();
Map<String, String> sorted = new TreeMap<>(metadata.entries());
for (Map.Entry<String, String> entry : sorted.entrySet()) {
properties.setProperty(entry.getKey(), entry.getValue());
}
try (OutputStream out = Files.newOutputStream(sidecar)) {
properties.store(out, "CodecMedia metadata sidecar");
} catch (IOException e) {
throw new CodecMediaException("Failed to write metadata sidecar: " + sidecar, e);
}
}
@Override
public ExtractionResult extractAudio(Path input, Path outputDir, AudioExtractOptions options) throws CodecMediaException {
ensureExists(input);
if (outputDir == null) {
throw new CodecMediaException("Output directory is required");
}
ProbeResult probe = probe(input);
AudioExtractOptions effective = options != null
? options
: AudioExtractOptions.defaults(normalizeExtension(probe.extension()));
if (effective.targetFormat() == null || effective.targetFormat().isBlank()) {
throw new CodecMediaException("AudioExtractOptions.targetFormat is required");
}
if (probe.mediaType() != MediaType.AUDIO) {
throw new CodecMediaException("Input is not an audio file: " + input);
}
String sourceExtension = normalizeExtension(probe.extension());
String requestedExtension = normalizeExtension(effective.targetFormat());
if (!requestedExtension.equals(sourceExtension)) {
throw new CodecMediaException(
"Stub extractAudio does not transcode. Requested format '" + requestedExtension
+ "' must match source format '" + sourceExtension + "'"
);
}
try {
Files.createDirectories(outputDir);
String baseName = baseName(input.getFileName().toString());
String extension = sourceExtension;
Path outputFile = outputDir.resolve(baseName + "_audio." + extension);
Files.copy(input, outputFile, StandardCopyOption.REPLACE_EXISTING);
return new ExtractionResult(outputFile, extension);
} catch (IOException e) {
throw new CodecMediaException("Failed to extract audio: " + input, e);
}
}
@Override
public ConversionResult convert(Path input, Path output, ConversionOptions options) throws CodecMediaException {
ensureExists(input);
if (output == null) {
throw new CodecMediaException("Output file is required");
}
String sourceExtension = normalizeExtension(extractExtension(input));
String inferredTargetFormat = extractExtension(output);
ConversionOptions effective = options != null ? options : ConversionOptions.defaults(inferredTargetFormat);
if (effective.targetFormat() == null || effective.targetFormat().isBlank()) {
throw new CodecMediaException("ConversionOptions.targetFormat is required");
}
String requestedExtension = normalizeExtension(effective.targetFormat());
ProbeResult sourceProbe = probe(input);
me.tamkungz.codecmedia.model.MediaType targetMediaType = mediaTypeByExtension(requestedExtension);
ConversionRequest request = new ConversionRequest(
input,
output,
sourceExtension,
requestedExtension,
sourceProbe.mediaType(),
targetMediaType,
effective
);
return conversionHub.convert(request);
}
@Override
public PlaybackResult play(Path input, PlaybackOptions options) throws CodecMediaException {
ensureExists(input);
ProbeResult probe = probe(input);
PlaybackOptions effective = options != null ? options : PlaybackOptions.defaults();
if (probe.mediaType() == MediaType.UNKNOWN) {
throw new CodecMediaException("Playback is not supported for unknown media type: " + input);
}
if (effective.dryRun()) {
return new PlaybackResult(true, "dry-run", probe.mediaType(), "Playback simulation successful");
}
if (effective.allowExternalApp() && Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(input.toFile());
return new PlaybackResult(true, "desktop-open", probe.mediaType(), "Opened with system default application");
} catch (IOException | RuntimeException e) {
throw new CodecMediaException("Failed to open media with system player/viewer: " + input, e);
}
}
throw new CodecMediaException("No playback backend available. Try dryRun=true or allowExternalApp=true");
}
@Override
public ValidationResult validate(Path input, ValidationOptions options) {
ValidationOptions effective = options != null ? options : ValidationOptions.defaults();
boolean exists = Files.exists(input);
if (!exists) {
return new ValidationResult(false, List.of(), List.of("File does not exist: " + input));
}
try {
long size = Files.size(input);
if (effective.maxBytes() > 0 && size > effective.maxBytes()) {
return new ValidationResult(
false,
List.of(),
List.of("File exceeds maxBytes: " + size + " > " + effective.maxBytes())
);
}
if (effective.strict()) {
String extension = extractExtension(input);
if (size > STRICT_VALIDATION_MAX_BYTES) {
return new ValidationResult(
false,
List.of(),
List.of("Strict validation is limited to files <= " + STRICT_VALIDATION_MAX_BYTES + " bytes")
);
}
byte[] bytes = Files.readAllBytes(input);
if ("mp3".equals(extension)) {
try {
Mp3Parser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for mp3: " + e.getMessage()));
}
} else if ("ogg".equals(extension)) {
try {
OggParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for ogg: " + e.getMessage()));
}
} else if ("wav".equals(extension)) {
try {
WavParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for wav: " + e.getMessage()));
}
} else if ("png".equals(extension)) {
try {
PngParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for png: " + e.getMessage()));
}
} else if ("jpg".equals(extension) || "jpeg".equals(extension)) {
try {
JpegParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for jpg/jpeg: " + e.getMessage()));
}
} else if ("mov".equals(extension)) {
try {
MovParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for mov: " + e.getMessage()));
}
} else if ("mp4".equals(extension) || "m4a".equals(extension)) {
try {
Mp4Parser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for " + extension + ": " + e.getMessage()));
}
} else if ("webm".equals(extension)) {
try {
WebmParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for webm: " + e.getMessage()));
}
} else if ("webp".equals(extension)) {
try {
WebpParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for webp: " + e.getMessage()));
}
} else if ("bmp".equals(extension)) {
try {
BmpParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for bmp: " + e.getMessage()));
}
} else if ("tif".equals(extension) || "tiff".equals(extension)) {
try {
TiffParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for tif/tiff: " + e.getMessage()));
}
} else if ("heic".equals(extension) || "heif".equals(extension) || "avif".equals(extension)) {
try {
HeifParser.parse(bytes);
} catch (CodecMediaException e) {
return new ValidationResult(false, List.of(), List.of("Strict validation failed for heic/heif/avif: " + e.getMessage()));
}
}
}
return new ValidationResult(true, List.of(), List.of());
} catch (IOException e) {
return new ValidationResult(false, List.of(), List.of("Failed to validate file: " + e.getMessage()));
}
}
private static void ensureExists(Path input) throws CodecMediaException {
if (!Files.exists(input)) {
throw new CodecMediaException("File does not exist: " + input);
}
}
private static String extractExtension(Path input) {
String name = input.getFileName().toString();
int dotIndex = name.lastIndexOf('.');
if (dotIndex < 0 || dotIndex == name.length() - 1) {
return "";
}
return name.substring(dotIndex + 1).toLowerCase(Locale.ROOT);
}
private static boolean isLikelyOgg(byte[] bytes) {
return bytes.length >= 4
&& bytes[0] == 'O'
&& bytes[1] == 'g'
&& bytes[2] == 'g'
&& bytes[3] == 'S';
}
private static boolean isLikelyMp3(byte[] bytes) {
if (bytes.length < 3) {
return false;
}
if (bytes[0] == 'I' && bytes[1] == 'D' && bytes[2] == '3') {
return true;
}
if (bytes.length < 2) {
return false;
}
return (bytes[0] & (byte) 0xFF) == (byte) 0xFF && (bytes[1] & (byte) 0xE0) == (byte) 0xE0;
}
private static Path metadataSidecarPath(Path input) {
return input.resolveSibling(input.getFileName() + ".codecmedia.properties");
}
private static String normalizeExtension(String format) {
String value = format.trim().toLowerCase(Locale.ROOT);
return value.startsWith(".") ? value.substring(1) : value;
}
private static String baseName(String fileName) {
int dot = fileName.lastIndexOf('.');
return dot > 0 ? fileName.substring(0, dot) : fileName;
}
private static MediaType mediaTypeByExtension(String extension) {
return switch (normalizeExtension(extension)) {
case "mp3", "ogg", "wav", "pcm", "m4a", "aac", "flac" -> MediaType.AUDIO;
case "mp4", "mkv", "mov", "avi", "webm" -> MediaType.VIDEO;
case "png", "jpg", "jpeg", "gif", "bmp", "webp", "tif", "tiff", "heic", "heif", "avif" -> MediaType.IMAGE;
default -> MediaType.UNKNOWN;
};
}
}