mediaway-encoder 0.1.8

Hardware-accelerated video/audio encoding (OS-native backends)
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
//! WebCodecs encode backend — wasm32 browser implementation.

#![forbid(unsafe_code)]

use std::cell::RefCell;
use std::rc::Rc;

use bytes::Bytes;
use iso_bmff::{Codec, Demuxer, Error, Muxer, Rational, Sample, Track};
use js_sys::Float32Array;
use js_sys::Uint8Array;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    AudioData, AudioDataInit, AudioEncoder, AudioEncoderConfig as WebAudioEncoderConfig,
    AudioEncoderInit, AudioSampleFormat, EncodedAudioChunk, EncodedVideoChunk,
    EncodedVideoChunkType, Gpu, GpuCanvasAlphaMode, GpuCanvasConfiguration, GpuCanvasContext,
    GpuColorDict, GpuDevice, GpuLoadOp, GpuRenderPassColorAttachment, GpuRenderPassDescriptor,
    GpuStoreOp, GpuTexture, OffscreenCanvas, VideoEncoder,
    VideoEncoderConfig as WebVideoEncoderConfig, VideoEncoderInit, VideoFrame,
    VideoFrameBufferInit, VideoFrameInit, VideoPixelFormat,
};

use crate::web::chunks::{EncodedAudioChunks, EncodedVideoChunks};
use crate::web::config::{WebAudioOpenConfig, WebVideoOpenConfig};
use crate::web::timestamp::timestamp_us_to_i32;

/// Returns whether WebCodecs H.264 + AAC configs are supported in this browser.
#[cfg(all(feature = "audio", feature = "video"))]
#[wasm_bindgen]
pub async fn is_webcodecs_av_supported() -> bool {
    video_supported().await && audio_supported().await
}

#[cfg(feature = "video")]
async fn video_codec_supported(codec: &str) -> bool {
    let cfg = WebVideoEncoderConfig::new(codec, 64, 64);
    cfg.set_bitrate(500_000);
    let promise = VideoEncoder::is_config_supported(&cfg);
    // `is_config_supported` resolves to a `VideoEncoderSupport` dictionary (`{supported,
    // config}`), not a boolean — `JsFuture`'s typed `Promise<T>` support (js-sys 0.3.103+)
    // already yields that dictionary directly, so `get_supported()` reads the field with no
    // extra cast. (An earlier `.as_bool()` on this same value always returned `None`/`false`
    // regardless of real browser support — a latent bug this fixes.)
    let reported = JsFuture::from(promise)
        .await
        .ok()
        .and_then(|v| v.get_supported())
        .unwrap_or(false);
    if !reported {
        return false;
    }
    // `isConfigSupported` can still report `true` for a codec whose actual encoder isn't
    // wired up in this browser build — observed on this Chromium: `avc1.42E01E` reports
    // supported, then a real `configure()`/`encode()`/`flush()` throws `OperationError:
    // Encoding error` (no bundled H.264 software encoder, presumably). Confirm with one real
    // tiny encode rather than trusting the capability query alone.
    let Ok(frame) = black_nv12_frame(64, 64) else {
        return false;
    };
    let ok = encode_frame_via(&frame, codec, 64, 64, 500_000)
        .await
        .is_ok();
    frame.close();
    ok
}

#[cfg(feature = "video")]
async fn video_supported() -> bool {
    video_codec_supported("avc1.42E01E").await
}

/// Probe WebCodecs support for a video codec string (`avc1…`, `hev1…`, `av01…`, `vp09…`).
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn is_webcodecs_video_codec_supported(codec: String) -> bool {
    video_codec_supported(&codec).await
}

#[cfg(feature = "audio")]
async fn audio_codec_supported(codec: &str, channels: u32, sample_rate: u32) -> bool {
    // `AudioEncoderConfig::new`'s web-sys signature is `(codec, number_of_channels,
    // sample_rate)` — NOT `(codec, sample_rate, number_of_channels)`. Swapped args here used
    // to build a nonsensical config (48,000 channels at 2 Hz), which `isConfigSupported`
    // correctly rejected — the real, deterministic reason `is_webcodecs_av_supported` always
    // reported unsupported, not the `VideoEncoder`/`AudioEncoder` `.close()` resource-hygiene
    // issue fixed alongside this.
    let cfg = WebAudioEncoderConfig::new(codec, channels, sample_rate);
    let promise = AudioEncoder::is_config_supported(&cfg);
    // Same `{supported, config}` dictionary shape as `video_codec_supported` — see its
    // comment above.
    JsFuture::from(promise)
        .await
        .ok()
        .and_then(|v| v.get_supported())
        .unwrap_or(false)
}

#[cfg(feature = "audio")]
async fn audio_supported() -> bool {
    audio_codec_supported("mp4a.40.2", 2, 48_000).await
}

/// Probe `WebCodecs` support for an audio codec string (`mp4a.40.2`, `opus`, ...) at a given
/// channel count / sample rate.
#[cfg(feature = "audio")]
#[wasm_bindgen]
pub async fn is_webcodecs_audio_codec_supported(
    codec: String,
    channels: u32,
    sample_rate: u32,
) -> bool {
    audio_codec_supported(&codec, channels, sample_rate).await
}

/// Encode one black NV12 frame + short silence via WebCodecs, mux to fMP4, return bytes.
#[cfg(all(feature = "audio", feature = "video"))]
#[wasm_bindgen]
pub async fn webcodecs_av_fmp4_smoke() -> Result<Vec<u8>, JsValue> {
    if !is_webcodecs_av_supported().await {
        return Err(JsValue::from_str("WebCodecs H.264/AAC not supported"));
    }
    let vchunk = encode_one_h264_frame().await?;
    let achunk = encode_one_aac_buffer().await?;
    mux_av_chunks(&vchunk, &achunk)
}

/// Probe whether this browser can source a WebCodecs `VideoFrame` from a WebGPU-backed
/// canvas for `codec`: WebCodecs support for that codec string, plus `navigator.gpu` and a
/// grantable adapter/device.
#[cfg(feature = "video")]
async fn webgpu_video_codec_supported(codec: &str) -> bool {
    video_codec_supported(codec).await && request_gpu_device().await.is_ok()
}

/// H.264 convenience wrapper over [`is_webgpu_video_codec_supported`].
///
/// Kept additive (rather than replaced) to preserve this existing zero-arg entry point's
/// callers, mirroring how [`encode_video_frames`] was added alongside the pre-existing fixed
/// H.264 CPU path instead of replacing it. See
/// `crates/mediaway-encoder/adr/web/0001-webgpu-multi-codec-video-encode.md` Open Question #3.
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn is_webgpu_video_frame_supported() -> bool {
    webgpu_video_codec_supported("avc1.42E01E").await
}

/// Probe `WebCodecs` + `WebGPU` support for a video codec string sourced from a
/// WebGPU-backed canvas.
///
/// Accepts `avc1…`, `hev1…`/`hvc1…`, `av01…`, `vp09…`. Generalizes
/// [`is_webgpu_video_frame_supported`] to arbitrary codecs, mirroring
/// [`is_webcodecs_video_codec_supported`]'s relationship to the CPU path's `video_supported`.
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn is_webgpu_video_codec_supported(codec: String) -> bool {
    webgpu_video_codec_supported(&codec).await
}

/// Encode one WebGPU-resident frame via `WebCodecs` for `codec`, mux to fMP4, return bytes.
#[cfg(feature = "video")]
async fn gpu_video_fmp4_smoke_for(codec: &str) -> Result<Vec<u8>, JsValue> {
    if !webgpu_video_codec_supported(codec).await {
        return Err(JsValue::from_str(
            "WebCodecs codec or WebGPU device not supported",
        ));
    }
    let vchunk = encode_video_frame_from_webgpu_canvas_impl(codec, 64, 64, 500_000).await?;
    mux_video_chunk(codec, &vchunk)
}

/// Encode one WebGPU-resident frame via WebCodecs, mux to fMP4, return bytes. Video-only
/// companion to [`webcodecs_av_fmp4_smoke`] exercising the Stage 2 (Web) roadmap item
/// "`GPUTexture` → encode Zero-Copy" — see [`webgpu_canvas_frame`] for the honest cost
/// contract (GPU-resident, no CPU readback in the Mediaway path; not an unconditional
/// Zero-Copy guarantee, since a raw `GPUTexture` cannot be passed to `VideoFrame` directly).
///
/// H.264 convenience wrapper over [`webcodecs_gpu_video_fmp4_smoke_with_codec`] — kept
/// additive for the same reason as [`is_webgpu_video_frame_supported`].
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn webcodecs_gpu_video_fmp4_smoke() -> Result<Vec<u8>, JsValue> {
    gpu_video_fmp4_smoke_for("avc1.42E01E").await
}

/// Generalizes [`webcodecs_gpu_video_fmp4_smoke`] to an arbitrary `WebCodecs` video `codec`
/// string (`avc1…`, `hev1…`/`hvc1…`, `av01…`, `vp09…`).
///
/// # HEVC framing — unverified
///
/// See [`mux_video_chunk`]'s doc comment: whether this actually produces a correct `hvc1`
/// fMP4 sample for HEVC depends on an open, real-browser-only question (ADR-0001 §2).
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn webcodecs_gpu_video_fmp4_smoke_with_codec(codec: String) -> Result<Vec<u8>, JsValue> {
    gpu_video_fmp4_smoke_for(&codec).await
}

fn iso_err(error: &Error) -> JsValue {
    JsValue::from_str(&error.to_string())
}

fn take_js_err(cell: &RefCell<Option<JsValue>>) -> Result<(), JsValue> {
    cell.borrow_mut().take().map_or(Ok(()), Err)
}

#[cfg(feature = "video")]
async fn encode_one_h264_frame() -> Result<Vec<u8>, JsValue> {
    let frame = black_nv12_frame(64, 64)?;
    encode_frame_via(&frame, "avc1.42E01E", 64, 64, 500_000).await
}

/// Configure a `VideoEncoder` for `codec`/`width`/`height`/`bitrate_bps`, encode one `frame`,
/// flush, and drain the first chunk.
///
/// Shared by the CPU NV12 path ([`encode_one_h264_frame`]), the WebGPU-canvas path
/// ([`encode_video_frame_from_webgpu_canvas_impl`]), and [`video_codec_supported`]'s
/// real-encode probe — all three just need *some* `VideoFrame` encoded through WebCodecs.
/// `width`/`height`/`bitrate_bps` are explicit parameters (rather than the fixed 64×64 /
/// 500 kbps this function used before the GPU-surface path needed caller-chosen sizes) so
/// [`encode_video_frame_from_webgpu_canvas`] can honor its own `width`/`height`/`bitrate_bps`
/// arguments instead of silently ignoring them.
#[cfg(feature = "video")]
async fn encode_frame_via(
    frame: &VideoFrame,
    codec: &str,
    width: u32,
    height: u32,
    bitrate_bps: u32,
) -> Result<Vec<u8>, JsValue> {
    let chunks: Rc<RefCell<Vec<Vec<u8>>>> = Rc::new(RefCell::new(Vec::new()));
    // clone: Rc callback share
    let chunks_cb = chunks.clone();
    let copy_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let copy_err_cb = copy_err.clone();
    let output = Closure::wrap(Box::new(move |chunk: EncodedVideoChunk| {
        let mut buf = vec![0u8; chunk.byte_length() as usize];
        if chunk.copy_to_with_u8_slice(&mut buf).is_err() {
            *copy_err_cb.borrow_mut() =
                Some(JsValue::from_str("EncodedVideoChunk::copy_to failed"));
            return;
        }
        chunks_cb.borrow_mut().push(buf);
    }) as Box<dyn FnMut(EncodedVideoChunk)>);
    let enc_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let enc_err_cb = enc_err.clone();
    let error = Closure::wrap(Box::new(move |e: JsValue| {
        *enc_err_cb.borrow_mut() = Some(e);
    }) as Box<dyn FnMut(JsValue)>);
    let init = VideoEncoderInit::new(
        error.as_ref().unchecked_ref(),
        output.as_ref().unchecked_ref(),
    );
    let enc = VideoEncoder::new(&init).map_err(|_| JsValue::from_str("VideoEncoder::new"))?;
    error.forget();
    output.forget();

    let cfg = WebVideoEncoderConfig::new(codec, width, height);
    cfg.set_width(width);
    cfg.set_height(height);
    cfg.set_bitrate(bitrate_bps);
    cfg.set_framerate(30.0);
    enc.configure(&cfg)
        .map_err(|_| JsValue::from_str("VideoEncoder::configure"))?;

    enc.encode(frame)
        .map_err(|_| JsValue::from_str("VideoEncoder::encode"))?;
    JsFuture::from(enc.flush()).await?;
    // Release the (possibly hardware-backed) encode session promptly: leaving it open let
    // enough concurrent probes in one page exhaust the real encoder's session pool, making
    // `video_codec_supported`'s real-encode check spuriously fail on a later call in the same
    // page — see `docs/ai/wiki/encode/web-gpu-frame.md`.
    let _ = enc.close();
    take_js_err(&enc_err)?;
    take_js_err(&copy_err)?;

    chunks
        .borrow()
        .first()
        .cloned() // clone: take owned chunk buffer out of RefCell
        .ok_or_else(|| JsValue::from_str("no video chunk"))
}

/// Get `navigator.gpu`, erroring out on hosts without a `Window` (e.g. workers — not
/// exercised by this crate today).
#[cfg(feature = "video")]
fn navigator_gpu() -> Result<Gpu, JsValue> {
    Ok(web_sys::window()
        .ok_or_else(|| JsValue::from_str("no window"))?
        .navigator()
        .gpu())
}

/// Request a WebGPU adapter + device. `Err` when WebGPU is absent or no adapter is granted
/// (software-only hosts, permissions policy, disabled flag, …).
#[cfg(feature = "video")]
async fn request_gpu_device() -> Result<GpuDevice, JsValue> {
    let gpu = navigator_gpu()?;
    let adapter = JsFuture::from(gpu.request_adapter())
        .await?
        .into_option()
        .ok_or_else(|| JsValue::from_str("no WebGPU adapter"))?;
    JsFuture::from(adapter.request_device()).await
}

/// Build a `VideoFrame` sourced from a WebGPU-backed `OffscreenCanvas` — no CPU pixel
/// buffer anywhere in this function.
///
/// # Why not a bare `GPUTexture`?
///
/// WebCodecs' `VideoFrame` constructor only accepts a `CanvasImageSource`
/// (`HTMLCanvasElement` / `OffscreenCanvas` / `ImageBitmap` / `HTMLVideoElement` / …,
/// [WebCodecs §5.1](https://w3c.github.io/webcodecs/#dom-videoframe-videoframe)); a raw
/// `GPUTexture` is not a member of that union, and this crate's `web-sys` 0.3.103 bindings
/// (generated from the same IDL) expose no `VideoFrame` constructor that takes one. Verified
/// empirically on Chromium 148 (headless, this machine's Playwright build): `new
/// VideoFrame(texture, { timestamp: 0 })` throws `TypeError: Overload resolution failed`,
/// while `new VideoFrame(canvas, { timestamp: 0 })` succeeds. So the supported GPU-resident
/// path renders/writes into an `OffscreenCanvas` configured with a `"webgpu"`
/// (`GPUCanvasContext`) context, then builds the `VideoFrame` from that **canvas** — this
/// function writes a solid clear color straight into the canvas's current WebGPU texture via
/// a one-attachment render pass (`GPULoadOp::Clear`), never reading pixels back to the CPU.
///
/// # Zero-Copy honesty
///
/// This function and its caller never allocate a CPU pixel `Vec`, never call
/// `VideoFrame::copyTo`/`allocationSize`, and never map/read a `GPUBuffer` — the payload
/// stays GPU-resident on the Mediaway side end to end. Whether the browser's internal
/// `VideoFrame` representation *shares* the canvas's compositor texture or performs its own
/// internal GPU→GPU copy is implementation-defined by the WebCodecs/WebGPU specs and is not
/// observable from JS/wasm (no timing/inspection API exposes it). This path is therefore
/// documented as **GPU-resident, no CPU readback in the Mediaway path** — not as an
/// unconditional Zero-Copy guarantee. See `docs/spec/caveats-and-clarity.md` § Catalog
/// (`webgpu_canvas_frame` row) for the same caveat in the workspace catalog.
#[cfg(feature = "video")]
async fn webgpu_canvas_frame(width: u32, height: u32) -> Result<VideoFrame, JsValue> {
    let gpu = navigator_gpu()?;
    let device = request_gpu_device().await?;
    let format = gpu.get_preferred_canvas_format();

    let canvas = OffscreenCanvas::new(width, height)?;
    let ctx_obj = canvas
        .get_context("webgpu")?
        .ok_or_else(|| JsValue::from_str("no webgpu canvas context"))?;
    let ctx: GpuCanvasContext = ctx_obj
        .dyn_into()
        .map_err(|_| JsValue::from_str("canvas context is not a GPUCanvasContext"))?;

    let canvas_config = GpuCanvasConfiguration::new(&device, format);
    canvas_config.set_alpha_mode(GpuCanvasAlphaMode::Opaque);
    ctx.configure(&canvas_config)?;

    // GPU-resident write: clears the canvas's current texture in place via a render
    // pass. No `Vec<u8>` / CPU staging buffer is allocated anywhere in this function.
    let texture: GpuTexture = ctx.get_current_texture()?;
    let view = texture.create_view()?;
    let attachment = GpuRenderPassColorAttachment::new_with_gpu_texture_view(
        GpuLoadOp::Clear,
        GpuStoreOp::Store,
        &view,
    );
    attachment.set_clear_value_gpu_color_dict(&GpuColorDict::new(1.0, 0.0, 0.0, 1.0));
    let pass_desc = GpuRenderPassDescriptor::new(&[js_sys::JsNullable::wrap(attachment)]);
    let encoder = device.create_command_encoder();
    let pass = encoder.begin_render_pass(&pass_desc)?;
    pass.end();
    device.queue().submit(&[encoder.finish()]);

    let frame_init = VideoFrameInit::new();
    frame_init.set_timestamp(0);
    VideoFrame::new_with_offscreen_canvas_and_video_frame_init(&canvas, &frame_init)
        .map_err(|_| JsValue::from_str("VideoFrame::new from WebGPU canvas failed"))
}

/// Build a WebGPU-canvas `VideoFrame` at `width`x`height` and encode it via `WebCodecs` for
/// `codec`/`bitrate_bps`. Shared implementation behind the codec-parameterized public entry
/// point ([`encode_video_frame_from_webgpu_canvas`]) and the fixed-H.264 smoke path
/// ([`gpu_video_fmp4_smoke_for`]).
#[cfg(feature = "video")]
async fn encode_video_frame_from_webgpu_canvas_impl(
    codec: &str,
    width: u32,
    height: u32,
    bitrate_bps: u32,
) -> Result<Vec<u8>, JsValue> {
    let frame = webgpu_canvas_frame(width, height).await?;
    let result = encode_frame_via(&frame, codec, width, height, bitrate_bps).await;
    frame.close();
    result
}

/// Generalizes the previous fixed-64×64/H.264-only WebGPU-canvas encode path to an arbitrary
/// codec.
///
/// Accepts a `WebCodecs` video `codec` string and caller-chosen `width`/`height`/
/// `bitrate_bps`, per `crates/mediaway-encoder/adr/web/0001-webgpu-multi-codec-video-encode.md`'s
/// Decision. [`webgpu_canvas_frame`] itself needs no codec-specific branching (pixel format,
/// not video codec) — only this call site and [`mux_video_chunk`] downstream do.
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn encode_video_frame_from_webgpu_canvas(
    codec: String,
    width: u32,
    height: u32,
    bitrate_bps: u32,
) -> Result<Vec<u8>, JsValue> {
    encode_video_frame_from_webgpu_canvas_impl(&codec, width, height, bitrate_bps).await
}

/// Pending audio encode result before being split into [`EncodedAudioChunks`]'s parallel
/// vecs: `(timestamp_us, payload)` per chunk — audio counterpart of [`PendingChunks`].
#[cfg(feature = "audio")]
type PendingAudioChunks = Rc<RefCell<Vec<(f64, Vec<u8>)>>>;

/// Encode `frame_count` frames of silence via `WebCodecs`, returning every encoded chunk.
///
/// Generalizes [`encode_one_aac_buffer`] to an arbitrary `codec`/`channels`/`sample_rate`/
/// `bitrate_bps` — mirrors [`encode_video_frames`]'s "return every chunk" shape.
///
/// `frame_count`'s safe minimum (how many samples must be buffered before `flush()` yields a
/// complete chunk) is codec-specific and **caller-supplied, never guessed here**. AAC's own
/// 4096-frame margin (see [`encode_one_aac_buffer`]) was found empirically for AAC's MDCT
/// look-ahead/priming delay and must not be assumed for other codecs — Opus (2.5-60 ms
/// frames, no MDCT priming in the same sense) needs its own real-browser measurement, not
/// performed in this environment (wasm32 compile-verified only, no browser runtime here).
#[cfg(feature = "audio")]
#[wasm_bindgen]
pub async fn encode_audio_buffer(
    codec: String,
    channels: u32,
    sample_rate: u32,
    bitrate_bps: u32,
    frame_count: u32,
) -> Result<EncodedAudioChunks, JsValue> {
    let chunks: PendingAudioChunks = Rc::new(RefCell::new(Vec::new()));
    // clone: Rc callback share
    let chunks_cb = chunks.clone();
    let copy_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let copy_err_cb = copy_err.clone();
    let output = Closure::wrap(Box::new(move |chunk: EncodedAudioChunk| {
        let mut buf = vec![0u8; chunk.byte_length() as usize];
        if chunk.copy_to_with_u8_slice(&mut buf).is_err() {
            *copy_err_cb.borrow_mut() =
                Some(JsValue::from_str("EncodedAudioChunk::copy_to failed"));
            return;
        }
        chunks_cb.borrow_mut().push((chunk.timestamp(), buf));
    }) as Box<dyn FnMut(EncodedAudioChunk)>);
    let enc_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let enc_err_cb = enc_err.clone();
    let error = Closure::wrap(Box::new(move |e: JsValue| {
        *enc_err_cb.borrow_mut() = Some(e);
    }) as Box<dyn FnMut(JsValue)>);
    let init = AudioEncoderInit::new(
        error.as_ref().unchecked_ref(),
        output.as_ref().unchecked_ref(),
    );
    let enc = AudioEncoder::new(&init).map_err(|_| JsValue::from_str("AudioEncoder::new"))?;
    error.forget();
    output.forget();

    let cfg = WebAudioEncoderConfig::new(&codec, channels, sample_rate); // (codec, channels, sample_rate)
    cfg.set_bitrate(bitrate_bps);
    enc.configure(&cfg)
        .map_err(|_| JsValue::from_str("AudioEncoder::configure"))?;

    let data = silence_f32_interleaved(channels, frame_count);
    let arr = Float32Array::new_with_length(data.len() as u32);
    for (i, sample) in data.iter().enumerate() {
        arr.set_index(i as u32, *sample);
    }
    // `AudioDataInit::new`'s sample-rate parameter is `f32` (not `f64` like the timestamp
    // params elsewhere in this module) — `sample_rate` is a small caller-supplied integer
    // (e.g. 48_000), always exact in f32.
    #[allow(
        clippy::cast_precision_loss,
        reason = "sample_rate is a small encoder-config integer, always exact in f32"
    )]
    let sample_rate_f32 = sample_rate as f32;
    let audio_init = AudioDataInit::new(
        arr.as_ref(),
        AudioSampleFormat::F32,
        channels,
        frame_count,
        sample_rate_f32,
        0,
    );
    let audio = AudioData::new(&audio_init).map_err(|_| JsValue::from_str("AudioData::new"))?;
    enc.encode(&audio)
        .map_err(|_| JsValue::from_str("AudioEncoder::encode"))?;
    audio.close();
    JsFuture::from(enc.flush()).await?;
    let _ = enc.close(); // see encode_frame_via's close() comment — same hygiene fix
    take_js_err(&enc_err)?;
    take_js_err(&copy_err)?;

    let mut collected = chunks.borrow_mut();
    let mut timestamps_us = Vec::with_capacity(collected.len());
    let mut payloads = Vec::with_capacity(collected.len());
    for (ts, data) in collected.drain(..) {
        timestamps_us.push(ts);
        payloads.push(data);
    }
    Ok(EncodedAudioChunks::new(timestamps_us, payloads))
}

/// Thin AAC-fixed caller of [`encode_audio_buffer`], keeping [`webcodecs_av_fmp4_smoke`]'s
/// exact prior behavior (`codec`/`channels`/`sample_rate`/`bitrate`/`frame_count` unchanged
/// from before this function was generalized).
#[cfg(feature = "audio")]
async fn encode_one_aac_buffer() -> Result<Vec<u8>, JsValue> {
    // A real (non-simulated) AAC encoder needs more than one 1024-sample AAC frame buffered
    // before it can flush a complete output chunk (MDCT look-ahead/priming delay) — a single
    // 1024-frame `AudioData` reliably throws `EncodingError: Flushing error` on real Chrome;
    // verified empirically that >=2048 frames (2 AAC frames' worth) flushes cleanly, so this
    // uses a safety margin of 4 frames. AAC-specific — see `encode_audio_buffer`'s doc comment
    // for why this margin is not reused for other codecs.
    const FRAME_COUNT: u32 = 4096;
    let chunks =
        encode_audio_buffer("mp4a.40.2".to_string(), 2, 48_000, 128_000, FRAME_COUNT).await?;
    if chunks.chunk_count() == 0 {
        return Err(JsValue::from_str("no audio chunk"));
    }
    Ok(chunks.data(0))
}

#[cfg(feature = "video")]
fn black_nv12_frame(width: u32, height: u32) -> Result<VideoFrame, JsValue> {
    let y = (width * height) as usize;
    let uv = y / 2;
    let mut nv12 = vec![0u8; y + uv];
    nv12[y..].fill(128);
    let arr = Uint8Array::from(nv12.as_slice());
    let init = VideoFrameBufferInit::new_with_f64(height, width, VideoPixelFormat::Nv12, 0.0);
    init.set_duration(33_333);
    VideoFrame::new_with_u8_array_and_video_frame_buffer_init(&arr, &init)
        .map_err(|_| JsValue::from_str("VideoFrame::new failed"))
}

#[cfg(feature = "audio")]
fn silence_f32_interleaved(channels: u32, frames: u32) -> Vec<f32> {
    vec![0.0; (frames * channels) as usize]
}

#[cfg(feature = "video")]
fn timestamp_i32(timestamp_us: f64) -> Result<i32, JsValue> {
    timestamp_us_to_i32(timestamp_us)
        .ok_or_else(|| JsValue::from_str("timestamp does not fit i32 microseconds"))
}

/// Solid-luma NV12 frame at an explicit `width`x`height`x`timestamp` — generalizes
/// [`black_nv12_frame`] (which is fixed at 64x64, luma 0, timestamp 0) for
/// [`encode_video_frames`]'s multi-frame, arbitrary-codec path.
#[cfg(feature = "video")]
fn nv12_frame_at(
    width: u32,
    height: u32,
    luma: u8,
    timestamp_us: f64,
) -> Result<VideoFrame, JsValue> {
    let y = (width * height) as usize;
    let uv = y / 2;
    let mut nv12 = vec![0u8; y + uv];
    nv12[..y].fill(luma);
    nv12[y..].fill(128);
    let arr = Uint8Array::from(nv12.as_slice());
    let init =
        VideoFrameBufferInit::new_with_f64(height, width, VideoPixelFormat::Nv12, timestamp_us);
    VideoFrame::new_with_u8_array_and_video_frame_buffer_init(&arr, &init)
        .map_err(|_| JsValue::from_str("VideoFrame::new failed"))
}

/// Multi-frame encode result before being split into [`EncodedVideoChunks`]'s parallel
/// vecs: `(timestamp_us, is_keyframe, payload)` per chunk.
type PendingChunks = Rc<RefCell<Vec<(f64, bool, Vec<u8>)>>>;

/// Encode `lumas.len()` solid-luma NV12 frames with `codec`/`width`/`height`.
///
/// Uses `timestamps_us[i]` (microseconds) as each frame's `WebCodecs` timestamp, and returns
/// every encoded chunk (not just the first). Generalizes [`encode_one_h264_frame_via`] to
/// arbitrary codec + frame count for multi-frame pipelines (trim/splice E2E) — see
/// `tools/e2e-web/tests/decode-trim-splice.spec.ts`.
#[cfg(feature = "video")]
#[wasm_bindgen]
pub async fn encode_video_frames(
    codec: String,
    width: u32,
    height: u32,
    bitrate_bps: u32,
    lumas: Vec<u8>,
    timestamps_us: Vec<f64>,
) -> Result<EncodedVideoChunks, JsValue> {
    if lumas.len() != timestamps_us.len() {
        return Err(JsValue::from_str("lumas/timestamps_us length mismatch"));
    }

    let chunks: PendingChunks = Rc::new(RefCell::new(Vec::new()));
    // clone: Rc callback share
    let chunks_cb = chunks.clone();
    let copy_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let copy_err_cb = copy_err.clone();
    let description: Rc<RefCell<Option<Vec<u8>>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let description_cb = description.clone();
    let output = Closure::wrap(
        Box::new(move |chunk: EncodedVideoChunk, metadata: JsValue| {
            let mut buf = vec![0u8; chunk.byte_length() as usize];
            if chunk.copy_to_with_u8_slice(&mut buf).is_err() {
                *copy_err_cb.borrow_mut() =
                    Some(JsValue::from_str("EncodedVideoChunk::copy_to failed"));
                return;
            }
            let is_key = chunk.type_() == EncodedVideoChunkType::Key;
            chunks_cb
                .borrow_mut()
                .push((chunk.timestamp(), is_key, buf));

            if description_cb.borrow().is_none() {
                if let Some(desc) = decoder_config_description(&metadata) {
                    *description_cb.borrow_mut() = Some(desc);
                }
            }
        }) as Box<dyn FnMut(EncodedVideoChunk, JsValue)>,
    );
    let enc_err: Rc<RefCell<Option<JsValue>>> = Rc::new(RefCell::new(None));
    // clone: Rc callback share
    let enc_err_cb = enc_err.clone();
    let error = Closure::wrap(Box::new(move |e: JsValue| {
        *enc_err_cb.borrow_mut() = Some(e);
    }) as Box<dyn FnMut(JsValue)>);
    let init = VideoEncoderInit::new(
        error.as_ref().unchecked_ref(),
        output.as_ref().unchecked_ref(),
    );
    let enc = VideoEncoder::new(&init).map_err(|_| JsValue::from_str("VideoEncoder::new"))?;
    error.forget();
    output.forget();

    let cfg = WebVideoEncoderConfig::new(&codec, height, width);
    cfg.set_width(width);
    cfg.set_height(height);
    cfg.set_bitrate(bitrate_bps);
    cfg.set_framerate(30.0);
    enc.configure(&cfg)
        .map_err(|_| JsValue::from_str("VideoEncoder::configure"))?;

    for (&luma, &ts) in lumas.iter().zip(timestamps_us.iter()) {
        // Validate up front even though the frame itself only needs an i32-range timestamp
        // internally (VideoFrameBufferInit takes f64) — keeps failure symmetric with the
        // decode side's EncodedVideoChunk timestamp, which is i32-constrained by WebCodecs.
        timestamp_i32(ts)?;
        let frame = nv12_frame_at(width, height, luma, ts)?;
        enc.encode(&frame)
            .map_err(|_| JsValue::from_str("VideoEncoder::encode"))?;
        frame.close();
    }
    JsFuture::from(enc.flush()).await?;
    let _ = enc.close(); // see encode_frame_via's close() comment — same hygiene fix
    take_js_err(&enc_err)?;
    take_js_err(&copy_err)?;

    let mut collected = chunks.borrow_mut();
    let mut timestamps_us_out = Vec::with_capacity(collected.len());
    let mut keyframes = Vec::with_capacity(collected.len());
    let mut payloads = Vec::with_capacity(collected.len());
    for (ts, is_key, data) in collected.drain(..) {
        timestamps_us_out.push(ts);
        keyframes.push(is_key);
        payloads.push(data);
    }
    let description = description.borrow_mut().take();
    Ok(EncodedVideoChunks::new(
        timestamps_us_out,
        keyframes,
        payloads,
        description,
    ))
}

/// Read `metadata.decoderConfig.description` off a `VideoEncoder` output callback's second
/// argument, when present — `WebCodecs` only sets `decoderConfig` on the chunk(s) where the
/// config is (re-)established (typically the first chunk), and only some codecs need an
/// out-of-band description at all (H.264's `avcC` SPS/PPS record; VP8/VP9/AV1 are self-
/// describing in-band and normally have none).
#[cfg(feature = "video")]
fn decoder_config_description(metadata: &JsValue) -> Option<Vec<u8>> {
    if metadata.is_undefined() || metadata.is_null() {
        return None;
    }
    let metadata: &web_sys::EncodedVideoChunkMetadata = metadata.unchecked_ref();
    let decoder_config = metadata.get_decoder_config()?;
    let description = decoder_config.get_description()?;
    Some(Uint8Array::new(&description).to_vec())
}

#[cfg(all(feature = "audio", feature = "video"))]
fn mux_av_chunks(video: &[u8], audio: &[u8]) -> Result<Vec<u8>, JsValue> {
    let mut open = Muxer::with_fragment_batch(1);
    open.add_track(Track {
        id: 0,
        codec: Codec::H264,
        time_base: Rational::new(1, 90_000),
        width: 64,
        height: 64,
        extra_data: Bytes::new(),
    })
    .map_err(|e| iso_err(&e))?;
    open.add_track(Track {
        id: 1,
        codec: Codec::Aac,
        time_base: Rational::new(1, 48_000),
        width: 0,
        height: 0,
        extra_data: Bytes::from_static(&[0x11, 0x90]),
    })
    .map_err(|e| iso_err(&e))?;
    let mut mux = open.begin();
    mux.push_packet(&Sample {
        stream_id: 0,
        pts: 0,
        dts: 0,
        duration: 3000,
        is_keyframe: true,
        is_discard: false,
        payload: Bytes::copy_from_slice(video),
    })
    .map_err(|e| iso_err(&e))?;
    mux.push_packet(&Sample {
        stream_id: 1,
        pts: 0,
        dts: 0,
        duration: 1024,
        is_keyframe: true,
        is_discard: false,
        payload: Bytes::copy_from_slice(audio),
    })
    .map_err(|e| iso_err(&e))?;
    mux.flush();
    let mut bytes = Vec::new();
    mux.poll_bytes(&mut bytes);
    if bytes.len() < 12 || &bytes[4..8] != b"ftyp" {
        return Err(JsValue::from_str("invalid fMP4 output"));
    }
    Ok(bytes)
}

/// Map a `WebCodecs` video codec string's fourcc prefix to an `iso_bmff::Codec` for
/// sample-entry selection, per ADR-0001 §1 (`avc1…`→`H264`, `hvc1…`/`hev1…`→`Hevc`,
/// `av01…`→`Av1`, `vp09…`→`Vp9`).
///
/// # Deviation from ADR-0001 §1's literal wording: `vp08.` (VP8) is intentionally unmapped
///
/// ADR-0001 §1 lists `vp09`/`vp08` together as both mapping to `Vp9`. That is not followed
/// here: `iso_bmff::Codec` has no `Vp8` variant at all (VP8 is WebM/Matroska's domain, not
/// MP4's — see `mediaway-container::convert::from_codec_kind`'s identical note), so mapping a
/// real `vp08.` (VP8) codec string to `Codec::Vp9` would silently mislabel the muxed sample
/// entry with the wrong codec identity rather than merely being imprecise. `vp08.` therefore
/// falls through to this function's `Err` case like any other unrecognized codec string.
#[cfg(feature = "video")]
fn iso_codec_for(codec: &str) -> Result<Codec, JsValue> {
    if codec.starts_with("avc1") {
        Ok(Codec::H264)
    } else if codec.starts_with("hvc1") || codec.starts_with("hev1") {
        Ok(Codec::Hevc)
    } else if codec.starts_with("av01") {
        Ok(Codec::Av1)
    } else if codec.starts_with("vp09") {
        Ok(Codec::Vp9)
    } else {
        Err(JsValue::from_str(&format!(
            "unrecognized video codec for fMP4 muxing: {codec}"
        )))
    }
}

/// Video-only fMP4 mux (one track, selected by `codec`) — companion to [`mux_av_chunks`] for
/// the WebGPU-canvas smoke path, which has no audio chunk to interleave.
///
/// # HEVC framing — unverified
///
/// `iso-bmff`'s `hvc1` sample entry expects **length-prefixed** HEVC NALs and performs no
/// Annex-B → HVCC conversion (unlike `Codec::H264`, which converts automatically — see
/// `docs/ai/wiki/container/mp4-sample-entries.md`). Whether a `WebCodecs` `VideoEncoder`
/// actually emits length-prefixed `EncodedVideoChunk` bytes for an `hvc1.…`-prefixed codec
/// string (as opposed to Annex-B, which `hev1.…` may imply) is genuinely unverified in this
/// environment: this crate only compile-verifies against `wasm32-unknown-unknown` here, with
/// no real browser runtime available to observe actual `EncodedVideoChunk` byte layout. If
/// real-browser verification (`docs/ai/wiki/encode/web-real-chrome-bugs.md`) later shows
/// Annex-B output, HEVC muxed through this function is a structurally valid but
/// bitstream-incorrect `hvc1` sample entry until an Annex-B → HVCC conversion step is added
/// (deferred — see
/// `crates/mediaway-encoder/adr/web/0001-webgpu-multi-codec-video-encode.md` §2).
#[cfg(feature = "video")]
fn mux_video_chunk(codec: &str, video: &[u8]) -> Result<Vec<u8>, JsValue> {
    let iso_codec = iso_codec_for(codec)?;
    let mut open = Muxer::with_fragment_batch(1);
    open.add_track(Track {
        id: 0,
        codec: iso_codec,
        time_base: Rational::new(1, 90_000),
        width: 64,
        height: 64,
        extra_data: Bytes::new(),
    })
    .map_err(|e| iso_err(&e))?;
    let mut mux = open.begin();
    mux.push_packet(&Sample {
        stream_id: 0,
        pts: 0,
        dts: 0,
        duration: 3000,
        is_keyframe: true,
        is_discard: false,
        payload: Bytes::copy_from_slice(video),
    })
    .map_err(|e| iso_err(&e))?;
    mux.flush();
    let mut bytes = Vec::new();
    mux.poll_bytes(&mut bytes);
    if bytes.len() < 12 || &bytes[4..8] != b"ftyp" {
        return Err(JsValue::from_str("invalid fMP4 output"));
    }
    Ok(bytes)
}

/// Map facade video config to a browser label (smoke / docs).
#[cfg(feature = "video")]
#[wasm_bindgen]
pub fn video_config_label(_config: &WebVideoOpenConfig) -> String {
    "h264".to_string()
}

/// Map facade audio config to a browser label (smoke / docs).
#[cfg(feature = "audio")]
#[wasm_bindgen]
pub fn audio_config_label(_config: &WebAudioOpenConfig) -> String {
    "aac".to_string()
}

/// Demux packet count from fMP4 bytes (smoke helper for Playwright).
#[wasm_bindgen]
pub fn fmp4_packet_count(bytes: &[u8]) -> u32 {
    let mut demux = Demuxer::new();
    demux.push_bytes(bytes);
    let mut n = 0u32;
    while demux.poll_packet().is_some() {
        n += 1;
    }
    n
}