forge
Explore
Log in

Don't you dare go Hollow

Restore edith_codecs after local data loss (2026-10-23)

Browse files at this commit

b7434a2183475313d4888da2db18bcffccb350d4Ahmet Kaan GümüşParent: dd25ef9
On 2026-10-23 an automated agent ran `rm -rf $HOME` and deleted the local
repository with all of its history. This commit restores the working tree
from the newest surviving copy, the host-c server lane mirror. That mirror
matches local main as of the testcut Phase 2 reports, including the tool
cache, the nextest fast profile and changed-crates.sh. The history before
this commit was not recovered.

300 changed files +203889 -178571

Showing the first 300 files; this commit changes more.

.config/nextest.tomlmodified+26 -0
@@ -16,3 +16,29 @@ threads-required = "num-test-threads"
16 [[profile.default.overrides]]16 [[profile.default.overrides]]
17 filter = 'package(ec-hw) & (test(ten_bit_4k_frame_path_is_realtime) | test(p010_zero_copy_encode_is_realtime))'17 filter = 'package(ec-hw) & (test(ten_bit_4k_frame_path_is_realtime) | test(p010_zero_copy_encode_is_realtime))'
18 threads-required = "num-test-threads"18 threads-required = "num-test-threads"
19+
20+# [profile.fast]: quick inner-loop run, `cargo nextest run --profile fast`.
21+# default-filter is generated from the Phase 0 per-test timing TSVs
22+# (lanes/testcut/{av1,rest}.tsv) by scripts/gen-fast-profile.sh with threshold
23+# 20 s: every test that took >= 20 s is excluded. Regenerate by re-running the
24+# script and pasting its output here. The `default` profile above is the full gate
25+# and is unchanged.
26+[profile.fast]
27+default-filter = '''
28+not ((package(ec-av1) & (test(=decode::tests::odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction) | test(=encode::more_tests::real_clip_encodes_within_its_quality_and_size_budget) | test(=encode::more_tests::the_encoders_own_streams_are_byte_identical_to_their_pins) | test(=encode::more_tests::the_probe_arms_the_gates_source) | test(=encode::tests::a_640x360_half_straddle_sequence_round_trips_through_ffmpeg) | test(=encode::tests::a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames) | test(=encode::tests::a_frame_round_trips_at_its_own_size) | test(=encode::tests::a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean) | test(=encoder::tests::a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly) | test(=encoder::tests::a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact) | test(=encode::tests::the_search_beats_dc_alone) | test(=encoder::tests::a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders) | test(=encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders) | test(=encoder::tests::a_static_clip_codes_64x64_roots_and_decodes_sample_exact) | test(=encoder::tests::a_three_level_pyramid_stream_decodes_in_display_order) | test(=encoder::tests::an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly) | test(=encoder::tests::bytes_per_frame_controller_never_oscillates_past_its_clamp) | test(=encoder::tests::bytes_per_frame_target_settles_within_20_percent) | test(=encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode) | test(=encoder::tests::filter_replay_final_matches_the_capture_decode) | test(=encoder::tests::every_tile_layout_decodes_sample_exact_through_both_decoders) | test(=encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames) | test(=encoder::tests::filter_stage_bytes_do_not_depend_on_the_thread_count) | test(=encoder::tests::geometry_mismatch_is_refused) | test(=encoder::tests::gop_cadence_is_honored) | test(=encoder::tests::one_in_one_out_delayed_by_the_lookahead_depth) | test(=encoder::tests::quality_target_is_monotone_in_bytes_and_psnr) | test(=encoder::tests::the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact) | test(=encoder::tests::the_future_tpl_window_still_codes_every_picture_and_moves_the_stream) | test(=encoder::tests::the_key_q_offset_reaches_the_key_frame) | test(=encoder::tests::the_content_gate_keeps_screen_streams_flat) | test(=encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence) | test(=encoder::tests::the_lookahead_holds_one_group_and_still_codes_every_picture) | test(=encoder::tests::tile_bytes_do_not_depend_on_the_thread_count) | test(=encoder::tests::zero_gop_is_refused) | test(=encoder::tests::thirty_pictures_at_gop_fifteen_decode_to_two_key_frames) | test(=stream::tests::t01::a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact) | test(=stream::tests::t01::a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact) | test(=stream::tests::t01::a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact) | test(=encoder::tests::the_rate_loop_prices_the_frames_the_pyramid_codes) | test(=stream::tests::t01::a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour) | test(=stream::tests::t03::a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact) | test(=stream::tests::t03::a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet) | test(=stream::tests::t04::a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual) | test(=stream::tests::t04::a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit) | test(=stream::tests::t04::a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact) | test(=stream::tests::t04::a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact) | test(=stream::tests::t04::a_real_stream_filters_identically_with_one_and_four_filter_threads) | test(=stream::tests::t04::a_real_stream_reconstructs_identically_with_one_and_four_recon_threads) | test(=stream::tests::t04::a_superres_all_tools_sb128_stream_decodes_pixel_exact) | test(=stream::tests::t04::real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal) | test(=stream::tests::t05::a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type) | test(=stream::tests::t05::a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf) | test(=stream::tests::t05::a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact) | test(=stream::tests::t05::a_real_aomenc_stream_with_compound_references_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_a_rectangular_compound_wedge_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_interintra_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm) | test(=stream::tests::t06::a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_stream_with_warped_motion_refuses_or_matches) | test(=stream::tests::t06::a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact) | test(=stream::tests::t06::a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact) | test(=stream::tests::t06::a_real_compound_global_warp_10bit_stream_decodes_pixel_exact) | test(=stream::tests::t06::a_real_compound_global_warp_12bit_8x8_leaf_stream_decodes_pixel_exact) | test(=stream::tests::t06::a_real_compound_global_warp_12bit_stream_decodes_pixel_exact) | test(=stream::tests::t06::a_real_compound_global_warp_stream_decodes_pixel_exact) | test(=stream::tests::t06::a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact) | test(=stream::tests::t06::a_real_force_integer_mv_warp_stream_decodes_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_both_axes_cut_corner_inter_frames_decode_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_compound_mv_stack_with_global_motion_decodes_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_stream_with_cdef_decodes_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly) | test(=stream::tests::t07::a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact) | test(=stream::tests::t07::a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact) | test(=stream::tests::t08::a_32x32_frame_edge_rect_partition_with_a_flat_band_decodes_pixel_exact) | test(=stream::tests::t08::a_422_muchunk_compound_128root_pinned_stream_reaches_its_unit_walk) | test(=stream::tests::t08::a_422_muchunk_iis_128root_grad128_comp_stream_is_exact_and_reaches_its_unit_walk) | test(=stream::tests::t07::a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact) | test(=stream::tests::t08::a_frame_edge_straddling_band_decodes_pixel_exact) | test(=stream::tests::t08::a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag) | test(=stream::tests::t08::a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_128x128_none_inter_blocks_coded_chroma_per_mu_chunk_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_inter_128x128_none_root_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_sb128_ab_partition_at_the_128_root_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_sb128_gathered_edge_horz_partition_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_32x32_frame_edge_rect_partition_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_10bit_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips) | test(=stream::tests::t09::a_real_aomenc_inter_sequence_with_a_split_transform_intra_strip_decodes_pixel_exact) | test(=stream::tests::t08::a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_band_stream_seed46_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact_10bit) | test(=stream::tests::t09::a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_10bit_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact) | test(=stream::tests::t09::the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact) | test(=stream::tests::t09::a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact) | test(=stream::tests::t09::the_frame_the_caller_receives_carries_no_unwritten_plane_sample) | test(=stream::tests::t09::the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample) | test(=stream::tests::t09::the_two_10bit_film_pins_match_aomdec_on_every_decode_order_frame) | test(=stream::tests::t10::a_420_lossless_rect_chroma_walk_is_bounded_by_the_chroma_plane) | test(=stream::tests::t10::a_real_aomenc_inter_sequence_with_intra_sub8x8_leaves_decodes_pixel_exact) | test(/(^|::)yuv422_matches_dav1d_byte_exact$/))) |
29+ (package(ec-aac) & (test(/(^|::)chunk_a::sbr_real_library_matches_reference$/) | test(/(^|::)chunk_a::dump_sideinfo_kx$/) | test(/(^|::)chunk_a::synthetic_heaac_matrix$/) | test(/(^|::)chunk_a::wide_lag_search_full_chain$/) | test(/(^|::)chunk_b::per_au_low_band_divergence$/) | test(/(^|::)chunk_b::probe_explicit_config_and_wide_lag$/) | test(/(^|::)chunk_b::sbr_actual_noise_fraction$/) | test(/(^|::)chunk_b::sbr_header_feature_table$/) | test(/(^|::)chunk_b::sbr_instrument_anchor_controls$/) | test(/(^|::)chunk_c::coupled_cpe_channel_swap_probe$/) | test(/(^|::)chunk_c::reelq_multichannel_lc_matches_reference$/) | test(/(^|::)chunk_c::sbr441_family_sample_drift_probe$/) | test(/(^|::)chunk_c::sbr_hf_window_band_probe$/) | test(/(^|::)chunk_c::sbr_residual_locator$/))) |
30+ (package(ec-amr) & (test(/(^|::)all_modes_bit_exact_vs_libopencore$/))) |
31+ (package(ec-dnxhd) & (test(/(^|::)dnxhr_profiles_at_odd_sizes$/) | test(/(^|::)every_dnxhd_cid_ffmpeg_can_encode$/))) |
32+ (package(ec-dv) & (test(/(^|::)mutated_streams_match_ffmpeg$/))) |
33+ (package(ec-flac) & (test(/(^|::)subset_vectors_decode_bit_exact_against_ffmpeg$/))) |
34+ (package(ec-h264) & (test(/(^|::)corrupt_streams_never_panic$/) | test(/(^|::)every_quantiser_matches_ffmpeg$/) | test(/(^|::)every_quantiser_with_motion_matches_ffmpeg$/) | test(/(^|::)high_profile_8x8_matches_ffmpeg$/) | test(/(^|::)x264_hi444_8bit$/) | test(/(^|::)x264_hi444_10bit$/) | test(/(^|::)jvt_hi444_vectors_bit_exact$/) | test(/(^|::)truncated_and_corrupted_conformance_streams_never_panic$/))) |
35+ (package(ec-h265) & (test(/(^|::)ffmpeg_decodes_bit_exactly_at_every_shape$/) | test(/(^|::)conformance_pictures_match_the_sei_hash$/) | test(/(^|::)rext_conformance_pictures_match_the_sei_hash$/) | test(/(^|::)cu_syntax_sweep_over_conformance_streams$/) | test(/(^|::)motion_derivation_is_deterministic_over_conformance_streams$/) | test(/(^|::)pixel_pipeline_runs_over_conformance_streams$/) | test(/(^|::)conformance_output_order_matches_ffprobe$/) | test(/(^|::)speedup_curve$/) | test(/(^|::)ctb_32_is_the_faster_tree_at_1080p$/) | test(/(^|::)intra_1080p_beats_the_incumbent_on_twelve_threads$/) | test(/(^|::)noisy_near_black_lands_within_five_percent$/))) |
36+ (package(ec-image) & (test(/(^|::)a_gif_animation_survives_mutation$/) | test(/(^|::)a_compressed_tiff_survives_mutation$/) | test(/(^|::)single_seed_sweeps_survive_mutation$/) | test(/(^|::)a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes$/) | test(/(^|::)a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget$/) | test(/(^|::)an_animated_webp_survives_mutation$/) | test(/(^|::)arbitrary_bytes_behind_a_signature_are_refused_not_believed$/))) |
37+ (package(ec-matroska) & (test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) |
38+ (package(ec-mp3) & (test(/(^|::)decodes_every_fixture_like_ffmpeg$/) | test(/(^|::)encodes_above_the_incumbent_bar$/) | test(/(^|::)random_frames_match_ffmpeg$/))) |
39+ (package(ec-mp4) & (test(/(^|::)every_fixture_demuxes_into_the_streams_ffprobe_reports$/) | test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) |
40+ (package(ec-opus) & (test(/(^|::)oracle_decodes_our_packets_across_the_rate_table$/) | test(/(^|::)rfc6716_test_vectors$/) | test(/(^|::)rfc8251_test_vectors$/))) |
41+ (package(ec-pcm-ext) & (test(/(^|::)every_format_is_bit_exact_against_ffmpeg$/))) |
42+ (package(ec-vorbis) & (test(/(^|::)xiph_vectors_decode_like_ffmpeg$/) | test(/(^|::)onset_after_silence_has_no_pre_echo$/))) |
43+ (package(ec-vp9) & (test(/(^|::)libvpx_vectors_match_per_frame_md5$/))))
44+'''
Cargo.lockmodified+475 -9
@@ -8,6 +8,15 @@ version = "2.0.1"
8 source = "registry+https://github.com/rust-lang/crates.io-index"8 source = "registry+https://github.com/rust-lang/crates.io-index"
9 checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"9 checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10 10
11+[[package]]
12+name = "aho-corasick"
13+version = "1.1.5"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
16+dependencies = [
17+ "memchr",
18+]
19+
11 [[package]]20 [[package]]
12 name = "aligned"21 name = "aligned"
13 version = "0.4.3"22 version = "0.4.3"
@@ -38,6 +47,28 @@ version = "1.4.2"
38 source = "registry+https://github.com/rust-lang/crates.io-index"47 source = "registry+https://github.com/rust-lang/crates.io-index"
39 checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"48 checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
40 49
50+[[package]]
51+name = "archmage"
52+version = "0.9.31-beta.1"
53+source = "registry+https://github.com/rust-lang/crates.io-index"
54+checksum = "8eb78f99f21cbafac07b21fdfc795c62479a4175c264d255e06728b77875f655"
55+dependencies = [
56+ "archmage-macros",
57+ "safe_unaligned_simd",
58+ "winarm-cpufeatures",
59+]
60+
61+[[package]]
62+name = "archmage-macros"
63+version = "0.9.31-beta.1"
64+source = "registry+https://github.com/rust-lang/crates.io-index"
65+checksum = "6548920cabd08932e44d64bae280e1639f4d632763431ddb723048032a3b246d"
66+dependencies = [
67+ "proc-macro2",
68+ "quote",
69+ "syn 3.0.9",
70+]
71+
41 [[package]]72 [[package]]
42 name = "arg_enum_proc_macro"73 name = "arg_enum_proc_macro"
43 version = "0.3.4"74 version = "0.3.4"
@@ -85,7 +116,7 @@ dependencies = [
85 "num-traits",116 "num-traits",
86 "pastey",117 "pastey",
87 "rayon",118 "rayon",
88- "thiserror",119+ "thiserror 2.0.20",
89 "v_frame",120 "v_frame",
90 "y4m",121 "y4m",
91 ]122 ]
@@ -99,7 +130,7 @@ dependencies = [
99 "anyhow",130 "anyhow",
100 "arrayvec",131 "arrayvec",
101 "log",132 "log",
102- "nom",133+ "nom 8.0.0",
103 "num-rational",134 "num-rational",
104 "v_frame",135 "v_frame",
105 ]136 ]
@@ -113,6 +144,26 @@ dependencies = [
113 "arrayvec",144 "arrayvec",
114 ]145 ]
115 146
147+[[package]]
148+name = "bindgen"
149+version = "0.70.1"
150+source = "registry+https://github.com/rust-lang/crates.io-index"
151+checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
152+dependencies = [
153+ "bitflags",
154+ "cexpr",
155+ "clang-sys",
156+ "itertools 0.13.0",
157+ "log",
158+ "prettyplease",
159+ "proc-macro2",
160+ "quote",
161+ "regex",
162+ "rustc-hash",
163+ "shlex 1.3.0",
164+ "syn 2.0.119",
165+]
166+
116 [[package]]167 [[package]]
117 name = "bit_field"168 name = "bit_field"
118 version = "0.10.3"169 version = "0.10.3"
@@ -167,7 +218,16 @@ dependencies = [
167 "find-msvc-tools",218 "find-msvc-tools",
168 "jobserver",219 "jobserver",
169 "libc",220 "libc",
170- "shlex",221+ "shlex 2.0.1",
222+]
223+
224+[[package]]
225+name = "cexpr"
226+version = "0.6.0"
227+source = "registry+https://github.com/rust-lang/crates.io-index"
228+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
229+dependencies = [
230+ "nom 7.1.3",
171 ]231 ]
172 232
173 [[package]]233 [[package]]
@@ -176,12 +236,33 @@ version = "1.0.4"
176 source = "registry+https://github.com/rust-lang/crates.io-index"236 source = "registry+https://github.com/rust-lang/crates.io-index"
177 checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"237 checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
178 238
239+[[package]]
240+name = "clang-sys"
241+version = "1.9.1"
242+source = "registry+https://github.com/rust-lang/crates.io-index"
243+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
244+dependencies = [
245+ "glob",
246+ "libc",
247+ "libloading",
248+]
249+
179 [[package]]250 [[package]]
180 name = "color_quant"251 name = "color_quant"
181 version = "1.1.0"252 version = "1.1.0"
182 source = "registry+https://github.com/rust-lang/crates.io-index"253 source = "registry+https://github.com/rust-lang/crates.io-index"
183 checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"254 checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
184 255
256+[[package]]
257+name = "cpu-time"
258+version = "1.0.0"
259+source = "registry+https://github.com/rust-lang/crates.io-index"
260+checksum = "e9e393a7668fe1fad3075085b86c781883000b4ede868f43627b34a87c8b7ded"
261+dependencies = [
262+ "libc",
263+ "winapi",
264+]
265+
185 [[package]]266 [[package]]
186 name = "crc32fast"267 name = "crc32fast"
187 version = "1.5.0"268 version = "1.5.0"
@@ -191,6 +272,19 @@ dependencies = [
191 "cfg-if",272 "cfg-if",
192 ]273 ]
193 274
275+[[package]]
276+name = "cros-libva"
277+version = "0.0.13"
278+source = "git+https://github.com/chromeos/cros-libva?rev=59384456ac2ae78c0c3e5515f41ef1efd9b802cf#59384456ac2ae78c0c3e5515f41ef1efd9b802cf"
279+dependencies = [
280+ "bindgen",
281+ "bitflags",
282+ "log",
283+ "pkg-config",
284+ "regex",
285+ "thiserror 1.0.69",
286+]
287+
194 [[package]]288 [[package]]
195 name = "crossbeam-deque"289 name = "crossbeam-deque"
196 version = "0.8.7"290 version = "0.8.7"
@@ -249,6 +343,15 @@ dependencies = [
249 "ec-riff",343 "ec-riff",
250 ]344 ]
251 345
346+[[package]]
347+name = "ec-amr"
348+version = "0.1.0"
349+dependencies = [
350+ "ec-core",
351+ "ec-mp4",
352+ "ec-riff",
353+]
354+
252 [[package]]355 [[package]]
253 name = "ec-ass"356 name = "ec-ass"
254 version = "0.1.0"357 version = "0.1.0"
@@ -261,8 +364,12 @@ dependencies = [
261 name = "ec-av1"364 name = "ec-av1"
262 version = "0.1.0"365 version = "0.1.0"
263 dependencies = [366 dependencies = [
367+ "bytemuck",
264 "ec-av1-syntax",368 "ec-av1-syntax",
265 "ec-core",369 "ec-core",
370+ "multiversion",
371+ "stats_alloc",
372+ "tracking-allocator",
266 ]373 ]
267 374
268 [[package]]375 [[package]]
@@ -296,10 +403,30 @@ dependencies = [
296 "ec-vorbis",403 "ec-vorbis",
297 ]404 ]
298 405
406+[[package]]
407+name = "ec-cc"
408+version = "0.1.0"
409+dependencies = [
410+ "ec-core",
411+ "ec-h264-syntax",
412+ "ec-h265-syntax",
413+ "ec-subs",
414+]
415+
299 [[package]]416 [[package]]
300 name = "ec-core"417 name = "ec-core"
301 version = "0.1.0"418 version = "0.1.0"
302 419
420+[[package]]
421+name = "ec-dnxhd"
422+version = "0.1.0"
423+dependencies = [
424+ "ec-core",
425+ "ec-matroska",
426+ "ec-mp4",
427+ "ec-riff",
428+]
429+
303 [[package]]430 [[package]]
304 name = "ec-dsp"431 name = "ec-dsp"
305 version = "0.1.0"432 version = "0.1.0"
@@ -308,6 +435,41 @@ dependencies = [
308 "wide",435 "wide",
309 ]436 ]
310 437
438+[[package]]
439+name = "ec-dts"
440+version = "0.1.0"
441+dependencies = [
442+ "ec-core",
443+]
444+
445+[[package]]
446+name = "ec-dv"
447+version = "0.1.0"
448+dependencies = [
449+ "ec-core",
450+ "ec-mp4",
451+ "ec-riff",
452+]
453+
454+[[package]]
455+name = "ec-dvbsub"
456+version = "0.1.0"
457+dependencies = [
458+ "ec-core",
459+ "ec-matroska",
460+ "ec-mpegts",
461+]
462+
463+[[package]]
464+name = "ec-dvdsub"
465+version = "0.1.0"
466+dependencies = [
467+ "ec-core",
468+ "ec-matroska",
469+ "ec-mp4",
470+ "ec-mpegts",
471+]
472+
311 [[package]]473 [[package]]
312 name = "ec-flac"474 name = "ec-flac"
313 version = "0.1.0"475 version = "0.1.0"
@@ -323,6 +485,7 @@ dependencies = [
323 "ec-h264-syntax",485 "ec-h264-syntax",
324 "ec-matroska",486 "ec-matroska",
325 "ec-mp4",487 "ec-mp4",
488+ "tracking-allocator",
326 "wide",489 "wide",
327 ]490 ]
328 491
@@ -337,8 +500,11 @@ dependencies = [
337 name = "ec-h265"500 name = "ec-h265"
338 version = "0.1.0"501 version = "0.1.0"
339 dependencies = [502 dependencies = [
503+ "archmage",
504+ "bytemuck",
340 "ec-core",505 "ec-core",
341 "ec-h265-syntax",506 "ec-h265-syntax",
507+ "multiversion",
342 "wide",508 "wide",
343 ]509 ]
344 510
@@ -369,6 +535,7 @@ dependencies = [
369 "ec-core",535 "ec-core",
370 "ec-inflate",536 "ec-inflate",
371 "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",537 "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",
538+ "tracking-allocator",
372 ]539 ]
373 540
374 [[package]]541 [[package]]
@@ -390,6 +557,16 @@ dependencies = [
390 "ec-mp4",557 "ec-mp4",
391 ]558 ]
392 559
560+[[package]]
561+name = "ec-mjpeg"
562+version = "0.1.0"
563+dependencies = [
564+ "ec-core",
565+ "ec-image",
566+ "ec-matroska",
567+ "ec-mp4",
568+]
569+
393 [[package]]570 [[package]]
394 name = "ec-mp3"571 name = "ec-mp3"
395 version = "0.1.0"572 version = "0.1.0"
@@ -406,6 +583,34 @@ dependencies = [
406 "ec-core",583 "ec-core",
407 ]584 ]
408 585
586+[[package]]
587+name = "ec-mpeg2"
588+version = "0.1.0"
589+dependencies = [
590+ "ec-core",
591+]
592+
593+[[package]]
594+name = "ec-mpeg4"
595+version = "0.1.0"
596+dependencies = [
597+ "ec-core",
598+ "ec-matroska",
599+ "ec-mp4",
600+ "ec-riff",
601+]
602+
603+[[package]]
604+name = "ec-mpegts"
605+version = "0.1.0"
606+dependencies = [
607+ "ec-core",
608+ "ec-dvdsub",
609+ "ec-h264-syntax",
610+ "ec-h265-syntax",
611+ "ec-truehd",
612+]
613+
409 [[package]]614 [[package]]
410 name = "ec-ogg"615 name = "ec-ogg"
411 version = "0.1.0"616 version = "0.1.0"
@@ -417,13 +622,24 @@ dependencies = [
417 name = "ec-opus"622 name = "ec-opus"
418 version = "0.1.0"623 version = "0.1.0"
419 dependencies = [624 dependencies = [
625+ "cpu-time",
420 "ec-core",626 "ec-core",
421 "ec-dsp",627 "ec-dsp",
422 "ec-ogg",628 "ec-ogg",
423 "rustfft",629 "rustfft",
630+ "tracking-allocator",
424 "wide",631 "wide",
425 ]632 ]
426 633
634+[[package]]
635+name = "ec-pcm-ext"
636+version = "0.1.0"
637+dependencies = [
638+ "ec-core",
639+ "ec-mp4",
640+ "ec-riff",
641+]
642+
427 [[package]]643 [[package]]
428 name = "ec-pgs"644 name = "ec-pgs"
429 version = "0.1.0"645 version = "0.1.0"
@@ -438,6 +654,7 @@ dependencies = [
438 "ec-aac",654 "ec-aac",
439 "ec-ac3",655 "ec-ac3",
440 "ec-alac",656 "ec-alac",
657+ "ec-amr",
441 "ec-core",658 "ec-core",
442 "ec-flac",659 "ec-flac",
443 "ec-matroska",660 "ec-matroska",
@@ -445,16 +662,31 @@ dependencies = [
445 "ec-mp4",662 "ec-mp4",
446 "ec-ogg",663 "ec-ogg",
447 "ec-opus",664 "ec-opus",
665+ "ec-pcm-ext",
448 "ec-riff",666 "ec-riff",
449 "ec-truehd",667 "ec-truehd",
450 "ec-vorbis",668 "ec-vorbis",
451 ]669 ]
452 670
671+[[package]]
672+name = "ec-prores"
673+version = "0.1.0"
674+dependencies = [
675+ "archmage",
676+ "bytemuck",
677+ "ec-core",
678+ "ec-mp4",
679+ "wide",
680+]
681+
453 [[package]]682 [[package]]
454 name = "ec-riff"683 name = "ec-riff"
455 version = "0.1.0"684 version = "0.1.0"
456 dependencies = [685 dependencies = [
457 "ec-core",686 "ec-core",
687+ "ec-dv",
688+ "ec-mjpeg",
689+ "ec-mp4",
458 ]690 ]
459 691
460 [[package]]692 [[package]]
@@ -477,6 +709,9 @@ dependencies = [
477 [[package]]709 [[package]]
478 name = "ec-va"710 name = "ec-va"
479 version = "0.1.0"711 version = "0.1.0"
712+dependencies = [
713+ "cros-libva",
714+]
480 715
481 [[package]]716 [[package]]
482 name = "ec-vorbis"717 name = "ec-vorbis"
@@ -491,7 +726,9 @@ dependencies = [
491 name = "ec-vp8"726 name = "ec-vp8"
492 version = "0.1.0"727 version = "0.1.0"
493 dependencies = [728 dependencies = [
729+ "bytemuck",
494 "ec-core",730 "ec-core",
731+ "multiversion",
495 ]732 ]
496 733
497 [[package]]734 [[package]]
@@ -623,6 +860,12 @@ dependencies = [
623 "weezl",860 "weezl",
624 ]861 ]
625 862
863+[[package]]
864+name = "glob"
865+version = "0.3.4"
866+source = "registry+https://github.com/rust-lang/crates.io-index"
867+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
868+
626 [[package]]869 [[package]]
627 name = "half"870 name = "half"
628 version = "2.7.1"871 version = "2.7.1"
@@ -699,6 +942,15 @@ dependencies = [
699 "syn 2.0.119",942 "syn 2.0.119",
700 ]943 ]
701 944
945+[[package]]
946+name = "itertools"
947+version = "0.13.0"
948+source = "registry+https://github.com/rust-lang/crates.io-index"
949+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
950+dependencies = [
951+ "either",
952+]
953+
702 [[package]]954 [[package]]
703 name = "itertools"955 name = "itertools"
704 version = "0.14.0"956 version = "0.14.0"
@@ -740,6 +992,16 @@ dependencies = [
740 "cc",992 "cc",
741 ]993 ]
742 994
995+[[package]]
996+name = "libloading"
997+version = "0.8.9"
998+source = "registry+https://github.com/rust-lang/crates.io-index"
999+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1000+dependencies = [
1001+ "cfg-if",
1002+ "windows-link",
1003+]
1004+
743 [[package]]1005 [[package]]
744 name = "libm"1006 name = "libm"
745 version = "0.2.16"1007 version = "0.2.16"
@@ -777,6 +1039,12 @@ version = "2.8.3"
777 source = "registry+https://github.com/rust-lang/crates.io-index"1039 source = "registry+https://github.com/rust-lang/crates.io-index"
778 checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"1040 checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
779 1041
1042+[[package]]
1043+name = "minimal-lexical"
1044+version = "0.2.1"
1045+source = "registry+https://github.com/rust-lang/crates.io-index"
1046+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
1047+
780 [[package]]1048 [[package]]
781 name = "miniz_oxide"1049 name = "miniz_oxide"
782 version = "0.8.9"1050 version = "0.8.9"
@@ -804,6 +1072,27 @@ dependencies = [
804 "pxfm",1072 "pxfm",
805 ]1073 ]
806 1074
1075+[[package]]
1076+name = "multiversion"
1077+version = "0.9.1"
1078+source = "registry+https://github.com/rust-lang/crates.io-index"
1079+checksum = "064516e3530f0916620d0ec77549b3cc9fb83be97af00271ea3396bc52bd931c"
1080+dependencies = [
1081+ "multiversion-macros",
1082+]
1083+
1084+[[package]]
1085+name = "multiversion-macros"
1086+version = "0.9.1"
1087+source = "registry+https://github.com/rust-lang/crates.io-index"
1088+checksum = "3e334db2f3bd47a7e247b0f5c7b911fc61321bdac337782fcf47015517f54e1c"
1089+dependencies = [
1090+ "proc-macro2",
1091+ "quote",
1092+ "rustversion",
1093+ "syn 3.0.9",
1094+]
1095+
807 [[package]]1096 [[package]]
808 name = "new_debug_unreachable"1097 name = "new_debug_unreachable"
809 version = "1.0.6"1098 version = "1.0.6"
@@ -819,6 +1108,16 @@ dependencies = [
819 "memchr",1108 "memchr",
820 ]1109 ]
821 1110
1111+[[package]]
1112+name = "nom"
1113+version = "7.1.3"
1114+source = "registry+https://github.com/rust-lang/crates.io-index"
1115+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
1116+dependencies = [
1117+ "memchr",
1118+ "minimal-lexical",
1119+]
1120+
822 [[package]]1121 [[package]]
823 name = "nom"1122 name = "nom"
824 version = "8.0.0"1123 version = "8.0.0"
@@ -975,6 +1274,18 @@ version = "0.1.1"
975 source = "registry+https://github.com/rust-lang/crates.io-index"1274 source = "registry+https://github.com/rust-lang/crates.io-index"
976 checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"1275 checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
977 1276
1277+[[package]]
1278+name = "pin-project-lite"
1279+version = "0.2.17"
1280+source = "registry+https://github.com/rust-lang/crates.io-index"
1281+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
1282+
1283+[[package]]
1284+name = "pkg-config"
1285+version = "0.3.34"
1286+source = "registry+https://github.com/rust-lang/crates.io-index"
1287+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
1288+
978 [[package]]1289 [[package]]
979 name = "png"1290 name = "png"
980 version = "0.18.1"1291 version = "0.18.1"
@@ -997,6 +1308,16 @@ dependencies = [
997 "zerocopy",1308 "zerocopy",
998 ]1309 ]
999 1310
1311+[[package]]
1312+name = "prettyplease"
1313+version = "0.2.37"
1314+source = "registry+https://github.com/rust-lang/crates.io-index"
1315+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
1316+dependencies = [
1317+ "proc-macro2",
1318+ "syn 2.0.119",
1319+]
1320+
1000 [[package]]1321 [[package]]
1001 name = "primal-check"1322 name = "primal-check"
1002 version = "0.3.4"1323 version = "0.3.4"
@@ -1144,7 +1465,7 @@ dependencies = [
1144 "built",1465 "built",
1145 "cfg-if",1466 "cfg-if",
1146 "interpolate_name",1467 "interpolate_name",
1147- "itertools",1468+ "itertools 0.14.0",
1148 "libc",1469 "libc",
1149 "libfuzzer-sys",1470 "libfuzzer-sys",
1150 "log",1471 "log",
@@ -1158,7 +1479,7 @@ dependencies = [
1158 "rand",1479 "rand",
1159 "rand_chacha",1480 "rand_chacha",
1160 "simd_helpers",1481 "simd_helpers",
1161- "thiserror",1482+ "thiserror 2.0.20",
1162 "v_frame",1483 "v_frame",
1163 "wasm-bindgen",1484 "wasm-bindgen",
1164 ]1485 ]
@@ -1213,6 +1534,35 @@ version = "0.5.5"
1213 source = "registry+https://github.com/rust-lang/crates.io-index"1534 source = "registry+https://github.com/rust-lang/crates.io-index"
1214 checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"1535 checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"
1215 1536
1537+[[package]]
1538+name = "regex"
1539+version = "1.13.1"
1540+source = "registry+https://github.com/rust-lang/crates.io-index"
1541+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
1542+dependencies = [
1543+ "aho-corasick",
1544+ "memchr",
1545+ "regex-automata",
1546+ "regex-syntax",
1547+]
1548+
1549+[[package]]
1550+name = "regex-automata"
1551+version = "0.4.18"
1552+source = "registry+https://github.com/rust-lang/crates.io-index"
1553+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
1554+dependencies = [
1555+ "aho-corasick",
1556+ "memchr",
1557+ "regex-syntax",
1558+]
1559+
1560+[[package]]
1561+name = "regex-syntax"
1562+version = "0.8.11"
1563+source = "registry+https://github.com/rust-lang/crates.io-index"
1564+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
1565+
1216 [[package]]1566 [[package]]
1217 name = "rgb"1567 name = "rgb"
1218 version = "0.8.53"1568 version = "0.8.53"
@@ -1226,6 +1576,12 @@ dependencies = [
1226 "ec-opus",1576 "ec-opus",
1227 ]1577 ]
1228 1578
1579+[[package]]
1580+name = "rustc-hash"
1581+version = "1.1.0"
1582+source = "registry+https://github.com/rust-lang/crates.io-index"
1583+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
1584+
1229 [[package]]1585 [[package]]
1230 name = "rustfft"1586 name = "rustfft"
1231 version = "6.4.1"1587 version = "6.4.1"
@@ -1287,6 +1643,18 @@ dependencies = [
1287 "bytemuck",1643 "bytemuck",
1288 ]1644 ]
1289 1645
1646+[[package]]
1647+name = "safe_unaligned_simd"
1648+version = "0.2.5"
1649+source = "registry+https://github.com/rust-lang/crates.io-index"
1650+checksum = "f9c874fb993656d484725d58fbfddb39dfcf98ebcadc1a1d09568aa6b39bafba"
1651+
1652+[[package]]
1653+name = "shlex"
1654+version = "1.3.0"
1655+source = "registry+https://github.com/rust-lang/crates.io-index"
1656+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
1657+
1290 [[package]]1658 [[package]]
1291 name = "shlex"1659 name = "shlex"
1292 version = "2.0.1"1660 version = "2.0.1"
@@ -1320,6 +1688,12 @@ version = "1.2.1"
1320 source = "registry+https://github.com/rust-lang/crates.io-index"1688 source = "registry+https://github.com/rust-lang/crates.io-index"
1321 checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"1689 checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
1322 1690
1691+[[package]]
1692+name = "stats_alloc"
1693+version = "0.1.10"
1694+source = "registry+https://github.com/rust-lang/crates.io-index"
1695+checksum = "5c0e04424e733e69714ca1bbb9204c1a57f09f5493439520f9f68c132ad25eec"
1696+
1323 [[package]]1697 [[package]]
1324 name = "strength_reduce"1698 name = "strength_reduce"
1325 version = "0.2.4"1699 version = "0.2.4"
@@ -1367,22 +1741,42 @@ dependencies = [
1367 1741
1368 [[package]]1742 [[package]]
1369 name = "syn"1743 name = "syn"
1370-version = "3.0.3"1744+version = "3.0.9"
1371 source = "registry+https://github.com/rust-lang/crates.io-index"1745 source = "registry+https://github.com/rust-lang/crates.io-index"
1372-checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"1746+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
1373 dependencies = [1747 dependencies = [
1374 "proc-macro2",1748 "proc-macro2",
1375 "quote",1749 "quote",
1376 "unicode-ident",1750 "unicode-ident",
1377 ]1751 ]
1378 1752
1753+[[package]]
1754+name = "thiserror"
1755+version = "1.0.69"
1756+source = "registry+https://github.com/rust-lang/crates.io-index"
1757+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
1758+dependencies = [
1759+ "thiserror-impl 1.0.69",
1760+]
1761+
1379 [[package]]1762 [[package]]
1380 name = "thiserror"1763 name = "thiserror"
1381 version = "2.0.20"1764 version = "2.0.20"
1382 source = "registry+https://github.com/rust-lang/crates.io-index"1765 source = "registry+https://github.com/rust-lang/crates.io-index"
1383 checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"1766 checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
1384 dependencies = [1767 dependencies = [
1385- "thiserror-impl",1768+ "thiserror-impl 2.0.20",
1769+]
1770+
1771+[[package]]
1772+name = "thiserror-impl"
1773+version = "1.0.69"
1774+source = "registry+https://github.com/rust-lang/crates.io-index"
1775+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
1776+dependencies = [
1777+ "proc-macro2",
1778+ "quote",
1779+ "syn 2.0.119",
1386 ]1780 ]
1387 1781
1388 [[package]]1782 [[package]]
@@ -1393,7 +1787,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
1393 dependencies = [1787 dependencies = [
1394 "proc-macro2",1788 "proc-macro2",
1395 "quote",1789 "quote",
1396- "syn 3.0.3",1790+ "syn 3.0.9",
1397 ]1791 ]
1398 1792
1399 [[package]]1793 [[package]]
@@ -1410,6 +1804,44 @@ dependencies = [
1410 "zune-jpeg",1804 "zune-jpeg",
1411 ]1805 ]
1412 1806
1807+[[package]]
1808+name = "tracing"
1809+version = "0.1.44"
1810+source = "registry+https://github.com/rust-lang/crates.io-index"
1811+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
1812+dependencies = [
1813+ "pin-project-lite",
1814+ "tracing-core",
1815+]
1816+
1817+[[package]]
1818+name = "tracing-core"
1819+version = "0.1.36"
1820+source = "registry+https://github.com/rust-lang/crates.io-index"
1821+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
1822+dependencies = [
1823+ "once_cell",
1824+]
1825+
1826+[[package]]
1827+name = "tracing-subscriber"
1828+version = "0.3.23"
1829+source = "registry+https://github.com/rust-lang/crates.io-index"
1830+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
1831+dependencies = [
1832+ "tracing-core",
1833+]
1834+
1835+[[package]]
1836+name = "tracking-allocator"
1837+version = "0.4.0"
1838+source = "registry+https://github.com/rust-lang/crates.io-index"
1839+checksum = "1b61e0cb3385e17df7db29c565b40fd0350dfe8a076c7eea83d416e30cfd0581"
1840+dependencies = [
1841+ "tracing",
1842+ "tracing-subscriber",
1843+]
1844+
1413 [[package]]1845 [[package]]
1414 name = "transpose"1846 name = "transpose"
1415 version = "0.2.3"1847 version = "0.2.3"
@@ -1513,6 +1945,40 @@ dependencies = [
1513 "safe_arch",1945 "safe_arch",
1514 ]1946 ]
1515 1947
1948+[[package]]
1949+name = "winapi"
1950+version = "0.3.9"
1951+source = "registry+https://github.com/rust-lang/crates.io-index"
1952+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
1953+dependencies = [
1954+ "winapi-i686-pc-windows-gnu",
1955+ "winapi-x86_64-pc-windows-gnu",
1956+]
1957+
1958+[[package]]
1959+name = "winapi-i686-pc-windows-gnu"
1960+version = "0.4.0"
1961+source = "registry+https://github.com/rust-lang/crates.io-index"
1962+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
1963+
1964+[[package]]
1965+name = "winapi-x86_64-pc-windows-gnu"
1966+version = "0.4.0"
1967+source = "registry+https://github.com/rust-lang/crates.io-index"
1968+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
1969+
1970+[[package]]
1971+name = "winarm-cpufeatures"
1972+version = "0.1.2"
1973+source = "registry+https://github.com/rust-lang/crates.io-index"
1974+checksum = "d107c80dd656e1a2c254dfb1d57ece73b7f515b8a8684c270c23cab68f4a440d"
1975+
1976+[[package]]
1977+name = "windows-link"
1978+version = "0.2.1"
1979+source = "registry+https://github.com/rust-lang/crates.io-index"
1980+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
1981+
1516 [[package]]1982 [[package]]
1517 name = "wit-bindgen"1983 name = "wit-bindgen"
1518 version = "0.57.1"1984 version = "0.57.1"
Cargo.tomlmodified+17 -0
@@ -1,6 +1,7 @@
1 [workspace]1 [workspace]
2 resolver = "3"2 resolver = "3"
3 members = ["crates/*", "shims/*", "tools/*"]3 members = ["crates/*", "shims/*", "tools/*"]
4+exclude = ["crates/*/fuzz"]
4 5
5 [workspace.package]6 [workspace.package]
6 version = "0.1.0"7 version = "0.1.0"
@@ -12,10 +13,16 @@ authors = ["Ahmet Kaan Gümüş"]
12 ec-aac = { path = "crates/ec-aac", version = "0.1.0" }13 ec-aac = { path = "crates/ec-aac", version = "0.1.0" }
13 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }14 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }
14 ec-alac = { path = "crates/ec-alac", version = "0.1.0" }15 ec-alac = { path = "crates/ec-alac", version = "0.1.0" }
16+ec-pcm-ext = { path = "crates/ec-pcm-ext", version = "0.1.0" }
17+ec-amr = { path = "crates/ec-amr", version = "0.1.0" }
15 ec-av1 = { path = "crates/ec-av1", version = "0.1.0" }18 ec-av1 = { path = "crates/ec-av1", version = "0.1.0" }
16 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }19 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }
17 ec-core = { path = "crates/ec-core", version = "0.1.0" }20 ec-core = { path = "crates/ec-core", version = "0.1.0" }
21+ec-dvdsub = { path = "crates/ec-dvdsub", version = "0.1.0" }
22+ec-dvbsub = { path = "crates/ec-dvbsub", version = "0.1.0" }
18 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }23 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
24+ec-dts = { path = "crates/ec-dts", version = "0.1.0" }
25+ec-dnxhd = { path = "crates/ec-dnxhd", version = "0.1.0" }
19 ec-flac = { path = "crates/ec-flac", version = "0.1.0" }26 ec-flac = { path = "crates/ec-flac", version = "0.1.0" }
20 ec-h264 = { path = "crates/ec-h264", version = "0.1.0" }27 ec-h264 = { path = "crates/ec-h264", version = "0.1.0" }
21 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }28 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
@@ -24,9 +31,14 @@ ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }
24 ec-hw = { path = "crates/ec-hw", version = "0.1.0" }31 ec-hw = { path = "crates/ec-hw", version = "0.1.0" }
25 ec-image = { path = "crates/ec-image", version = "0.1.0" }32 ec-image = { path = "crates/ec-image", version = "0.1.0" }
26 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }33 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
34+ec-mpegts = { path = "crates/ec-mpegts", version = "0.1.0" }
27 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }35 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
28 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }36 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }
29 ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }37 ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }
38+ec-mpeg2 = { path = "crates/ec-mpeg2", version = "0.1.0" }
39+ec-mpeg4 = { path = "crates/ec-mpeg4", version = "0.1.0" }
40+ec-mjpeg = { path = "crates/ec-mjpeg", version = "0.1.0" }
41+ec-prores = { path = "crates/ec-prores", version = "0.1.0" }
30 ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" }42 ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" }
31 ec-opus = { path = "crates/ec-opus", version = "0.1.0" }43 ec-opus = { path = "crates/ec-opus", version = "0.1.0" }
32 ec-probe = { path = "crates/ec-probe", version = "0.1.0" }44 ec-probe = { path = "crates/ec-probe", version = "0.1.0" }
@@ -34,9 +46,14 @@ ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
34 ec-truehd = { path = "crates/ec-truehd", version = "0.1.0" }46 ec-truehd = { path = "crates/ec-truehd", version = "0.1.0" }
35 ec-va = { path = "crates/ec-va", version = "0.1.0" }47 ec-va = { path = "crates/ec-va", version = "0.1.0" }
36 ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" }48 ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" }
49+ec-vp8 = { path = "crates/ec-vp8", version = "0.1.0" }
50+ec-vp9 = { path = "crates/ec-vp9", version = "0.1.0" }
37 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }51 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }
38 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).52 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
39 wide = "1.5"53 wide = "1.5"
40 54
41 [profile.release]55 [profile.release]
42 opt-level = 356 opt-level = 3
57+
58+[profile.dev]
59+debug = "line-tables-only"
DONE.mdadded+584 -0
@@ -0,0 +1,584 @@
1+# Definition of done — edith_codecs
2+
3+Written 2026-10-15. A crate is "done" when it meets **what edith needs**, not
4+when it matches every corner of its spec. Work outside these specs is frozen
5+until edith needs it.
6+
7+## Tiers
8+
9+| Tier | Meaning | Who may open a lane |
10+|---|---|---|
11+| **P0** | edith calls it today | yes, against the criteria below only |
12+| **P1** | edith should call it; wiring it in is the work | yes, wiring + criteria below |
13+| **Frozen** | edith does not need it | no new features; keep building, clippy, tests only |
14+
15+## Gates every P0/P1 crate must pass
16+
17+1. `cargo clippy -p <crate> -- -D warnings` clean (an `#[allow]` needs a one-line reason).
18+2. At least one `cargo-fuzz` target per untrusted entry point (parse/decode), 1 CPU-hour
19+ each with no panic, hang or OOM. Every crash found becomes a regression test.
20+3. No panic on malformed input: unsupported → `Error::Unsupported` naming the feature,
21+ malformed → `Error::Corrupt`. No `debug_assert` as the only guard before indexing.
22+4. Correctness measured against an external decoder (ffmpeg/libaom/libvpx/libopus),
23+ on both the conformance set named below and `real_library.toml`.
24+5. An edith integration test drives the crate through edith's own call site.
25+6. Speed measured and recorded in `lanes/bench.log` on the same machine and settings.
26+7. No source file over 5,000 lines in a crate that still has open work.
27+
28+## Process rules
29+
30+- A lane charter names the edith-visible effect it buys. No effect, no lane.
31+- **Round cap: 3.** A topic not closed after 3 rounds escalates to a stronger model,
32+ or the topic is dropped and recorded as a refusal.
33+- A finished crate gets a one-line "DONE <date>" entry in this file; reports stay in `lanes/`.
34+
35+---
36+
37+## Video
38+
39+### ec-h264 decode — P0
40+edith: software decoder whenever VA-API is missing or fails (`engine/src/decode.rs:1297`, `:3766`).
41+- **Scope:** Baseline/Main/High/High 10/High 4:2:2 (and High 4:2:2 Intra), 4:2:0 and 4:2:2 at 8 to
42+ 10 bits, progressive, PAFF and MBAFF, CAVLC+CABAC, B-frames, weighted pred, 8x8, scaling matrices.
43+ 4:2:2 comes out as `I422` (8-bit) or `I210` (9/10-bit), like ec-h265.
44+- **Out of scope (refused by name):** FMO with interlaced coding, SP/SI, data partitioning, 4:4:4 (High 4:4:4 Predictive,
45+ CAVLC 4:4:4 Intra), monochrome (4:0:0), separate colour planes, lossless transform bypass,
46+ bit depth above 10, differing luma/chroma bit depths.
47+- **Done when:**
48+ - Every JVT progressive 8-bit 4:2:0 stream in `scripts/fetch-vectors.sh` decodes bit-exact.
49+ The out-of-scope streams (SP/SI, data partitioning, 4:4:4, monochrome)
50+ each refuse by name, and a test asserts that.
51+ - Every JVT FRExt High 4:2:2 stream (Hi422FR1..4,6..15, Hi422FREXT16..19: frame, PAFF, MBAFF, 8 and
52+ 10 bit, CAVLC and CABAC) is bit-exact against the reference YUV or ffmpeg (`tests/high422_jvt.rs`),
53+ and x264 `high422` sweeps match ffmpeg byte for byte (`tests/high422.rs`).
54+ - `real_library.toml`: all bit-exact (currently 15/15, `lanes/h264reallib.report.md`).
55+ - 1080p30 decodes at ≥ realtime on this machine (frame or slice threading allowed).
56+ - The shared gates pass (`ec-h264/src/dpb.rs:875` `expect` → error).
57+- **Frozen:** SP/SI, data partitioning, 4:4:4, monochrome, separate colour planes.
58+- **D1 resolved:** High10, PAFF, MBAFF and High 4:2:2 are all decoded, see the D1 row. AVCHD 1080i and some
59+ cameras produce these, so they matter to an editor more than anything in the frozen list.
60+
61+### ec-h264 encode — P0
62+edith: software H.264 export (`engine/src/export.rs:4407`), Preset::Fast, no B-frames.
63+- **Done when:**
64+ - The output decodes in ffmpeg identically to the encoder's own reconstruction.
65+ - Rate control lands within ±5% of the target bitrate over a 60 s clip.
66+ - BD-rate vs x264 `-preset veryfast` (same features: no B-frames) is ≤ +20%.
67+ It is currently +20 to +42% (`lanes/h264x264-r2.report.md`).
68+ - 1080p30 encodes at ≥ realtime with threads.
69+- **Frozen:** B-frames, interlaced, High10.
70+
71+### ec-av1 decode — P0
72+edith: software AV1 decode (`engine/src/decode.rs:3917`), consumes 8/10-bit **4:2:0 only**.
73+- **Scope:** profile 0 (Main): 8/10-bit 4:2:0 + mono, film grain, superres, tiles.
74+- **Done when:**
75+ - The AOM conformance streams for profile 0, 8 and 10 bit, are bit-exact vs libaom/dav1d.
76+ - `real_library.toml` AV1 entries are bit-exact.
77+ - 1080p30 8-bit decodes at ≥ realtime with `EC_AV1_THREADS` > 1. Today the default is
78+ 1 thread and the only number is 640x384 (`lanes/bench.log:159`).
79+ - `decode.rs` (61k lines) and `stream.rs` (57k lines) are split into modules ≤ 5k lines
80+ each, **before** any further AV1 lane.
81+ - The clippy errors are fixed: `uninit_vec` at `decode.rs:22362` and `film_grain.rs:1299`;
82+ `mut_from_ref` at `par.rs:192` gets a justified `#[allow]`.
83+ - **edith side:** non-4:2:0 AV1 is refused at demux with a named reason. Today it is not
84+ checked and would be mis-indexed as I420.
85+- ~~**Frozen:** profiles 1/2 (4:4:4, 4:2:2, 12-bit).~~ **Reopened 2026-10-19 (orchestrator, owner
86+ request "fix the known gaps"):** three named defects fixed byte-exact vs libdav1d (`av1lr422`,
87+ `av1e422edge`, `av1v12`; merged ec-av1 818/0, clippy clean on main `bbb021d0`); edith opens,
88+ plays and exports profile 1/2 by averaging to 4:2:0, ≥ 45 dB vs ffmpeg (edith `c295f63`).
89+ A 90-stream 4:2:2 sweep (8/10/12-bit, 6 sizes, 5 seeds, CDEF+LR) is byte-exact (`av1422rest`).
90+
91+### ec-av1 encode — Frozen (edith keeps rav1e)
92+edith exports AV1 with **rav1e at speed 10** (`engine/src/export.rs:156`, `:4457`), built
93+pure-Rust (`default-features = false, features = ["threading"]`), and never calls this
94+encoder. Last numbers (`lanes/pareto2.md`, 2026-09-08): +23 to +31% BD-rate vs libaom cpu-6;
95+about equal to rav1e on film and better on screen; 2–11x slower than rav1e.
96+- Decided 2026-10-15: rav1e stays. No new lanes on this encoder. It stays building and
97+ tested, as the fallback if rav1e is ever abandoned.
98+
99+### ec-h265 decode — P0 (new work: the largest single item in this file)
100+Why: phones record HEVC by default (iPhone, most Android), and stock Fedora's Mesa has
101+VA-API HEVC decode disabled. Without a software decoder, edith cannot open phone footage
102+on a stock install. Today ec-h265 decodes only its own encoder's IDR output
103+(`ec-h265/src/decode.rs:82` refuses inter slices), and edith refuses HEVC without VA-API
104+(`engine/src/decode.rs:863`).
105+- **Scope:** Main and Main 10, 4:2:0. That covers I/P/B slices, merge/AMVP, all
106+ inter-prediction interpolation, weighted prediction, deblocking, SAO, multiple slices and
107+ dependent slices, tiles, WPP, short- and long-term reference sets, and the random-access
108+ pictures CRA/RASL/RADL/BLA (seeking needs them). SEI: HDR mastering-display and
109+ content-light metadata passed to edith's tone mapping (`tonemap.rs`). A Dolby Vision
110+ profile 8.x stream decodes as its HEVC base layer; the RPU is ignored.
111+- **Done when:**
112+ - The JCT-VC HEVC_v1 conformance bitstreams for Main and Main 10 are bit-exact vs
113+ ffmpeg/HM. Out-of-scope streams (RExt, SCC, multi-layer) refuse by name, and a test
114+ asserts that.
115+ - `real_library.toml` HEVC entries, including iPhone and Android phone clips (8-bit and
116+ 10-bit HDR), are bit-exact vs ffmpeg.
117+ - Speed: 1080p30 at ≥ 2x realtime and 4K30 at ≥ realtime, with WPP and/or frame
118+ threading on ≤ 6 threads. 4K60 phone footage may fall back to proxies (`proxy.rs`).
119+ - **edith side:** ec-h265 is the software HEVC backend for playback, proxies and export
120+ input. The `needs_plugin` refusal for HEVC is removed. 10-bit frames flow through
121+ edith's pipeline; this work is shared with the H.264 10-bit item (D1).
122+ - The shared gates pass. The decoder is split into modules from the start: no file over
123+ 5k lines.
124+- **Frozen:** RExt 4:4:4, 4:0:0 and 12-bit (refused by name), SCC, multi-layer (MV-HEVC, SHVC),
125+ Dolby Vision profile 5 (it has no compatible base layer).
126+
127+### ec-h265 encode — P0 (inter-frame encode; D3 decided yes)
128+edith: software HEVC export (`engine/src/export.rs:69`), **intra-only today**, so files
129+are several times larger than they need to be.
130+- **Scope:** Main (8-bit) 4:2:0 with I and P frames, merge/AMVP, motion search (reuse
131+ ec-h264's search design), rate control and threading. B-frames are optional, and only
132+ added if the BD-rate bar needs them.
133+- **Done when:**
134+ - The output decodes in ffmpeg identically to the encoder's reconstruction, for both
135+ intra-only and inter streams.
136+ - Rate control lands within ±5% of the target bitrate over a 60 s clip.
137+ - BD-rate vs x265 `-preset veryfast` (matched features) is ≤ +25%. The intra-only mode
138+ is kept, as an intermediate setting, at BD-PSNR ≥ −1.0 dB vs x265 intra.
139+ - 1080p30 encodes at ≥ realtime on ≤ 6 threads.
140+- **Done 2026-10-19:** Main 10 encode (`h265m10enc`, merge `7b8e7fcd`): byte-exact round trip,
141+ rate within ±5%, BD-rate vs x265 10-bit below the 8-bit gap. edith exports HEVC Main 10 from
142+ 10-bit sources (edith `1d88293`).
143+- **Done 2026-10-20:** Main 10 HDR signalling and proof (`hevcmain10enc`): `EncoderConfig` gains
144+ `chroma_sample_loc` and `mastering_display` (full mdcv SEI) beside `video_signal_type` and
145+ `content_light`; ffprobe reports Main 10, yuv420p10le and BT.2020 PQ/HLG tags; ffmpeg decode equals the
146+ reconstruction (testsrc2, mandelbrot, gradients, intra and GOP); gradient and 0/1023 extremes pass at QP -12..51;
147+ 8-bit bitstream hash pinned (`tests/it/enc8_bitstream_hash.rs`), unchanged. BD-rate vs x265 veryfast 10-bit
148+ 720p: 14.5% (testsrc2), 25.7% (mandelbrot), both below the 8-bit gaps (17.3%, 29.0%). 1080p30 10-bit,
149+ 6 threads, loaded host: ~0.87x realtime.
150+
151+### ec-vp9 decode — P1 (largest cheap win)
152+edith refuses VP9 without VA-API: "there is no software VP9 decoder"
153+(`engine/src/demux.rs:141-161`). That is stale: ec-vp9 reports 1080p frames identical to
154+libvpx 1.15.0 (`lanes/vp9f72.report.md`).
155+- **Done when:**
156+ - edith uses ec-vp9 as its software VP9 backend (playback, proxy, export input), and
157+ the `needs_plugin` refusal is removed for VP9.
158+ - Profile 0 (8-bit 4:2:0) and profile 2 (10-bit 4:2:0) libvpx test vectors are bit-exact.
159+ - 1080p30 profile 0 decodes at ≥ realtime (tile threading allowed). Threading is not
160+ implemented today.
161+ - Dead code is removed: `modes.rs:131` `read_partition`, `tables/mod.rs:16` `TM_PRED`,
162+ and the `allow(dead_code)` in `gen_tables.rs`.
163+ - Stale reports are marked superseded (`vp9inter`, `vp9hbd`).
164+- **Frozen:** further profile 1/3 (4:4:4) work.
165+
166+### ec-vp8 decode — P0
167+edith: software VP8 decode, but only **inside the VA-API plugin** (`engine-hw/src/vpx.rs`),
168+so VP8 fails whenever the plugin is missing.
169+- **Done when:**
170+ - edith calls it from `engine` directly, not only through `engine-hw`.
171+ - The 12/12 IVF fixtures stay bit-exact (`lanes/vp8.report.md`).
172+ - The release-mode guard is fixed: `loopfilter.rs:458` and `:584` slice with only a
173+ `debug_assert`. The `panic!` calls at `intra.rs:114` and `:365` become errors.
174+- **Frozen:** VP8 encode, alpha.
175+
176+### ec-mpeg2 decode — P1 (broadcast .ts, DVD VOB, HDV .m2t, old .mpg)
177+Pure-Rust MPEG-1 and MPEG-2 video decoder (ISO 11172-2 / 13818-2), `CodecId::Mpeg2Video`,
178+registered in the decoder registry; ec-mpegts exposes stream types 0x01/0x02 with it.
179+- **Scope:** Main and 4:2:2 profile, all levels; 4:2:0 and 4:2:2; I, P, B; frame and field
180+ pictures, frame/field/16x8/dual-prime prediction, field or frame DCT, alternate scan,
181+ both intra VLC tables, q_scale_type, DC precision 8-11, MPEG-1 (oddification). Output is
182+ woven frames with the interlace flag, plus repeat_first_field / top_field_first /
183+ progressive_frame in `PictureInfo`. Damaged slices are concealed and the frame is marked
184+ corrupt; no panics, bounded allocation.
185+- **Refusals (named errors):** MPEG-1 D-pictures, scalable/SNR/spatial extension, 4:4:4 and
186+ monochrome chroma formats, pictures above 8192 wide or 8192x4352 area. Pictures before the
187+ first sequence header are dropped; a B picture without its forward reference is dropped.
188+- **ffmpeg-compat quirks reproduced:** skipped B macroblocks are predicted frame-wise;
189+ a zero MV delta returns the predictor without range wrap; invalid cbp 0 and out-of-picture
190+ MVs are not defined by the spec and are not covered. Mid-row slice starts follow the spec
191+ (ffmpeg differs) and are not tested.
192+- **Done when:**
193+ - Byte-exact against ffmpeg (default simple IDCT) on the ffmpeg-encoded matrix
194+ (progressive/interlaced, IPB, MPEG-1, 4:2:2, SD and 1080) and on 1200+ random-syntax
195+ streams (field pictures, dual prime, 16x8, matrices, 4:2:2) in `tests/synth_parity.rs`.
196+ - `cargo test -p ec-mpeg2 -p ec-mpegts -p ec-core --release` passes with `EC_REQUIRE_FIXTURES=1`.
197+ - Fuzz target `decode_mpeg2` (`crates/ec-mpeg2/fuzz`) clean; `tests/robust.rs` passes.
198+ - edith uses it as the software MPEG-2 backend: `engine/src/decode/mpeg2.rs` (with `ivtc.rs`, `deinterlace.rs`), tested by `engine/tests/mpegts.rs` `mpeg2_video_opens_probes_and_decodes_as_ffmpeg_does` (plus seek and interlaced cases), `mpegps.rs` and `ivtc.rs`.
199+
200+### ec-prores decode — P1 (Apple ProRes .mov)
201+Pure-Rust Apple ProRes decoder (SMPTE RDD 36), `CodecId::ProRes`, registered in the decoder
202+registry; ec-mp4 maps the sample entries `apco apcs apcn apch ap4h ap4x` to it.
203+- **Scope:** 422 Proxy/LT/Standard/HQ (output `I210`), 4444 and 4444 XQ (output `I412`, a new
204+ 12-bit 4:4:4 `PixelFormat` in ec-core), progressive and interlaced (TFF/BFF, two field
205+ pictures woven, interlace flag set), all slice sizes (1/2/4/8 MBs), progressive and
206+ interlaced scans, custom luma/chroma quant matrices, per-slice qscale, odd sizes. 8- and
207+ 16-bit alpha is returned as a separate 16-bit plane (`DecodedFrame::alpha`,
208+ `ProResDecoder::last_alpha`); `VideoFrame` itself cannot carry it. Optional slice-parallel
209+ decode (`set_threads`, up to 6, default = available cores).
210+- **Refusals (named errors):** other frame versions / chroma factors, pictures above 16384
211+ wide or 8192x4608 area, malformed headers and slice tables (`Corrupt`). A damaged slice
212+ fails the frame.
213+- **ffmpeg-compat quirks reproduced:** ffmpeg's `ff_prores_idct` (10-bit and 12-bit
214+ simple-IDCT variants with 16-bit wraparound) bit for bit; 10-bit clip [4,1019], 12-bit
215+ [4,4091]; absent luma matrix = all 4, absent chroma matrix = luma matrix; 4:4:4 chroma
216+ block order differs from luma; DC codebook index starts at 5.
217+- **Performance (server host c, EPYC-Rome, 1080p 422 HQ, ~190 Mbit/s):** single-thread 34-40 fps
218+ (shared host), 4 threads 65-79 fps. The 60 fps single-thread target is not met: ~1.5 M
219+ coefficients per frame go through a bit-serial rice/exp-golomb decoder (about 70% of the
220+ time), under `forbid(unsafe_code)` and baseline SSE2 only (no AVX2, no unchecked access).
221+ The IDCT is SIMD (`wide`) and is a minor cost. Re-measured 2026-10-23 on quiet host b (main `bed76a50`, `cargo test -p ec-prores --release --test perf`, 1080p 422 HQ 25 fps, 24 frames noisy testsrc2): 63.7 fps single-thread (set spread 2.7%), 161.1 fps on 4 threads, so the 60 fps single-thread target is met; the numbers above are kept as history.
222+- **Done when:**
223+ - Byte-exact against ffmpeg 8.x `prores_ks`/`prores_aw` output, 1 and 3 threads, on ~55
224+ cases (every profile, alpha, interlaced, noise, saturated, odd sizes, SD, 1080p)
225+ in `tests/ffmpeg_parity.rs`.
226+ - `EC_REQUIRE_FIXTURES=1 cargo test -p ec-prores -p ec-mp4 -p ec-core --release` passes.
227+ - Fuzz target `decode_prores` (`crates/ec-prores/fuzz`) clean for 10 minutes;
228+ `tests/robust.rs` passes.
229+ - edith uses it as the software ProRes backend: `engine/src/decode/prores.rs` (`ProResSeat` wraps `ec_prores::ProResDecoder`) via `engine/src/decode.rs`, tested by `engine/tests/procodecs.rs` `prores_every_profile_opens_decodes_seeks_and_exports` and `engine/tests/prores_export.rs`.
230+
231+---
232+
233+## Audio
234+
235+### ec-aac — P0
236+edith: decode for >2 channels only (stereo goes to symphonia, `engine/src/audio.rs:1900`);
237+encode for AAC export (`engine/src/export.rs:2330`).
238+- **Decode done when:**
239+ - **All** AAC in edith routes through ec-aac, mono and stereo included. Today symphonia
240+ refuses SBR ("aac: aac too complex", `symphonia-codec-aac/src/aac/mod.rs:91-96`), so
241+ stereo HE-AAC files fail to open.
242+ - AAC-LC and HE-AAC v1, mono through 7.1, raw + ADTS, match ffmpeg (correlation ≥ 0.999
243+ per channel). The `sbr_hf.rs:202-226` unwraps become errors.
244+- **Encode done when:** LC CBR at 1–6 and 8 channels passes the existing
245+ `INCUMBENT_BAR` (`tests/oracle.rs:396`); an objective score vs ffmpeg's native AAC
246+ encoder at 128 kbps stereo is recorded (none exists today); rate is within ±5%.
247+- **Frozen:** SBR/PS encode, LTP, SSR, LATM.
248+- **Decision needed (D4):** HE-AAC v2 (Parametric Stereo) decode. Today it outputs the
249+ core only, at half rate (`lib.rs:167`). That is common in low-bitrate broadcast and
250+ streaming audio.
251+
252+### ec-opus — P0
253+edith: the **only** Opus decoder (symphonia has none) and the Opus encoder for MKV export
254+(`engine/src/export.rs:2438`).
255+- **Decode done when:** the 12 RFC 6716 vectors pass (`tests/conformance.rs:414`), are
256+ run and recorded (no pass/fail record exists today), and the RFC 8251 updated vectors
257+ are added and pass. The `celt.rs:2227/2297/2406/2410` unwraps become errors.
258+- **Encode done when:** the SILK packet budget is enforced (`encoder.rs:19`, "D2b");
259+ rate is within ±5%; no FAIL rows remain in the dropout gate (`opus-gate-r1`: reelm@64k).
260+- **Frozen:** PLC/FEC (a dropped frame decodes to silence, which is acceptable for
261+ file-based editing).
262+
263+### ec-vorbis — P0, nearly done
264+edith: decode and `.ogg` export (`engine/src/export.rs:3932`).
265+- **Done when:** the shared gates pass. Quality is already met: 14/14 PASS at equal size
266+ vs libvorbis (`lanes/vorbis-rate-r1.report.md`).
267+- **Frozen:** further floor/psy tuning.
268+
269+### ec-mp3 encode — P0, nearly done
270+edith: MP3 export (`engine/src/export.rs:3832`). Decode stays on symphonia.
271+- **Done when:** the shared gates pass. Quality is already met: CBR matches or beats LAME
272+ on 14 rows; hein@192 is 0.2 dB behind (accepted) (`lanes/mp3lame-r1.report.md`).
273+- **Frozen:** VBR encode (not exposed by edith), decode (symphonia does it).
274+
275+### ec-mp3 Layer I/II decode (MP1/MP2) — P1
276+broadcast and disc audio: DVB, DVD, HDV, VCD, `.mpg`, `.mp2`. Lives in `ec-mp3` beside Layer III, behind the same
277+`Mp3Reader` / `Mp3Decode` / `Mp3Decoder` (the header picks the layer), with `CodecId::Mp2` and `CodecId::Mp1`.
278+- **Scope:** MPEG-1, MPEG-2 LSF (16/22.05/24 kHz) and MPEG-2.5 headers with each layer's own bitrate table;
279+ Layer II allocation tables 3-B.2a..d and the LSF table (measured from an oracle, `scripts/mp2-tables/`),
280+ scfsi, scalefactors, 3/5/9-level grouped samples, requantisation, joint-stereo intensity bound
281+ (`mode_extension`), dual channel, header CRC (allocation and scfsi bits for Layer II, allocation for
282+ Layer I); Layer I allocation and scalefactors; the polyphase bank in f64 with the exact `D[i]` window.
283+ The MPEG-2 multichannel (5.1 BC) extension is ignored: the stereo base is decoded. Output is f32 in `[-1, 1]`
284+ like Layer III. `ec-mpegts` hands MP1/MP2 streams out as `Mp1`/`Mp2` instead of refusing them.
285+- **Refused by name:** free-format streams (bitrate index 0). No encoder.
286+- **Done when:**
287+ - `ffmpeg -c:a mp2` / `mp2fixed` streams at 16/22.05/24/32/44.1/48 kHz, mono and stereo, 8 to 384 kbit/s
288+ (sine, pink noise, chirp) decode within 1e-5 of ffmpeg's float decoder (`mp2float`); libtwolame streams
289+ (joint stereo, stereo, dual channel, mono, with and without CRC) likewise
290+ (`tests/mp2_matrix.rs`).
291+ - 336 hand-built Layer I and II streams (legal random allocation, scfsi, scalefactors and samples; MPEG-1,
292+ LSF and 2.5; every table; stereo, joint stereo with each bound, dual, mono; CRC on and off) match ffmpeg's
293+ `mp2float`/`mp1float` to a few 1e-5 (full-scale noise in every band; ffmpeg's float synthesis is the
294+ coarser side) and its fixed-point decoder to 1 LSB of s16.
295+ - A flipped allocation bit in a CRC-protected frame is reported as a CRC error; free-format frames are
296+ refused by name; damaged and truncated frames never panic (`tests/mp2_matrix.rs`).
297+ - Layer III tests pass unchanged; the shared gates pass.
298+- **Layer I coverage:** ffmpeg has no MP1 encoder and no clearly licensed MP1 sample was at hand, so Layer I is
299+ tested on the hand-built frames above only.
300+- **Frozen:** MPEG-2 multichannel and the MPEG-2 extension bit streams, free-format scanning, a Layer I/II encoder.
301+
302+### ec-ac3 decode — P0
303+edith: AC-3 and E-AC-3 decode (`engine/src/audio.rs:2091`).
304+- **Done when:** AC-3 and E-AC-3 independent substreams match ffmpeg on
305+ `real_library.toml`, through 5.1. The shared gates pass.
306+- **Frozen:** encode (unused), Atmos JOC, enhanced coupling.
307+- **Decision needed (D5):** E-AC-3 dependent substreams (7.1). Today only the first
308+ substream decodes, so 7.1 becomes 5.1.
309+
310+### ec-truehd decode — P1 candidate
311+edith does not decode TrueHD at all, so Blu-ray remux tracks have no audio. ec-truehd is
312+bit-exact on a 7.1 remux (`ec-truehd/src/lib.rs:1-12`).
313+- **Done when:** edith decodes TrueHD through it from MKV; the 2/6/8-channel substreams
314+ are bit-exact vs ffmpeg; the shared gates pass. **Frozen:** Atmos (substream 4), encode.
315+- **Decision needed (D6):** whether Blu-ray remuxes are a target for edith.
316+
317+---
318+
319+## Containers
320+
321+### ec-mpegts demux — P1 (AVCHD camcorder files and broadcast/recorder .ts)
322+edith: opens `.mts`/`.m2ts` (192-byte BDAV packets) and `.ts` (188/204) through the same
323+`ec_core::Demuxer` seat as `ec-mp4` and `ec-matroska`. New crate; wiring it into `engine/src/demux.rs`
324+is the integration lane (edith is untouched by this crate's lane).
325+- **Scope:** packet size by sync stride (188, 192, 204) with resync after damage; adaptation field,
326+ PCR, discontinuity; PAT/PMT with CRC32 (first program by default, all listed, `with_program`),
327+ PMT changes mid-stream; PES reassembly with 33-bit PTS/DTS unwrapped to monotonic `i64`, unbounded
328+ video PES, continuity-counter checks and duplicate drop (damaged PES flagged `corrupt`).
329+ Streams: H.264 and HEVC (Annex-B access units, keyframe from IDR/IRAP, recovery-point SEI or
330+ `random_access_indicator`; `avcC`/`hvcC` extradata and a length-prefixed mode), AAC ADTS (frames split,
331+ AudioSpecificConfig derived), AC-3 and E-AC-3 (0x81/0x87/0x84/0xA1 and private data with the 0x05/0x6A/0x7A
332+ descriptors; syncframes split, dependent substreams joined), MPEG audio layers I, II and III (as `Mp1`, `Mp2`,
333+ `Mp3`; decoded by ec-mp3), HDMV LPCM
334+ (header parsed, 16-bit as `PcmS16Be`, 20/24-bit as `PcmS24Le`, odd channel counts de-padded), HDMV PGS
335+ (`Pgs`). Start offset per stream, duration from the file tail, bisection seek to the video keyframe at
336+ or before the target.
337+- **Exposed:** MPEG-1/2 video (stream types 0x01/0x02) as `CodecId::Mpeg2Video`, one packet per coded picture (`tests/mpeg2.rs`); decoding is `ec-mpeg2`'s job.
338+- **Refused by name** (listed in `tracks()` with a reason, never silently dropped, never decoded wrong):
339+ AAC LATM/LOAS (`aac_latm`), VC-1, IGS, TextST, teletext, and every other stream type. DTS and DTS-HD (lane `dts`), TrueHD (lane `tstruehd`) and DVB subtitles (lane `dvdsubs`) are now exposed, not refused.
340+ Interlaced (PAFF/MBAFF) H.264 is split on PES boundaries only; access unit delimiters inside a PES split
341+ progressive H.264 and HEVC only.
342+- **Done when:**
343+ - Packets are byte-exact, with sizes, pts, dts and keyframe flags equal to `ffprobe -show_packets`,
344+ on ffmpeg-made 188-byte `.ts` and 192-byte `.m2ts`: H.264 progressive and MBAFF, HEVC, AAC, AC-3 and
345+ E-AC-3 at 32/44.1/48 kHz, MP2, MP3, LPCM (`pcm_bluray`, against ffmpeg's s16be decode), two programs, a PTS
346+ wrap, an audio-only stream (`tests/ffmpeg_parity.rs`); duration within one frame; MP2 is exposed as `Mp2`.
347+ - A seek then read equals the sequential read from the landing offset, packet for packet, at several
348+ targets in `SyncBefore` and `Exact` modes, and lands on the last keyframe at or before the target.
349+ - Truncated, overwritten, cut and garbage-prefixed files open, read on, count the damage in `stats()` and
350+ flag it `corrupt`; seeded mutation of the fixtures never panics (`tests/robust.rs`).
351+ - Hand-built streams cover PCR on its own PID, two access units in one PES, 204-byte packets, duplicate
352+ packets, PMT change, bad CRC, refusals and PGS (`tests/synthetic.rs`); the committed tiny fixtures
353+ match ffmpeg's bytes without ffmpeg (`tests/committed.rs`).
354+ - Fuzz targets `demux_ts` and `ts_parts` (`crates/ec-mpegts/fuzz`): 1 CPU-hour each, no panic, hang or OOM. **Done 2026-10-20:** 6.27M (`demux_ts`) and 7.51M (`ts_parts`) runs in 3600 s each on server host a, clean.
355+ - The shared gates pass; `cargo test -p ec-mpegts --release` passes with `EC_REQUIRE_FIXTURES=1`.
356+- **Frozen:** LATM, teletext, SCTE-35,
357+ PCR-driven clock recovery.
358+
359+### ec-mpegts PS — MPEG-1 system / MPEG-2 program streams (`.mpg`, `.mpeg`, `.vob`, `.m2p`) and raw `.m2v`/`.mpv`
360+
361+- **Scope:** `PsDemuxer` in `ec-mpegts` (`src/ps.rs`, `src/psvideo.rs`), the same `Demuxer` API as `TsDemuxer` (tracks, streams,
362+ `next_packet`, `seek` SyncBefore/SyncAfter/Exact, `stats`, `duration_secs`), reusing its PES, framing and refusal machinery.
363+ Pack headers (MPEG-1 and MPEG-2, SCR), system header, PSM stream types, padding, program end code, private_stream_2 (skipped).
364+ Video: MPEG-1/2 (`Mpeg2Video`), H.264/HEVC (PSM or sniffed) as Annex-B. Audio: MP1/MP2/MP3, AAC ADTS, AC-3 (private_stream_1
365+ 0x80-0x87), DVD LPCM 16/20/24-bit (0xA0-0xA7; 20/24-bit exposed as `PcmS24Le`). Raw MPEG-1/2 video elementary streams open in the
366+ same type (indexed once at open; timestamps from the frame rate). 33-bit PTS wrap unwrapped; an SCR step back of more than
367+ 0.5 s, or a step forward of more than 1 s, between consecutive packs (concatenated VOBs, cell joins) starts a new epoch
368+ (`stats().discontinuities`); at open each later epoch is shifted so its first picture is shown where the previous epoch's
369+ last picture ends (video presentation times, audio shares the shift), so the timeline is continuous, the duration is the sum
370+ of the segments and seeks are exact on both sides of a join. A `.vob` that
371+ starts mid-GOP opens and delivers from the first keyframe on.
372+- **Refused by name:** DTS (`dts`), other private_stream_1
373+ substreams, LATM, and every PSM stream type the family cannot decode. VobSub subpictures (`DVD subtitles (VobSub)`) are now exposed (lane `dvdsubs`), not refused.
374+- **Limits:** 20/24-bit DVD LPCM seeks may land mid 2-frame group; PAFF field pictures are one packet per picture header;
375+ joins are found from the SCR only (a PTS restart without an SCR restart is not seen) and the alignment needs a video picture on both sides; files over 96 MiB check SCR resets by sampling (backward steps only); pictures with no PES
376+ timestamp get derived dts/pts (flagged internally; MPEG-1/2 pictures take the display order of the GOP before; after a seek reading starts at the keyframe before the landing one so the times equal the sequential read's); after a seek the pictures that share the
377+ landing PES but precede the keyframe are dropped.
378+- **Done when:**
379+ - Packets equal `ffprobe -show_packets` / `ffmpeg -c copy -f data` (bytes, sizes, pts, dts, keyframe flags), duration within one
380+ frame, seek-then-read equals the sequential read, on ffmpeg-made `-f mpeg` (MPEG-1 and MPEG-2), `-f vob`, `-f dvd` (nav packs),
381+ interlaced, PTS wrap, H.264+MP3, DVD LPCM 16/24-bit, raw `.m2v`/`.m1v` (`tests/ps.rs`; committed fixtures without ffmpeg in
382+ `tests/committed_ps.rs`).
383+ - Concatenated VOBs (also through the sampled check), mid-GOP start, injected VobSub/DTS/nav/padding, truncation at every
384+ offset prefix-consistent, seeded mutation never panics (`tests/ps.rs`).
385+ - Fuzz target `demux_ps`, 5 min smoke on a server, no panic, hang or OOM.
386+ - The TS tests are unchanged; the shared gates pass; `cargo test -p ec-mpegts --release` passes with `EC_REQUIRE_FIXTURES=1`.
387+
388+## Dependency replacement — only rav1e and symphonia stay
389+
390+**Goal:** edith's `Cargo.lock` contains no third-party media crate except **rav1e** and
391+**symphonia**. Every other codec, container, subtitle, image and VA-API crate is an ec-* crate.
392+
393+**Stays:**
394+- `rav1e` (AV1 export; decided 2026-10-15, see **ec-av1 encode**). After wave 3 removes
395+ `image`, rav1e has one owner only: `engine`'s AV1 export. It no longer arrives via `ravif`.
396+- `symphonia`, `symphonia-core` (decided 2026-10-15): audio probing and MP3/FLAC/ALAC/WAV
397+ decode. The one exception is `symphonia-codec-aac`, which goes: all AAC routes through
398+ ec-aac (the HE-AAC fix under **ec-aac**). Keep symphonia's `aac` feature off so it
399+ does not come back.
400+- Not media: `gpui` (UI; it also brings `proc-macro-error2`), `pipewire`/`libspa-sys`
401+ (audio output), `libc`, `libloading`.
402+
403+**Done for the whole goal when:**
404+- `cargo tree -p engine -p engine-hw -p engine-audio -e normal` lists none of:
405+ `symphonia-codec-aac`, `mp4`, `cros-codecs`, `cros-libva`, `gbm`, `oxideav-*`, `image`,
406+ `ravif`, `flacenc`, `hound`, `miniz_oxide`.
407+- A test in edith fails if any of them comes back, in the style of the existing window-guard
408+ tests. The test allow-lists `rav1e`, `symphonia` and `symphonia-core` by name, and only as
409+ direct dependencies of `engine`.
410+- `edith/vendor/` holds nothing but `proc-macro-error2` (or nothing, once gpui no longer needs
411+ the patch), and the matching `[patch.crates-io]` entries are gone.
412+
413+**Done for each swap when:**
414+1. The old crate is gone from `Cargo.lock`.
415+2. Every existing edith test still passes, with no test deleted or `#[ignore]`d to get there.
416+3. Parity is shown on `real_library.toml` against the crate being replaced:
417+ - **demux:** identical packet bytes, timestamps and stream metadata;
418+ - **mux:** ffprobe-clean, and decodes identically in ffmpeg;
419+ - **decode:** sample/pixel-equal output.
420+4. The ec-* crate it now depends on passes the shared gates above (it becomes P0).
421+
422+### Wave 1 — one-call swaps
423+| Replace | With | Gap to close |
424+|---|---|---|
425+| `miniz_oxide` | ec-inflate | none; swap `demux.rs:2363` to `inflate_zlib(input, LIMIT)` |
426+| `hound` | ec-riff `WavWriter` | RF64 for > 4 GB WAV exports (unverified today) |
427+| `flacenc` | ec-flac encode | match flacenc's compression level and bit depths edith exports |
428+
429+### Wave 2 — the patched forks (highest maintenance risk)
430+| Replace | With | Gap to close |
431+|---|---|---|
432+| `mp4` (vendored, patched) | ec-mp4 | mux sample entries `av01`, `ac-3`, `Opus`/`dOps`, `alac`; the mp4a version-1 esds quirk the vendored patch fixes; rotation, edit lists and stss/ctts parity with `demux.rs:304-377`, `:4206-4236`, `:1196-1226` |
433+| `cros-codecs`, `cros-libva`, `gbm` (vendored, patched) | ec-hw + ec-va | rewrite `engine-hw` onto ec-hw, keeping each local fix as an ec-hw regression test: open-GOP H.264 `frame_num` gap fill, HEVC Main 10 decode contexts, radeonsi probe size, HEVC encode, the per-cache-line flush, the `munmap` leak, and `slice_fix.rs` (`cabac_zero_word`). Buffer export without the `gbm` crate. |
434+
435+### Wave 3 — subtitles, stills, Ogg mux
436+| Replace | With | Gap to close |
437+|---|---|---|
438+| `oxideav-subtitle` | ec-subs | map its cue IR to edith's `Segment` (`subtitle.rs:522`, `:609`) |
439+| `oxideav-ass` | ec-ass | same, plus edith's handling of `Segment::Raw` override tags (`subtitle.rs:559`, `:611`) |
440+| `oxideav-sub-image` | ec-pgs | the epoch/display-set handling at `subtitle.rs:90-114` |
441+| `oxideav-ogg`, `oxideav-core` | ec-ogg | Opus pre-skip and Vorbis header lacing parity (`mux.rs:1715-1731`, `export.rs:3957`) |
442+| `image` | ec-image | pixel-format mapping to edith's frames, in `engine` (`decode.rs:1711`, `:1746`, `:1825`) **and** `app`; EXIF orientation applied by edith as today |
443+
444+### Optional consolidation (first-party code, not a dependency)
445+edith's own Matroska reader/writer (`demux.rs`, `mux.rs`) could move onto ec-matroska. Gap:
446+Projection roll, Cues reorder tolerance, V_AV1/HEVC CodecPrivate parity. Not required for the goal.
447+
448+---
449+
450+## Open decisions (for the owner)
451+
452+| # | Question | Effect if yes |
453+|---|---|---|
454+| ~~D1~~ | H.264 interlaced + High10 decode? | **High10 done (lane/h264hi10)**: ec-h264 decodes High 10 (4:2:0 progressive, 9/10-bit, CAVLC and CABAC, intra/inter/weighted prediction) byte-exact against ffmpeg `yuv420p10le`, output as `I010` like HEVC Main 10. **PAFF done (lane/h264interlace)**: field pictures (field POC, field DPB and reference marking, field MV/ref handling, chroma mv offset, field deblocking, temporal direct and implicit weights with field POCs, field scans and CABAC field contexts) byte-exact against the JVT vectors, frames output woven with `VideoFrame.interlace` set. **MBAFF done (lane/h264mbaff)**: pair addressing and per-pair field flag (CAVLC and CABAC, with the 7.4.4 inference and skipped-top handling), Table 6-4 neighbour derivation for every reader, field-MB geometry, doubled reference lists, MV/ref/mvd scaling, implicit weights and temporal/spatial direct with field MBs and every colocated case, constrained intra with partly available left samples, mixed-edge deblocking. All 24 JVT MBAFF vectors (CVMA*, CAMA*, cama*_vtc, CAMP_MOT_MBAFF, CAPAMA3, CVMAPAQP3, FRExt2/4, MR9_BT_B) bit-exact, plus x264 `--interlaced` tff/bff sweeps (CABAC/CAVLC, B, direct, weightp, 8x8dct, slices, High 10, 576 and 1080) byte-exact against ffmpeg (lane/h264mbaff, 2026-10-20). **High 4:2:2 done (lane/h264hi422)**: 2x4 chroma DC (own transform with QP'c+3, nC -2 CAVLC tables, CABAC 8-coefficient DC), 8 chroma AC blocks per component, 8x16 chroma intra prediction (DC rules, plane with yCF 4), full-height chroma MC, the extra chroma horizontal deblock edges (frame and MBAFF), I_PCM; all 18 Sony Hi422FR/Hi422FREXT vectors (progressive, PAFF, MBAFF; 8 and 10 bit) bit-exact, plus x264 high422 sweeps at 8 and 10 bits (intra, long-GOP, CABAC/CAVLC, 8x8dct, weightp, cqm, MBAFF) byte-exact against ffmpeg; output `I422`/`I210`. Monochrome stays refused. |
455+| ~~D2~~ | Replace rav1e with ec-av1's encoder? | **Decided 2026-10-15: no.** rav1e stays; the ec-av1 encoder is frozen |
456+| ~~D3~~ | Inter-frame HEVC export? | **Decided 2026-10-15: yes.** HEVC software decode is also P0 |
457+| ~~D4~~ | HE-AAC v2 (PS) decode? | **Yes (orchestrator, 2026-10-15)**: one lane after AAC routing |
458+| ~~D5~~ | E-AC-3 7.1 dependent substreams? | **Yes (orchestrator, 2026-10-15)**: one lane |
459+| ~~D6~~ | TrueHD / Blu-ray remuxes as a target? | **Yes (orchestrator, 2026-10-15)**: ec-truehd is P1, wiring only |
460+| ~~D7~~ | Speed targets above ("≥ realtime 1080p30") right for this machine? | **Kept (orchestrator, 2026-10-15)**: measured on the local 12-core machine, recorded in `lanes/bench.md` |
461+| ~~D8~~ | HEVC RExt decode (4:2:2 10-bit: Sony XAVC HS, Canon, Panasonic cameras)? | **Done 2026-10-19**: 4:2:2 at 8/10 bit byte-exact vs ffmpeg on the Sony RExt vectors and generated clips (`hevc422`, merge `8b9d547e`); edith opens it (edith `f291196`). 4:4:4 and 12-bit still refused by name |
462+
463+## Done log
464+
465+(one line per crate: `DONE <date> <crate> <scope>`)
466+
467+- DONE 2026-10-17 ec-truehd decode: 2-, 6- and 8-channel PCM substreams bit-exact vs ffmpeg `-f s32le` (2.0 and 5.1 fixtures at 16/24-bit, committed; 7.1 from a local remux by path, not committed; `crates/ec-truehd/tests/it/fixture_exact.rs`). Report: `lanes/truehdexact.report.md`.
468+- DONE 2026-10-17 ec-ac3 decode: AC-3 and E-AC-3 through 5.1 at correlation >= 0.999 per channel on the 2 real_library entries (`crates/ec-ac3/tests/it/real_library.rs`); E-AC-3 7.1 dependent substreams (D5) on the matrix fixtures. Updated 2026-10-18: AC-3 zero-bit dither is now ffmpeg's lagged-Fibonacci generator, so per-channel correlation vs ffmpeg is 1.000000 on 10 s pink-noise fixtures at 5.1 448k, 2.0 192k and 5.1 640k (`ac3parity`, merge `a99a45ab`, `crates/ec-ac3/tests/it/ffmpeg_parity.rs`). Bit-exactness is not claimed. AC-3 decode speed: 323.2x realtime, local, best of 5 (`benchrows`, merge `e188b83b`, `lanes/bench.md`). Reports: `lanes/truehdexact.report.md`, `lanes/ac3parity.report.md`.
469+- DONE 2026-10-18 ec-h264 decode and encode: JVT 26 bit-exact, 9 refused by name with tests (`h264refusals`, `refusals.rs`); real_library 15/15 (`h264reallib`); encode recon 28/28 md5 vs ffmpeg, rate within 5%, BD-rate +12.46% vs x264 veryfast (`h264encrc`, `h264encspeed2`). Edith tests are on codecs-integration.
470+- DONE 2026-10-18 ec-opus decode and encode: RFC 6716 12/12 and RFC 8251 12/12, SILK packet budget enforced, rate +0.00%, reelm@64k dropout gate met (`opusgate`).
471+- DONE 2026-10-18 ec-vorbis: 14/14 PASS vs libvorbis at equal size (`vorbis-rate-r1`); fuzz 1 h clean (`fuzz1haudio`).
472+- DONE 2026-10-18 ec-mp3 encode: CBR matches or beats LAME on 14 rows, hein@192 0.2 dB behind accepted (`mp3lame-r1`).
473+- DONE 2026-10-18 ec-h265 encode: intra-only and inter output decodes in ffmpeg identical to the encoder's reconstruction (`hevcencrc`, `hevcencrcpar`, `hevc-gop-roundtrip.sh`); rate control within 0.2% at 1000/2500/5000 kb/s and within 0.02% on 60 s constant-target runs (`hevcencrcpar`, `hevcencspeed5`); BD-rate vs x265 veryfast at most +21.16% YUV, bitrate mode (`hevcencrcpar`; constant QP at most +18.8%, `hevcencspeed4`); intra-only BD-PSNR at least -1.0 dB vs x265 intra on all three clips, with `-tune psnr` (`hevcmisc`, merge `7d8711af`); 1080p30 at 40.16 fps = 1.34x realtime on 6 threads, local (`hevcencspeed5`, merge `8fb9fb6c`; bitrate mode 51.9 fps, `hevcencrcpar`). Local machine per D7. Main 10 encode stays open, only if edith starts exporting 10-bit/HDR.
474+- DONE 2026-10-18 ec-aac encode: LC CBR passes `INCUMBENT_BAR` at 1-6 and 8 channels (`aacencbar`, merge `5241ffbe`; the 8-channel bar is ffmpeg's native AAC, a stricter proxy than rusty_aac, which refuses more than 6 channels, margin 0.0002); objective score vs ffmpeg native AAC at 128 kbps stereo recorded (`aacgates2`); rate within ±5% (`aacgates2`: +0.9 to +4.4% before the ADTS-header budget fix; `aacencbar`: +0.6 to +1.0% after it). Edith tests are on codecs-integration. Frozen items unchanged.
475+- DONE 2026-10-18 ec-av1 decode (8-bit and 10-bit 4:2:0): AOM profile 0 242/242 exact (`av1svc`, merge `a62e7dc2`); 1080p30 4.03x realtime at 6 threads (`av1bench6`); `decode_stream` and `parse_obu` 1 CPU-hour clean on the final tree, `decode_stream` re-run from real seeds at cov 28.7k (`fuzzre-a`, merge `8936fe06`); worker panics return an error (`av1panichang`); workspace clippy `-D warnings` clean on main `f43403af`. Non-4:2:0 stays refused by name.
476+- DONE 2026-10-18 ec-vp8 decode: 12/12 IVF fixtures byte-exact vs ffmpeg, malformed input returns errors (`vp8guards`); 1080p30 5.24x realtime (`benchrows`); edith decodes VP8 WebM from `engine` directly and the real_library `vp8_webm` entry matches ffmpeg (edith `codecs-integration` merge `fe21ed4`, `real_library_video.rs`).
477+- DONE 2026-10-18 ec-vp9 decode (profile 0): md5 = ffmpeg on the fixtures and the real_library `vp9_opus_mp4` entry (edith merge `fe21ed4`); 1080p30 5.50x realtime at 1 thread (`benchrows`); `decode_frame` and `decode_stream` 1 CPU-hour clean on the final tree (`fuzzre-a`, merge `8936fe06`).
478+- DONE 2026-10-18 ec-aac decode: LC mono to 7.1 correlation 1.000000 vs ffmpeg (`aacdecmulti`); HE-AAC v1 and v2 mono to 5.1 correlation >= 0.99997 vs ffmpeg, `decode_he` 1 CPU-hour clean (`aachev1`, merge `18d1db47`); LC decode targets 1 CPU-hour clean (`fuzzre-c`, merge `f43403af`); bench row (`benchaudio`, merge `1cd59b57`); edith routes every AAC stream to ec-aac with seek tests incl. HE-AAC (edith merge `e0e8922`). ec-aac encode also meets `NOISY_BAR` at 128k/192k (`aacencnoise`, merge `f05345dc`).
479+- DONE 2026-10-18 ec-mp4: demux and mux parity per the Wave 2 swap criteria (`mp4alac`, `swapmp4`); rotation matrices snap within 0.5 degrees and match ffmpeg in edith (`rotation_parity.rs`, edith merge `61bfe00`); real_library `mp4_h264_aac`, `mp4_phone_h264`, `mp4_mov_text`, `mp4_heaac` packet parity (edith merge `fe21ed4`, `real_library_containers.rs`); bench row (`benchaudio`).
480+- DONE 2026-10-18 ec-matroska: 7 fuzz targets 1 h clean (`fuzzmkv`); unknown-length clusters wider than the read window keep every block (`reallib`, merge `edea19ce`; edith `mkv_unknown_cluster.rs`); real_library Matroska entries match ffmpeg packets; zlib-compressed PGS and VobSub tracks on 2 real_library keys match ffprobe on 4073 packets (edith merge `8a50186`, `real_library_zlib.rs`). Bench row 1.81 M packets/s, packets = ffprobe (`benchrest`, merge `f1eb8728`). `demux_packets`, `seek` and `open_tracks` 1 CPU-hour clean on the final demux code (`fuzzre-d`, merge `6bc4c954`).
481+- DONE 2026-10-18 ec-riff: WAV/RF64 writer replaces hound (Wave 1); real_library `wav_pcm16` matches ffmpeg (edith merge `fe21ed4`, `real_library_audio.rs`); bench row (`benchp1`).
482+- DONE 2026-10-18 ec-subs, ec-pgs: Wave 3 swaps met; fuzz 1 h clean; bench rows (`benchp1`, `pgsbudget`). ec-pgs `compose` and `segments` re-run 1 CPU-hour clean after `pgsbudget` (`fuzzre-d`, merge `6bc4c954`).
483+- DONE 2026-10-18 ec-ass: Wave 3 swap met; timing, order and text match ffmpeg on 7 scripts, `\t(...)` kept as one verbatim tag (`assparity`, merge `569e2d0b`). `overrides` and `events` re-run 1 CPU-hour clean after the splitter change (`fuzzre-d`, merge `6bc4c954`).
484+- DONE 2026-10-18 ec-image: Wave 3 swap met in `engine` and the app's own PNG writing; `image` stays only under app -> gpui (exception 2026-10-16). Bench rows: PNG decode 105 Mpix/s and encode 25 Mpix/s bit-exact vs ffmpeg, JPEG decode 225 Mpix/s within max delta 4 of libjpeg (`benchrest`, merge `f1eb8728`).
485+- DONE 2026-10-18 ec-inflate: Wave 1 swap met (`demux.rs` zlib through `inflate_zlib`); fuzz 1 h clean (`fuzzinflate`, `fuzz1hcontainers`, no source change since); zlib-compressed Matroska PGS and VobSub tracks on 2 real_library keys inflate to ffprobe's bytes, 4073 packets (edith merge `8a50186`, `real_library_zlib.rs`); 288 MB/s on one 64 MiB stream and 320 MB/s on 20k 3 KiB blocks, md5 = zlib (`benchrest`, merge `f1eb8728`).
486+- DONE 2026-10-18 ec-flac encode (the part on edith's path; edith decodes FLAC with symphonia): Wave 1 flacenc swap met at every level and depth, 12/12 (`flacparity`); fuzz 1 h clean (`fuzzflac`, `fuzz1haudio`); the owner's audio on 3 real_library keys (stereo and 5.1, 16 and 24 bit, 60 s each) written through `engine::flac_write` decodes in ffmpeg to the input sample for sample, with STREAMINFO MD5 right (edith merge `3696025`, `real_library_flac.rs`); encode 152x realtime stereo and 39x 5.1 24-bit, decode 627x and 149x (`benchrest`).
487+- DONE 2026-10-18 ec-hw, ec-va: every carried cros-codecs/gbm fix has a regression test (`hwregress`); parameter builders 1 h fuzz clean (`hwfuzz`, merge `3c08b0ce`); VA-API decode/encode bench rows on the local GPU with every picture md5 = ffmpeg (`benchhw`, merge `9e1d91cd`). ec-va has no bitstream parser, so G2 is N/A for it (orchestrator, 2026-10-18). ec-hw does not link on the servers (no libva); its gates run locally.
488+
489+### Milestones (not crate DONE lines; the per-crate gates still apply)
490+- 2026-10-16 dependency replacement reached on edith `codecs-integration`: `cargo tree -p engine -p engine-hw -p engine-audio -e normal` lists none of the banned crates; `vendor/` holds only `proc-macro-error2`; `engine/tests/dependency_guard.rs` enforces it (PENDING_WAVE2 empty). Lanes: swapflacenc, swapsubs, swapogg, swapimage, swapimage2, swapmp4, depguard, enginehw (+ ec-side mp4mux, mp4demux, imagegaps, hwfixes, hwgaps). On edith `main` since `468d96d` (2026-10-18).
491+- Exception (orchestrator, 2026-10-16): `image` remains in the **app** crate only, because gpui 0.2.2 exposes `image` types in its API (`RenderImage`, `Frame`). The goal's crate list covers `engine`, `engine-hw`, `engine-audio`, which are clean. The app's own PNG writing goes through ec-image.
492+- Correction (orchestrator, 2026-10-16): the wave-3 row for `oxideav-ogg` cites Opus pre-skip at `mux.rs:1715-1731`; that is the Matroska `A_OPUS` writer, and edith has no Ogg-Opus writer. Ogg parity was shown on Vorbis only (lanes/edith-swapogg.report.md).
493+
494+### Criteria met, crate not yet DONE (2026-10-18)
495+
496+The crate's other criteria still apply. Bench rows are local (D7), best of 5 unless stated.
497+
498+- **ec-aac decode (met):** AAC-LC mono, stereo, 5.1 and 7.1, raw ADTS and m4a: per-channel correlation 1.000000 vs ffmpeg (`aacdecmulti`, merge `0ad0ea98`, `crates/ec-aac/tests/it/multichannel_parity.rs`). HE-AAC v1 is not covered by this lane. Still open: edith routing and the HE-AAC v2 refusal check in mp4.
499+- **ec-h265 decode (met):** Dolby Vision profile 8.x base layer decodes bit-exact vs ffmpeg with RPU NAL units (type 62) ignored (`hevcmisc`, merge `7d8711af`). mp4 `dvcC`/`dvvC` boxes are not covered.
500+- **ec-vp8 decode (met):** bench row, 1080p30 libvpx 4 Mb/s: 157.30 fps, 5.24x realtime, md5 = ffmpeg (`benchrows`, merge `e188b83b`, `lanes/bench.md`).
501+- **ec-vp9 decode (met):** 1080p30 profile 0, 4 tile columns: 165.13 fps, 5.50x realtime at 1 thread, md5 = ffmpeg (`benchrows`, merge `e188b83b`). Bench-row criterion only.
502+- **ec-ac3 decode (met):** bench row, AC-3 5.1 448 kb/s: 322.2x realtime (`ac3benchrerun`, local best of 5). Parity re-run on the 60 s bench clip after `ac3parity`: min per-channel correlation 1.000000 vs ffmpeg 8.1.3 (the earlier 0.981 FAIL row predates the dither fix). `lanes/bench.md`, `lanes/ac3benchrerun.report.md`.
503+- **ec-av1 decode (met):** 1080p30 8-bit 4:2:0 at or above realtime with `EC_AV1_THREADS` > 1: 3.93x at 4 threads, 4.03x at 6 threads, quiet local machine, md5 = ffmpeg (`av1bench6`, merge `5939a7de`, `lanes/av1bench6.report.md`).
504+- **ec-av1 decode (met):** AOM conformance profile 0 at 242/242 exact (611 shown frames), including the two spatial-SVC vectors via scaled-reference prediction and libaom's last-shown-frame-per-TU output policy (`av1svc`, merge `a62e7dc2`, `lanes/av1svc.report.md`).
505+- **ec-av1 decode (met):** 1 h fuzz on the final tree: `decode_stream` 960,909 runs / 3601 s and `parse_obu` 21,470,442 runs / 3601 s, both clean; the run1 crashes are fixed with replay tests (`av1fuzzfinal`, merge `96ae4d45`, `lanes/av1fuzzfinal.report.md`).
506+- **Wave 1 flacenc swap (met):** ec-flac encode at every level and bit depth edith exports decodes identically in ffmpeg, 12/12 (`flacparity`, merge `d376bf2c`, `crates/ec-flac/tests/level_depth_parity.rs`).
507+- **Wave 2 mp4 swap (met):** ec-mp4 mux of `av01`, `ac-3`, `Opus`/`dOps` and `alac` sample entries is ffprobe-clean and decodes identically in ffmpeg (`mp4alac`, merge `fde0fa1e`).
508+- **Wave 2 cros-codecs swap (met):** every carried cros-codecs/gbm local fix has an ec-hw regression test; HEVC entry points past 32; display-free HEVC parameter building with a `build_parameters` fuzz target (`hwregress`, merge `55d7a6c5`).
509+- **Wave 3 swaps (met):** ec-subs, ec-ass, ec-pgs, ec-ogg and ec-riff have bench rows (`benchp1`, merge `c0347b7f`); ec-pgs caps queued display sets at 8 and rasterizes on take, 442x realtime (`pgsbudget`, merge `e7e8c552`); edith tests cover WebVTT/SRT/ASS in Matroska, Ogg Opus import, PGS `.sup` vs ffmpeg and zlib-compressed Matroska tracks (edith `codecs-integration` merge `dcf9352`).
510+- **ec-hw fuzz (met):** H.264, VP9, AV1 and HEVC VA-API parameter builders are display-free and each fuzzed 1 h with 0 crashes (3.7M, 45.9M, 14.0M and 4.8M runs); the one crash found, an H.264 PPS scaling-list delta overflow in `ec-h264-syntax`, is refused as corrupt with a regression test (`hwfuzz`, merge `3c08b0ce`).
511+- **ec-av1 decode robustness (met):** a panicking worker (frame job, wavefront recon, loop-filter pipeline) fails the decode with an error instead of hanging, and the next decode in the process works; `tests/worker_panic.rs` (`av1panichang`, merge `c479e778`).
512+
513+### Plan status (orchestrator, 2026-10-18)
514+
515+Each execution-plan phase, checked against the tree on edith_codecs `d5ca7236` and edith `codecs-integration` `f4d5e8a`:
516+
517+- **Phase 0, 1 (gates, fuzz scaffolding, edith wins, wave 1):** done. Every crate on edith's path has fuzz targets, each run 1 CPU-hour on its final code (latest re-runs: `fuzzre-a` to `fuzzre-d`, `truehdrecover`).
518+- **HEVC decode track:** every Done-when item met (conformance 147/147 streams, refusals by name, 1080p 5.18x and 4K 1.52x, edith software backend), including the phone-clip row (public-domain Android and iPhone originals, plus a synthetic 10-bit HLG clip; below).
519+- **HEVC encode track:** DONE line above.
520+- **Phase 2 (AV1 split, threads):** done; the largest source file in any crate is 4848 lines (`ec-av1/src/decode/rect.rs`); AV1 DONE line above.
521+- **Phase 3 (waves 2, 3, dep guard):** done; `cargo tree -p engine -p engine-hw -p engine-audio -e normal` on `f4d5e8a` lists no banned crate (only rav1e and symphonia remain, as decided); `engine/tests/dependency_guard.rs` enforces it; `vendor/` holds only `proc-macro-error2`.
522+- **Phase 4 (per-crate gates):** DONE lines for ec-h264, ec-h265 encode, ec-av1, ec-vp8, ec-vp9, ec-aac (decode and encode), ec-opus, ec-vorbis, ec-mp3 encode, ec-ac3, ec-truehd, ec-mp4, ec-matroska, ec-riff, ec-subs, ec-pgs, ec-ass, ec-image, ec-inflate, ec-flac encode, ec-hw/ec-va.
523+- **All items met** (2026-10-18). ec-h265 phone clips and ec-ogg's real_library row are resolved below on public-domain media. The 10-bit HDR phone row uses a synthetic clip.
524+
525+### Still open (2026-10-18)
526+
527+- **G6 note (orchestrator, 2026-10-18):** the speed rows live in `lanes/bench.md` (D7); `lanes/bench.log` is old build output and is not evidence.
528+- **ec-ogg real_library row (resolved 2026-10-18, owner rule "use public-domain media"):** four public-domain and CC0 Commons recordings (three Vorbis, one Opus, 90–148 s) sit in the local gitignored manifest. `crates/ec-ogg/tests/real_library.rs` (ignored, local only) demuxes every packet and matches ffmpeg on count, sizes, payload bytes, header block, pts and granule ends for all four (`oggreal`, merge `26630dce`). Demux only: decode parity is covered by the ec-vorbis and ec-opus gates. ec-flac decode is still not on edith's path (symphonia, kept 2026-10-15).
529+- **ec-truehd (resolved 2026-10-18):** a refused access unit now restores the decoder state, so later units decode exactly as if it were absent (233 corruptions, 158,367 later units equal; `refused_au_recovery.rs`). `decode_stream` 1 CPU-hour clean at cov 962 / ft 5136, decode cost +0.6% (`truehdrecover`, merge `1a3aee03`). The earlier cov 3087 came from the pre-fix decoder running on in stale state, and that state is gone now.
530+- **Decision (orchestrator, 2026-10-18, under the owner's no-questions rule): AAC priming.** With no edit list, edith keeps trimming 1024 samples (`engine/src/audio.rs` `DEFAULT_PRIMING`, ffmpeg's own AAC-LC encoder delay), and ffmpeg's decode does not. Kept: the trim gives the timing the encoder meant, `audio_decode.rs`, `audio_segments.rs` and `audio_copy.rs` assert it, and ffmpeg leaves the trim to an edit list it does not find. Follow-up noted, not a gate: the comment there still says HE-AAC is refused, which is stale since `aacv2`; HE-AAC encoders without an edit list usually delay 2112 samples. The owner can reverse this decision.
531+- **ec-h265 decode phone clips (resolved 2026-10-18, owner rule "use public-domain or generated media"):** `real_library_hevc_streams_match_ffmpeg` reports 29 bit-exact, 0 refused, 0 failed, 300 pictures each. The phone rows are:
532+ - a CC0 Android original (720x1280 portrait 8-bit; Android MPEG4Writer handler names and no re-encode trace);
533+ - a CC0 iPhone 7 Plus original (1080p 8-bit; Apple make/model tags; first 20 s stream-copied, bitstream untouched);
534+ - a **synthetic** 10-bit HLG BT.2020 clip in an `hvc1` mov (libx265 main10).
535+ Gap, stated plainly: no public-domain 10-bit HDR phone original turned up, so 10-bit HLG is shown on x265 output, not an iPhone 12+ encoder's. 10-bit decode is otherwise covered by 20 Main 10 library films and the conformance set.
536+
537+### ec-mjpeg (Motion JPEG decode) - DONE (lane `mjpeg`)
538+
539+- `ec-image::jpeg::decode_yuv` decodes a JPEG straight to native planes (4:2:0, 4:2:2, 4:4:4, gray; no upsampling, no RGB), with libavcodec's `simple_idct` and DC level shift, so output is byte-identical to ffmpeg's `mjpeg` decoder. Annex K default Huffman tables stand in for a missing DHT (AVI1/MJPG). The stills path (`decode`) is untouched; `ec-image` tests unchanged.
540+- `ec-mjpeg` (`MjpegDecoder`, `decode_frame`, `CodecId::Mjpeg`): full range (JFIF) always, two-field packets woven and flagged interlaced, restart markers, progressive. Refused by name: 12-bit, arithmetic/lossless/hierarchical, CMYK, RGB-coded, 4:4:0 / 4:1:1 / 4:1:0.
541+- Containers: ec-mp4 maps `jpeg` and `mjpa` to Mjpeg (`mjpb` stays in the unsupported-entry listing); ec-matroska maps `V_MJPEG`.
542+- Gate: `crates/ec-mjpeg/tests/ffmpeg_parity.rs` (stills with restart/progressive, 8 pix_fmt x size x quality x huffman x container cases, gray, no-DHT AVI, two-field AVI/MOV/MKV) byte-exact vs ffmpeg; `fuzz/` target `decode_mjpeg`.
543+
544+### ec-riff AVI video demux - DONE (lane `avivideo`)
545+
546+- `ec_riff::AviDemuxer` (new `src/demux.rs`; the audio-only `AviReader` is untouched, its tests pass unchanged): audio and video streams, `Demuxer` trait, `seek_stream` returning the landed instant, `field_order(stream)`, `tracks()` listing refused streams by name, `index_kind()`, `is_avi()` sniff.
547+- Codecs: MJPG/jpeg/dmb1/AVRn to Mjpeg, H264/X264/avc1 to H264 (Annex B), MPG2/mpg1 to Mpeg2Video, apcn etc. to ProRes; audio PCM 8/16/24/32, float, MP2, MP3, AC-3, AAC (ASC from `strf` extradata). Refused by name: MPEG-4 Part 2 / MS-MPEG4, DV, DNxHD (`AVdn`, TODO until `CodecId::Dnxhd` is on main), uncompressed video (DIB, YUY2, UYVY, v210, I420, YV12). Raw video is refused rather than given a `RawVideo` id: there is no consumer, the packed-4:2:2 and bottom-up DIB layouts have no `PixelFormat`/descriptor, and adding an id means touching `registry.rs` that the dnxhd lane is editing.
548+- Index: OpenDML `indx` + `ix##` across `RIFF AVIX`, legacy `idx1`, linear scan (also over truncated files). Keyframes from the index, sniffed (IDR / I picture) on scan. Zero-size video chunks keep their frame slot. B-frame H.264/MPEG-2: pts = dts = decode-order slot (documented limit). Mjpeg field order BottomFieldFirst; others from `vprp`.
549+- Tests `crates/ec-riff/tests/it/avi_video.rs`: ffmpeg-made mjpeg+pcm / mjpeg+mp3 / h264(+B)+aac / mpeg2+mp2 / rawvideo / xvid checked against `ffprobe -show_packets` (count, size, key, time, adler32 of bytes); MJPEG frames decoded through ec-mjpeg equal ffmpeg's; hand-built OpenDML (two RIFFs), idx1, scan, vprp, seek. Fuzz target `avi_demux`.
550+
551+### ec-dnxhd (Avid DNxHD / DNxHR decode) - DONE (lane `dnxhd`)
552+
553+- `ec-dnxhd` (`DnxhdDecoder::decode(&Packet) -> VideoFrame`, `decode_bytes`, `decode_native`, `CodecId::Dnxhd`): all 20 compression ids ffmpeg knows (1235-1260 DNxHD at 8/10-bit 4:2:2, progressive and two-field interlaced with the interlace flag set, MBAFF 1260; DNxHR LB/SQ/HQ 8-bit, HQX 10/12-bit 4:2:2, 444 10/12-bit 4:4:4 YCbCr) at any size up to 8192x4608. Output I422/I210/I444/I410; ec-core has no 12-bit formats, so `decode` narrows 12 to 10 bits (`(v+2)>>2`) and `decode_native` returns the coded-depth `u16` planes. Refused by name: alpha, RGB (GBR) 4:4:4, ACT on 4:2:2.
554+- Containers: ec-mp4 maps `AVdn`/`AVdh`, ec-matroska maps `V_QUICKTIME`/`V_MS/VFW/FOURCC` carrying them, ec-riff maps `AVdn` (AVI).
555+- Gate: `crates/ec-dnxhd/tests/ffmpeg_parity.rs` byte-exact against ffmpeg's C decoder (`-cpuflags 0`): 19 DNxHD streams at 1080p/1080i/720p/1440/960, DNxHR x 5 profiles x 5 sizes (1280x544, 322x178, 258x122, 256x120, 1000x300), 3840x2160, 12-bit and MBAFF by header-patched streams, 1 and 3 threads. Against ffmpeg's default x86 SIMD build the output matches except where ffmpeg's own SIMD IDCT departs from its C code: 10-bit streams of saturated noise at very high rates (under 0.06% of samples differ, overflowing coefficients) and 12-bit (rounding, max abs error 1, above 80 dB). We follow the C code.
556+- Speed (server, 1080p DNxHR HQ at ~176 Mbps): 28 fps on one thread, 70 fps with 4-6 threads (rows handed out dynamically, `std::thread::scope`, at most 6).
557+- Fuzz: `crates/ec-dnxhd/fuzz` target `decode_dnxhd`, seeds in `fuzz/seeds`, 10 minutes clean.
558+
559+### ec-prores encoder (Apple ProRes encode) - DONE (lane `proresenc`)
560+
561+- `ec_prores::ProResEncoder` (`EncoderConfig`, `Profile`, `nominal_frame_bytes`; also the registry `Encoder` trait): 422 Proxy / LT / 422 / HQ from I210 or I422, 4444 / 4444 XQ from I410 / I412 / I444, progressive. Alpha is not coded (off by design: `alpha_channel_type` 0, `VideoFrame` carries none) and interlaced (two-field) output is refused by name; both are future work.
562+- Rate control: one quantiser for the whole frame (the MSE optimum), chosen by a secant search on a slice sample so the frame lands on Apple's rate for the profile and size (1080p29.97: 45/102/147/220/330/500 Mbit/s, scaled by `(macroblocks/8160)^0.846`, which gives Apple's UHD figures too); a Bresenham-spread fraction of slices takes the next finer step to land on the budget. Measured frame size is 0.997-1.001 of nominal on dense content at 1080p and 2160p.
563+- Bit-exact in both decoders: ffmpeg and ec-prores decode every profile identically (tests); output bytes do not depend on the thread count. PSNR vs `prores_ks` at the same profile on testsrc2 / mandelbrot / noisy testsrc2 is higher on smooth content (10-25 dB) and within 0.2 dB on noise, at equal or smaller frames.
564+- Slice-parallel via `std::thread::scope` (max 6 threads). Muxing: `ec-mp4` writes a ProRes sample entry from `CodecParameters.extradata` = the 4-byte profile fourcc (no config box; `colr`, `fiel`, `pasp` after it); use `Mp4Muxer::with_brands(w, *b"qt ", &[*b"qt "])` for a QuickTime .mov. ffprobe reads codec, profile, pix_fmt, `field_order=progressive` and the colour tags. Frame-header creator id is `edth` (configurable; ffmpeg itself writes `Lavc`, not `apl0`).
565+- Tests `crates/ec-prores/tests/encode.rs` (synthetic only); decoder files untouched. Example `examples/enc.rs`.
566+
567+### ec-mpeg4 (MPEG-4 Part 2 Simple / Advanced Simple and H.263 decode) - DONE (lane `mpeg4p2`)
568+
569+- `ec-mpeg4` (`Mpeg4Decoder`, `CodecId::Mpeg4Part2`, registry name `mpeg4`): XviD / DivX 4-5 / FMP4 / mp4v and H.263 baseline (short header, QCIF to 4CIF, GOB headers). I / P / B / S-VOPs, half- and quarter-pel MC, 4MV, direct mode (8x8, 16x16 and field variants), field DCT and field MC, interlace flag set on output, MPEG and H.263 quantisation with custom matrices, AC/DC prediction, resync markers, N-VOPs. Output I420 in display order.
570+- GMC: 0 to 3 warp points are decoded, all exact (libxvid emits 3). The brief asked to refuse more than 1; this is a superset and nothing is refused.
571+- Output order and delay: unless the VOL says `low_delay`, one reference picture is held, so output lags decode by one picture; B pictures come out at once and flush emits the held one. There is no PTS in AVI, so display order is the only contract. Like libavcodec, an N-VOP produces no output frame (a final N-VOP makes flush emit the held picture with the last packet's pts).
572+- Packed bitstream (DivX packed B-frames): unpacked inside the decoder with libavcodec's stash model (a trailing I or B VOP in a packet is stashed and decoded in place of the next, short N-VOP packet). Not gated on a DivX user-data sniff, so XviD packed streams unpack too.
573+- libavcodec workarounds matched, taken from the user data (XviD / DivX / Lavc build): XviD IDCT chosen when an XviD build is seen (`set_xvid_idct` forces it either way), qpel chroma variants, hpel chroma, dc clip, direct block size, edge. A FourCC is only used if given through `set_fourcc`; the registry constructor cannot pass it.
574+- Refused by name: studio profiles, non-rectangular shape, static sprites, sprite brightness change, NEWPRED, reduced-resolution VOPs, scalability, data partitioning and reversible VLC, H.263 PLUSPTYPE / SAC / AP / PB-frames. MS-MPEG4 v1/2/3 (DIV3, MP43, ...) stay refused in ec-riff.
575+- Containers: ec-riff maps XVID/XVIX/DIVX/DX50/FMP4/MP4V/M4S2/MP4S/RMP4/DVX1/BLZ0/UMP4 (supersedes the "refused" line in the avivideo entry); ec-mp4 maps `mp4v` (esds objectTypeIndication 0x20, DecSpecificInfo as extradata) and `s263`/`h263`; ec-matroska maps `V_MPEG4/ISO/SP|ASP|AP` and VFW FourCCs.
576+- Gate: `crates/ec-mpeg4/tests/ffmpeg_parity.rs` (30 cases) and `tests/containers.rs` byte-exact against `ffmpeg -threads 1 -cpuflags 0`: I/P, q 2 to 31, 4MV, AIC, CBR, B 1 and 2, qpel, field DCT/ME with direct-field, mpeg_quant, resync, odd and tiny sizes, 720p everything, H.263 formats, libxvid GMC/qpel/interlaced, AVI DX50/XVID/FMP4, MP4 mp4v, 3GP H.263, MKV, packed bitstream, refusal and corruption robustness. Reference recipe: `-threads 1` because the frame-threaded interlaced direct mode loses the field-MV table (non-deterministic output); `-cpuflags 0` because ffmpeg's x86 `put_no_rnd_pixels8_x2/y2` SIMD is not bit-exact with its C code (+-1 in rare pixels). We follow the C code. `-flags +bitexact` is not a usable reference (it changes the MPEG-2 intra dequantiser).
577+- Speed: ignored test `speed_720p_at_least_120_fps` (qpel+4MV+B, one thread); see the report for server numbers. Fuzz: `crates/ec-mpeg4/fuzz` target `decode_mpeg4`, seeded corpus.
578+- DONE 2026-10-20 ec-dv decode (DV25 4:1:1/4:2:0, DVCPRO25, DVCPRO50, DVCPRO HD 1080i/720p): byte-exact vs ffmpeg dvvideo in native pix_fmt on 9 fixtures flavours and on mutated/damaged streams (incl. ffmpeg VLC length quirk and ec=3 concealment); DV audio sample-exact vs ffmpeg dvaudio (16-bit 48/44.1/32k, 12-bit nonlinear); raw .dv DIF demuxer with `is_dv`; DvVideo mapped in ec-mp4 and ec-riff AVI. 4:1:1 widened to I422 by duplication in the Decoder trait, native via `DvVideoDecoder`. Report: `dvvideo.report.md`.
579+- DONE 2026-10-20 muxhdr: ec-mp4 muxes and demuxes QuickTime PCM `in24`/`in32`/`fl32` (LE and BE via `wave/frma/enda`, sound description v1, frame-per-sample tables, `chan` for mono/stereo/5.1; sample entries byte-identical to ffmpeg) plus demux of v2 `lpcm`; new `CodecId::PcmS24Be/PcmS32Be/PcmF32Be`; `ec_core::MasteringPrimaries` + `ContentLight::mastering_primaries`; `Mp4Muxer::set_content_light`/`set_channel_layout_box` and `MatroskaMuxer::set_content_light` write `mdcv`/`clli` and `Colour/MasteringMetadata` (primaries, white point, luminance) + MaxCLL/MaxFALL, all read back. Nothing is written unless the caller sets it. Tests: `ec-mp4/tests/it/qt_pcm_hdr.rs`, `ec-matroska/tests/hdr_metadata.rs`. Report: `muxhdr.report.md`.
580+- DONE 2026-10-23 ec-prores decode (P1, `doneaudit`): byte-exact vs ffmpeg 8.x `prores_ks`/`prores_aw` on the 54 `matches_ffmpeg` cases (`tests/ffmpeg_parity.rs`), 1 and 3 threads, pass (report `prores.report.md`, merge `327c3138`); `EC_REQUIRE_FIXTURES=1 cargo test -p ec-prores -p ec-mp4 -p ec-core --release` 152 passed, 0 failed, 2 ignored (server); clippy clean; `forbid(unsafe)` since `safesimd-prores` (merge `5c0d241a`); fuzz `decode_prores` 10 min clean, 9,027,240 runs on host c; speed on quiet host b (load 0.05) 1080p 422 HQ: 63.7 fps single-thread (2.55x, set spread 2.7%), 161.1 fps on 4 threads (6.44x), so the 60 fps single-thread target is met (`doneaudit` bench rows); edith decodes through `ProResSeat` (`engine/tests/procodecs.rs` `prores_every_profile_opens_decodes_seeks_and_exports`, `prores_export.rs`).
581+- DONE 2026-10-23 ec-mpeg2 decode (P1, `doneaudit`): byte-exact vs ffmpeg 8.1.3 (default simple IDCT, md5 match) with `ffmpeg_parity.rs` 4 pass and `synth_parity.rs` 4 pass; `EC_REQUIRE_FIXTURES=1 cargo test -p ec-mpeg2 -p ec-mpegts -p ec-core --release` 144 passed, 0 failed, 1 ignored; clippy clean; fuzz `decode_mpeg2`: the first 1-hour run found a panic (MB-row change in a sequence extension without resize overran a pooled picture, decoder.rs:1106), fixed in lane `mpeg2crash` (merge `77ec01a1`, regression test `robust.rs` `mb_height_change_without_resize_is_concealed`), then 1 CPU-hour clean on the fixed code, 430,880 runs on host b (`-max_len=8192`, cov 1807 ft 9673); single-thread decode 101.5 fps on 1080i29.97 20 Mb/s IPB (3.39x) and 467.5 fps on 576i25 6 Mb/s IPB (18.70x), shared host b, spreads 5-15% so treat as rough (`doneaudit` bench rows); merge `0771c21b`; edith uses it as the software MPEG-2 backend (`engine/src/decode/mpeg2.rs`, `engine/tests/mpegts.rs` `mpeg2_video_opens_probes_and_decodes_as_ffmpeg_does`).
582+- DONE 2026-10-23 ec-mp3 Layer I/II decode (MP1/MP2, `doneaudit`): `ffmpeg -c:a mp2`/`mp2fixed` and libtwolame streams within 1e-5 of ffmpeg's float decoder (`tests/mp2_matrix.rs`, max 5.2e-6 and 6.2e-6); 336 hand-built Layer I and II streams max 3.85e-5 vs `mp2float` and 1 LSB vs `mp2fixed`; `cargo test --release -p ec-mp3`: 35 passed, 0 failed, 2 ignored; clippy clean; fuzz target `decode` (MP1/MP2/MP3 through `Mp3Reader`) 1 CPU-hour clean, 322,492 runs on host c (`mp3fuzz`, merge `49de1e0e`); public-domain real media (archive.org) equal to ffmpeg: ZeitgeistWeekendLiner.mpg 3,287,808 samples (max diff 1.49e-6), wtc_construction.mpg 14,063,616 samples (max 9.8e-7), and StripQueen.mpg equal except its final truncated 88-byte packet, which ffmpeg decodes and ec-mp3 refuses as incomplete (one 1152-sample frame, 24 ms); single-thread 389.0x realtime at 384 kb/s and 401.1x at 192 kb/s on shared host b, spreads 5-24%; merge `6acc9d93`; edith's MP2 tests (`cargo test --release -p engine --test mpegps --test avi`, 18 passed) ran locally because the server slots were busy. Layer I is tested only on hand-built frames (no MP1 encoder and no clearly licensed MP1 sample).
583+- DONE 2026-10-23 ec-mpegts TS demux (`doneaudit`): `cargo test --release -p ec-mpegts` with `EC_REQUIRE_FIXTURES=1` 79 passed, 0 failed, clippy clean; fuzz `demux_ts` 1 CPU-hour clean, 948,269 runs on host c (`-max_len=16384`, cov 2808 ft 16195), and `ts_parts` 1 CPU-hour clean, 17,792,835 runs on host c, both on current main because the 2026-10-20 record had no log and predated the TrueHD/DTS/DVB-subtitle changes; packet counts equal ffprobe on a 60 s H.264 1080p30 + AAC 128k + AC-3 5.1 448k file (6489 packets, 123.8k packets/s, 942 MB/s, shared host b, spread 3.6-17%); TrueHD (lane `tstruehd`), DTS (lane `dts`) and DVB subtitles (lane `dvdsubs`, merges `482942fb`/`c8a3ed95`) are exposed; edith's `TsDemuxer` (`engine/src/demux/ts.rs`) is tested by `engine/tests/mpegts.rs` (12 tests); the 79-test run is shared with the PS line.
584+- DONE 2026-10-23 ec-mpegts PS demux (`doneaudit`): the same `cargo test --release -p ec-mpegts` run with `EC_REQUIRE_FIXTURES=1` (79 passed, 0 failed, `ps.rs` 29 and `committed_ps.rs` 2); fuzz `demux_ps` 10 min, 24,217 runs clean (`pstail`), which its section accepts as a smoke run; packets equal ffprobe on a 60 s MPEG-2 1080p30 + MP2 224k + AC-3 5.1 448k file (6175 packets, 61.1k packets/s, 644 MB/s, `PsDemuxer`, shared host b, spread 12-28%); VobSub is exposed (lane `dvdsubs`), no longer refused; edith's `PsDemuxer` (`engine/src/demux/ps.rs`) is tested by `engine/tests/mpegps.rs` (11 tests).
crates/ec-aac/examples/aacenc_file.rsadded+54 -0
@@ -0,0 +1,54 @@
1+//! Encodes a raw interleaved f32 little-endian PCM file to ADTS with `AacEncoder`,
2+//! for the objective encoder comparison in `scripts/aac-encode-score.sh`.
3+//!
4+//! ```text
5+//! cargo run --release -p ec-aac --example aacenc_file -- <in.f32le> <channels> <rate> <kbps> <out.aac>
6+//! ```
7+
8+use std::process::ExitCode;
9+
10+use ec_aac::{AacEncoder, AacEncoderConfig};
11+
12+fn main() -> ExitCode {
13+ let args: Vec<String> = std::env::args().collect();
14+ if args.len() != 6 {
15+ eprintln!("usage: aacenc_file <in.f32le> <channels> <rate> <kbps> <out.aac>");
16+ return ExitCode::from(2);
17+ }
18+ let parse = |s: &str| s.parse::<u32>().ok();
19+ let (Some(channels), Some(rate), Some(kbps)) = (parse(&args[2]), parse(&args[3]), parse(&args[4]))
20+ else {
21+ eprintln!("channels, rate and kbps must be unsigned integers");
22+ return ExitCode::from(2);
23+ };
24+ let raw = match std::fs::read(&args[1]) {
25+ Ok(raw) => raw,
26+ Err(e) => {
27+ eprintln!("read {}: {e}", args[1]);
28+ return ExitCode::FAILURE;
29+ }
30+ };
31+ let pcm: Vec<f32> = raw
32+ .chunks(4)
33+ .map(|b| f32::from_le_bytes(b.try_into().expect("whole f32 samples")))
34+ .collect();
35+ let mut enc = AacEncoder::new(AacEncoderConfig {
36+ bitrate_bps: kbps * 1_000,
37+ adts: true,
38+ ..Default::default()
39+ });
40+ if let Err(e) = enc.push_pcm(&pcm, channels as u16, rate) {
41+ eprintln!("push_pcm: {e:?}");
42+ return ExitCode::FAILURE;
43+ }
44+ enc.finish();
45+ let mut out = Vec::new();
46+ while let Ok(p) = enc.next_packet() {
47+ out.extend_from_slice(&p.data);
48+ }
49+ if let Err(e) = std::fs::write(&args[5], &out) {
50+ eprintln!("write {}: {e}", args[5]);
51+ return ExitCode::FAILURE;
52+ }
53+ ExitCode::SUCCESS
54+}
crates/ec-aac/examples/adts_to_pcm.rsmodified+1 -0
@@ -36,6 +36,7 @@ fn main() {
36 sbr_present: true,36 sbr_present: true,
37 ps_present: false,37 ps_present: false,
38 extension_sample_rate: Some(44100),38 extension_sample_rate: Some(44100),
39+ pce: Vec::new(),
39 });40 });
40 ec_aac::AacDecoder::with_config_bytes(&asc).expect("asc parses")41 ec_aac::AacDecoder::with_config_bytes(&asc).expect("asc parses")
41 } else {42 } else {
crates/ec-aac/examples/bench.rsadded+117 -0
@@ -0,0 +1,117 @@
1+//! bench: AAC decode and encode throughput for lanes/bench.md ("lane benchaudio").
2+//!
3+//! usage:
4+//! bench dec <in.adts> <out.f32le> [reps]
5+//! bench enc <in.f32le> <channels> <rate> <kbps> <out.adts> [reps]
6+//!
7+//! `dec` decodes every ADTS frame of the file with `AacDecoder` (implicit SBR is detected by the
8+//! decoder; an HE-AAC ADTS stream needs no config), `reps` times (default 5), and keeps the best
9+//! wall time. The decoded interleaved f32 PCM of the last run is written to `out.f32le`.
10+//! `enc` encodes raw interleaved f32le PCM to ADTS AAC-LC with `AacEncoder`, best of `reps`.
11+use std::hint::black_box;
12+use std::time::Instant;
13+
14+use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig, parse_adts};
15+
16+/// Decode the whole ADTS stream once: (interleaved samples, frames decoded, frames that failed).
17+fn decode_once(data: &[u8]) -> (Vec<f32>, usize, usize) {
18+ let mut decoder = AacDecoder::new();
19+ let mut out = Vec::new();
20+ let (mut ok, mut failed) = (0usize, 0usize);
21+ let mut at = 0usize;
22+ while at + 7 <= data.len() {
23+ let Ok(header) = parse_adts(&data[at..]) else {
24+ break;
25+ };
26+ let end = (at + header.frame_length).min(data.len());
27+ match decoder.decode(&data[at..end], None) {
28+ Ok(frame) => {
29+ out.extend_from_slice(&frame.samples);
30+ ok += 1;
31+ }
32+ Err(_) => failed += 1,
33+ }
34+ at = end;
35+ }
36+ (out, ok, failed)
37+}
38+
39+/// Encode interleaved f32 PCM to one ADTS byte stream.
40+fn encode_once(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> {
41+ let config = AacEncoderConfig {
42+ bitrate_bps: kbps * 1000,
43+ adts: true,
44+ ..AacEncoderConfig::default()
45+ };
46+ let mut encoder = AacEncoder::new(config);
47+ encoder.push_pcm(pcm, channels, rate).expect("push");
48+ encoder.finish();
49+ let mut out = Vec::new();
50+ loop {
51+ match encoder.next_packet() {
52+ Ok(packet) => out.extend_from_slice(&packet.data),
53+ Err(e) if e.is_eof() => break,
54+ Err(e) => panic!("encode: {e}"),
55+ }
56+ }
57+ out
58+}
59+
60+fn le_f32(bytes: &[u8]) -> Vec<f32> {
61+ bytes
62+ .as_chunks::<4>().0.iter()
63+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
64+ .collect()
65+}
66+
67+fn main() {
68+ let args: Vec<String> = std::env::args().collect();
69+ match args.get(1).map(String::as_str) {
70+ Some("dec") if args.len() >= 4 => {
71+ let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps"));
72+ let data = std::fs::read(&args[2]).expect("read input");
73+ let (pcm, ok, failed) = decode_once(&data);
74+ let mut best = f64::MAX;
75+ for _ in 0..reps {
76+ let t = Instant::now();
77+ black_box(decode_once(black_box(&data)).0.len());
78+ best = best.min(t.elapsed().as_secs_f64());
79+ }
80+ let mut bytes = Vec::with_capacity(pcm.len() * 4);
81+ for v in &pcm {
82+ bytes.extend_from_slice(&v.to_le_bytes());
83+ }
84+ std::fs::write(&args[3], &bytes).expect("write output");
85+ println!(
86+ "frames_ok={ok} frames_failed={failed} samples={} best_decode_s={best:.4} reps={reps}",
87+ pcm.len()
88+ );
89+ }
90+ Some("enc") if args.len() >= 7 => {
91+ let channels: u16 = args[3].parse().expect("channels");
92+ let rate: u32 = args[4].parse().expect("rate");
93+ let kbps: u32 = args[5].parse().expect("kbps");
94+ let reps: usize = args.get(7).map_or(5, |s| s.parse().expect("reps"));
95+ let pcm = le_f32(&std::fs::read(&args[2]).expect("read input"));
96+ let out = encode_once(&pcm, channels, rate, kbps);
97+ let mut best = f64::MAX;
98+ for _ in 0..reps {
99+ let t = Instant::now();
100+ black_box(encode_once(black_box(&pcm), channels, rate, kbps).len());
101+ best = best.min(t.elapsed().as_secs_f64());
102+ }
103+ std::fs::write(&args[6], &out).expect("write output");
104+ println!(
105+ "bytes={} best_encode_s={best:.4} reps={reps} audio_s={:.3}",
106+ out.len(),
107+ pcm.len() as f64 / f64::from(channels) / f64::from(rate)
108+ );
109+ }
110+ _ => {
111+ eprintln!(
112+ "usage: bench dec <in.adts> <out.f32le> [reps]\n bench enc <in.f32le> <channels> <rate> <kbps> <out.adts> [reps]"
113+ );
114+ std::process::exit(2);
115+ }
116+ }
117+}
crates/ec-aac/examples/wrap_sbr.rsmodified+1 -0
@@ -70,6 +70,7 @@ fn main() {
70 sbr_present: true,70 sbr_present: true,
71 ps_present: false,71 ps_present: false,
72 extension_sample_rate: Some(ext_rate),72 extension_sample_rate: Some(ext_rate),
73+ pce: Vec::new(),
73 });74 });
74 75
75 let time_base = TimeBase::from_rate(core_rate);76 let time_base = TimeBase::from_rate(core_rate);
crates/ec-aac/fuzz/.gitignoreadded+4 -0
@@ -0,0 +1,4 @@
1+target
2+corpus
3+artifacts
4+coverage
crates/ec-aac/fuzz/Cargo.tomladded+39 -0
@@ -0,0 +1,39 @@
1+[package]
2+name = "ec-aac-fuzz"
3+version = "0.0.0"
4+publish = false
5+edition = "2024"
6+
7+[package.metadata]
8+cargo-fuzz = true
9+
10+[dependencies]
11+libfuzzer-sys = "0.4"
12+
13+[dependencies.ec-aac]
14+path = ".."
15+
16+# Keeps this crate out of the main workspace.
17+[workspace]
18+members = ["."]
19+
20+[[bin]]
21+name = "decode_adts"
22+path = "fuzz_targets/decode_adts.rs"
23+test = false
24+doc = false
25+bench = false
26+
27+[[bin]]
28+name = "decode_raw"
29+path = "fuzz_targets/decode_raw.rs"
30+test = false
31+doc = false
32+bench = false
33+
34+[[bin]]
35+name = "decode_he"
36+path = "fuzz_targets/decode_he.rs"
37+test = false
38+doc = false
39+bench = false
crates/ec-aac/fuzz/fuzz_targets/decode_adts.rsadded+10 -0
@@ -0,0 +1,10 @@
1+#![no_main]
2+
3+use ec_aac::AacDecoder;
4+use libfuzzer_sys::fuzz_target;
5+
6+// The whole input is one packet of ADTS frames: `decode` walks every frame in it.
7+fuzz_target!(|data: &[u8]| {
8+ let mut dec = AacDecoder::new();
9+ let _ = dec.decode(data, None);
10+});
crates/ec-aac/fuzz/fuzz_targets/decode_he.rsadded+11 -0
@@ -0,0 +1,11 @@
1+#![no_main]
2+
3+use ec_aac::AacDecoder;
4+use libfuzzer_sys::fuzz_target;
5+
6+// HE-AAC path: the whole input is ADTS, so every frame goes through the SBR (and, for v2, PS)
7+// reconstruction. Seeds are the HE-AAC v1/v2 fixtures in tests/data/he (see seed.sh).
8+fuzz_target!(|data: &[u8]| {
9+ let mut dec = AacDecoder::new();
10+ let _ = dec.decode(data, None);
11+});
crates/ec-aac/fuzz/fuzz_targets/decode_raw.rsadded+33 -0
@@ -0,0 +1,33 @@
1+#![no_main]
2+
3+// Input layout:
4+// byte 0 selects one of the four AudioSpecificConfigs below (mod 4)
5+// then raw_data_block access units, each prefixed by a u16 big-endian length
6+// (a length past the end of the input is clamped to what remains)
7+
8+use ec_aac::AacDecoder;
9+use libfuzzer_sys::fuzz_target;
10+
11+// Valid, hand-packed AudioSpecificConfigs (ISO/IEC 14496-3 1.6.2.1).
12+const CONFIGS: [&[u8]; 4] = [
13+ &[0x11, 0x88], // AAC-LC, 48 kHz, mono
14+ &[0x11, 0x90], // AAC-LC, 48 kHz, stereo
15+ &[0x2B, 0x23, 0x10], // HE-AAC (explicit SBR): core 24 kHz, stereo, SBR at 48 kHz
16+ &[0x11, 0xB0], // AAC-LC, 48 kHz, 5.1
17+];
18+
19+fuzz_target!(|data: &[u8]| {
20+ let Some((&sel, mut rest)) = data.split_first() else {
21+ return;
22+ };
23+ let asc = CONFIGS[(sel as usize) % CONFIGS.len()];
24+ // The configs are constants above, so a parse failure is a harness bug, not an input finding.
25+ let mut dec = AacDecoder::with_config_bytes(asc).expect("built-in AudioSpecificConfig must parse");
26+ while rest.len() >= 2 {
27+ let len = u16::from_be_bytes([rest[0], rest[1]]) as usize;
28+ rest = &rest[2..];
29+ let (au, tail) = rest.split_at(len.min(rest.len()));
30+ let _ = dec.decode(au, None);
31+ rest = tail;
32+ }
33+});
crates/ec-aac/fuzz/seed.shadded+74 -0
@@ -0,0 +1,74 @@
1+#!/usr/bin/env bash
2+# seed.sh: fill fuzz/corpus/<target>/ from the repo's AAC fixtures (root fixtures/audio).
3+#
4+# decode_adts gets each ADTS fixture as-is.
5+# decode_he gets each HE-AAC v1/v2 ADTS fixture from tests/data/he as-is (no root fixtures needed).
6+# decode_raw gets each ADTS fixture re-packed as raw access units: selector byte, then
7+# u16 BE length + raw_data_block per ADTS frame. Mono/stereo/5.1 at 48 kHz pick
8+# their matching config; the stereo fixtures are also replayed through the HE-AAC
9+# config so SBR is reached.
10+#
11+# Corpus lives under fuzz/corpus, which is git-ignored.
12+set -euo pipefail
13+
14+FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15+HE_DIR=$(cd -- "$FUZZ_DIR/../tests/data/he" && pwd)
16+HE_CORPUS="$FUZZ_DIR/corpus/decode_he"
17+mkdir -p "$HE_CORPUS"
18+for f in "$HE_DIR"/*.aac; do cp -f "$f" "$HE_CORPUS/"; done
19+echo "seeded $(ls "$HE_CORPUS" | wc -l) decode_he seeds"
20+
21+FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio
22+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh (decode_he is seeded)" >&2; exit 0; }
23+
24+ADTS=("$FIXTURES"/aac-adts-*.aac)
25+[ -e "${ADTS[0]}" ] || { echo "seed.sh: no aac-adts-*.aac fixtures in $FIXTURES" >&2; exit 2; }
26+
27+ADTS_DIR="$FUZZ_DIR/corpus/decode_adts"
28+RAW_DIR="$FUZZ_DIR/corpus/decode_raw"
29+mkdir -p "$ADTS_DIR" "$RAW_DIR"
30+
31+python3 -I - "$FIXTURES" "$ADTS_DIR" "$RAW_DIR" <<'PY'
32+import glob, os, sys
33+
34+fixtures, adts_dir, raw_dir = sys.argv[1], sys.argv[2], sys.argv[3]
35+
36+def adts_frames(data):
37+ """Yield (body) for each ADTS frame; stops at the first malformed header."""
38+ i = 0
39+ while i + 7 <= len(data):
40+ if not (data[i] == 0xFF and (data[i + 1] & 0xF0) == 0xF0):
41+ break
42+ prot_absent = data[i + 1] & 1
43+ hdr = 7 if prot_absent else 9
44+ flen = ((data[i + 3] & 3) << 11) | (data[i + 4] << 3) | (data[i + 5] >> 5)
45+ if flen < hdr:
46+ break
47+ yield data[i + hdr:i + flen]
48+ i += flen
49+
50+def selector(name):
51+ if "mono" in name:
52+ return 0
53+ if "stereo" in name:
54+ return 1
55+ return 3 # 5.1
56+
57+for path in sorted(glob.glob(os.path.join(fixtures, "aac-adts-*.aac"))):
58+ name = os.path.basename(path)
59+ stem = os.path.splitext(name)[0]
60+ data = open(path, "rb").read()
61+ open(os.path.join(adts_dir, stem), "wb").write(data)
62+
63+ # Raw AUs under the matching config, and (for stereo) under HE-AAC as well.
64+ sels = [selector(name)]
65+ if "stereo" in name:
66+ sels.append(2)
67+ for sel in sels:
68+ out = bytearray([sel])
69+ for body in adts_frames(data):
70+ body = body[:65535]
71+ out += len(body).to_bytes(2, "big") + body
72+ open(os.path.join(raw_dir, f"{stem}-sel{sel}"), "wb").write(bytes(out))
73+print(f"seeded {len(os.listdir(adts_dir))} decode_adts and {len(os.listdir(raw_dir))} decode_raw seeds")
74+PY
crates/ec-aac/src/config.rsmodified+148 -14
@@ -42,6 +42,9 @@ pub struct AudioSpecificConfig {
42 pub ps_present: bool,42 pub ps_present: bool,
43 /// The rate SBR would output at, when signalled.43 /// The rate SBR would output at, when signalled.
44 pub extension_sample_rate: Option<u32>,44 pub extension_sample_rate: Option<u32>,
45+ /// The program config element the config carries when `channel_config` is 0. Raw
46+ /// blocks may then omit it, so their speaker layout comes from here.
47+ pub pce: Vec<PceElement>,
45 }48 }
46 49
47 /// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19).50 /// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19).
@@ -108,6 +111,7 @@ pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
108 sbr_present: false,111 sbr_present: false,
109 ps_present: false,112 ps_present: false,
110 extension_sample_rate: None,113 extension_sample_rate: None,
114+ pce: pce.elements,
111 });115 });
112 }116 }
113 // A backward-compatible SBR signal rides in a sync extension at the end.117 // A backward-compatible SBR signal rides in a sync extension at the end.
@@ -132,6 +136,7 @@ pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
132 sbr_present: sbr,136 sbr_present: sbr,
133 ps_present: ps,137 ps_present: ps,
134 extension_sample_rate: ext_rate,138 extension_sample_rate: ext_rate,
139+ pce: Vec::new(),
135 })140 })
136 }141 }
137 142
@@ -174,6 +179,7 @@ pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
174 sbr_present: false,179 sbr_present: false,
175 ps_present: false,180 ps_present: false,
176 extension_sample_rate: None,181 extension_sample_rate: None,
182+ pce: Vec::new(),
177 })183 })
178 }184 }
179 185
@@ -186,22 +192,113 @@ pub fn config_for_channels(channels: u16) -> u8 {
186 }192 }
187 }193 }
188 194
195+/// A loudspeaker position, named as FFmpeg's channel masks name it. The derived
196+/// order is the mask bit order, which is the order FFmpeg writes its output in.
197+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
198+#[allow(clippy::upper_case_acronyms)] // FFmpeg's and ISO's own speaker names.
199+pub enum Speaker {
200+ FL,
201+ FR,
202+ FC,
203+ LFE,
204+ BL,
205+ BR,
206+ FLC,
207+ FRC,
208+ BC,
209+ SL,
210+ SR,
211+}
212+
213+/// One element a program_config_element lists: its syntactic kind (`0` SCE, `1` CPE,
214+/// `3` LFE, as in the raw data block's `id_syn_ele`), its instance tag, and the
215+/// speaker of each of its channels. `speakers` is empty when the PCE's layout is
216+/// one this crate does not name, and the decoder then keeps the bitstream order.
217+#[derive(Clone, Debug, PartialEq, Eq)]
218+pub struct PceElement {
219+ pub kind: u8,
220+ pub tag: u8,
221+ pub speakers: Vec<Speaker>,
222+}
223+
189 /// What a program_config_element says about the stream.224 /// What a program_config_element says about the stream.
190 #[derive(Clone, Debug, Default)]225 #[derive(Clone, Debug, Default)]
191 pub struct ProgramConfig {226 pub struct ProgramConfig {
192 pub sf_index: u8,227 pub sf_index: u8,
193 pub channels: u16,228 pub channels: u16,
229+ /// The listed elements, in PCE order (front, side, back, LFE).
230+ pub elements: Vec<PceElement>,
231+}
232+
233+/// Names the speakers of a PCE's elements from the list each sits in.
234+///
235+/// Front elements run from the centre outwards: a centre SCE is FC, the outermost
236+/// front pair is FL/FR, and an inner pair is FLC/FRC. Side and back pairs are SL/SR
237+/// and BL/BR, a back SCE is BC, and each LFE is LFE. A layout outside those shapes
238+/// (two centres, a third front pair, two side pairs, ...) names nothing, which the
239+/// caller treats as an unknown layout.
240+fn name_speakers(
241+ front: &[(u8, u8)],
242+ side: &[(u8, u8)],
243+ back: &[(u8, u8)],
244+ lfe: &[u8],
245+) -> Option<Vec<Vec<Speaker>>> {
246+ use Speaker::*;
247+ let mut names: Vec<Vec<Speaker>> = Vec::new();
248+ // Front, from the centre outwards: walk the list backwards so the last pair is outermost.
249+ let mut front_names = vec![Vec::new(); front.len()];
250+ let (mut pairs, mut centres) = (0usize, 0usize);
251+ for (i, &(kind, _)) in front.iter().enumerate().rev() {
252+ if kind == 1 {
253+ front_names[i] = match pairs {
254+ 0 => vec![FL, FR],
255+ 1 => vec![FLC, FRC],
256+ _ => return None,
257+ };
258+ pairs += 1;
259+ } else {
260+ if centres == 1 {
261+ return None;
262+ }
263+ centres += 1;
264+ front_names[i] = vec![FC];
265+ }
266+ }
267+ names.extend(front_names);
268+ let mut side_names = Vec::new();
269+ for &(kind, _) in side {
270+ if kind != 1 || !side_names.is_empty() {
271+ return None;
272+ }
273+ side_names.push(vec![SL, SR]);
274+ }
275+ names.extend(side_names);
276+ let mut back_names = Vec::new();
277+ for &(kind, _) in back {
278+ let next = match (kind, back_names.is_empty()) {
279+ (1, true) => vec![BL, BR],
280+ (0, true) => vec![BC],
281+ _ => return None,
282+ };
283+ back_names.push(next);
284+ }
285+ names.extend(back_names);
286+ if lfe.len() > 1 {
287+ return None;
288+ }
289+ names.extend(lfe.iter().map(|_| vec![LFE]));
290+ Some(names)
194 }291 }
195 292
196-/// Parses a program_config_element far enough to count its channels.293+/// Parses a program_config_element, the channel layout a `channelConfiguration` of 0 carries.
197 pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {294 pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
198 let _tag = r.read_bits(4)?;295 let _tag = r.read_bits(4)?;
199 let _object_type = r.read_bits(2)?;296 let _object_type = r.read_bits(2)?;
200 let sf_index = r.read_bits(4)? as u8;297 let sf_index = r.read_bits(4)? as u8;
201- let front = r.read_bits(4)? as usize;298+ let front_n = r.read_bits(4)? as usize;
202- let side = r.read_bits(4)? as usize;299+ let side_n = r.read_bits(4)? as usize;
203- let back = r.read_bits(4)? as usize;300+ let back_n = r.read_bits(4)? as usize;
204- let lfe = r.read_bits(2)? as usize;301+ let lfe_n = r.read_bits(2)? as usize;
205 let assoc = r.read_bits(3)? as usize;302 let assoc = r.read_bits(3)? as usize;
206 let cc = r.read_bits(4)? as usize;303 let cc = r.read_bits(4)? as usize;
207 if r.read_bit()? {304 if r.read_bit()? {
@@ -214,12 +311,28 @@ pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
214 let _matrix_mixdown = r.read_bits(3)?;311 let _matrix_mixdown = r.read_bits(3)?;
215 }312 }
216 let mut channels = 0u16;313 let mut channels = 0u16;
217- for _ in 0..front + side + back {314+ let read_cpe_tag = |r: &mut BitReader<'_>| -> Result<(u8, u8)> {
218- channels += if r.read_bit()? { 2 } else { 1 };315+ let cpe = r.read_bit()?;
219- let _tag = r.read_bits(4)?;316+ let tag = r.read_bits(4)? as u8;
317+ Ok((u8::from(cpe), tag))
318+ };
319+ let mut front = Vec::with_capacity(front_n);
320+ for _ in 0..front_n {
321+ front.push(read_cpe_tag(r)?);
322+ }
323+ let mut side = Vec::with_capacity(side_n);
324+ for _ in 0..side_n {
325+ side.push(read_cpe_tag(r)?);
220 }326 }
221- channels += lfe as u16;327+ let mut back = Vec::with_capacity(back_n);
222- for _ in 0..lfe + assoc {328+ for _ in 0..back_n {
329+ back.push(read_cpe_tag(r)?);
330+ }
331+ let mut lfe = Vec::with_capacity(lfe_n);
332+ for _ in 0..lfe_n {
333+ lfe.push(r.read_bits(4)? as u8);
334+ }
335+ for _ in 0..assoc {
223 let _tag = r.read_bits(4)?;336 let _tag = r.read_bits(4)?;
224 }337 }
225 for _ in 0..cc {338 for _ in 0..cc {
@@ -229,11 +342,31 @@ pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
229 r.align_to_byte();342 r.align_to_byte();
230 let comment = r.read_bits(8)? as u64;343 let comment = r.read_bits(8)? as u64;
231 r.skip_bits(comment * 8)?;344 r.skip_bits(comment * 8)?;
232- Ok(ProgramConfig { sf_index, channels })
233-}
234 345
235-pub(crate) fn skip_program_config(r: &mut BitReader<'_>) -> Result<()> {346+ for &(kind, _) in front.iter().chain(&side).chain(&back) {
236- parse_program_config(r).map(|_| ())347+ channels += if kind == 1 { 2 } else { 1 };
348+ }
349+ channels += lfe.len() as u16;
350+
351+ // Speakers come back in the listing order (front, side, back, LFE), one entry per element.
352+ let named = name_speakers(&front, &side, &back, &lfe).unwrap_or_default();
353+ let listed = front
354+ .iter()
355+ .chain(&side)
356+ .chain(&back)
357+ .map(|&(kind, tag)| (kind, tag))
358+ .chain(lfe.iter().map(|&tag| (3, tag)));
359+ let mut elements = Vec::new();
360+ for (i, (kind, tag)) in listed.enumerate() {
361+ // An unnamed layout leaves `named` short, so every element then reads as unknown.
362+ let speakers = named.get(i).cloned().unwrap_or_default();
363+ elements.push(PceElement { kind, tag, speakers });
364+ }
365+ Ok(ProgramConfig {
366+ sf_index,
367+ channels,
368+ elements,
369+ })
237 }370 }
238 371
239 /// An ADTS frame header (§1.A.2.2).372 /// An ADTS frame header (§1.A.2.2).
@@ -343,6 +476,7 @@ mod tests {
343 sbr_present: true,476 sbr_present: true,
344 ps_present: false,477 ps_present: false,
345 extension_sample_rate: Some(44100),478 extension_sample_rate: Some(44100),
479+ pce: Vec::new(),
346 };480 };
347 let bytes = write_audio_specific_config(&cfg);481 let bytes = write_audio_specific_config(&cfg);
348 let parsed = parse_audio_specific_config(&bytes).expect("parses");482 let parsed = parse_audio_specific_config(&bytes).expect("parses");
crates/ec-aac/src/decode.rsmodified+159 -8
@@ -80,7 +80,7 @@ static TOOL_SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<ToolSideInfoR
80 static TOOL_SIDEINFO_AU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);80 static TOOL_SIDEINFO_AU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
81 81
82 fn tool_sideinfo_enabled() -> bool {82 fn tool_sideinfo_enabled() -> bool {
83- std::env::var("EC_AAC_TOOL_SIDEINFO_DEBUG").is_ok()83+ crate::knobs::tool_sideinfo_debug()
84 }84 }
85 85
86 fn log_tool_sideinfo(row: ToolSideInfoRow) {86 fn log_tool_sideinfo(row: ToolSideInfoRow) {
@@ -500,9 +500,29 @@ pub struct BlockDecoder {
500 noise: Noise,500 noise: Noise,
501 sf_index: u8,501 sf_index: u8,
502 sbr: Option<crate::sbr_chain::SbrChain>,502 sbr: Option<crate::sbr_chain::SbrChain>,
503+ /// Core rate an implicit SBR payload may double (ISO/IEC 14496-3 1.6.5.2),
504+ /// or `None` when implicit SBR is off: no core rate known yet, the stream's
505+ /// config already signals SBR (`sbr` is set), or the core is above 24 kHz.
506+ implicit_core: Option<u32>,
507+ /// Set once an SBR extension payload has armed `sbr` with no explicit signalling.
508+ implicit_on: bool,
509+ /// Set by `disable_implicit_sbr`: implicit SBR never arms, whatever the headers say.
510+ implicit_off: bool,
511+ /// Set once a PS extension has been decoded in a stream whose SBR was
512+ /// switched on implicitly (see `implicit_on`).
513+ implicit_ps: bool,
503 pns_aus: usize,514 pns_aus: usize,
515+ /// The elements of the last program_config_element seen in the stream, if any.
516+ pce: Option<Vec<crate::config::PceElement>>,
517+ /// Speaker of each channel of the last raw_data_block, in bitstream order, when every
518+ /// element of the block is named by its PCE. `None` keeps the bitstream order.
519+ plane_speakers: Option<Vec<crate::config::Speaker>>,
504 }520 }
505 521
522+/// Highest core rate at which an implicit SBR payload doubles the output (so the
523+/// doubled rate stays at or below 48 kHz). ffmpeg makes the same cut.
524+const IMPLICIT_SBR_MAX_CORE_RATE: u32 = 24_000;
525+
506 impl BlockDecoder {526 impl BlockDecoder {
507 pub fn new(sf_index: u8) -> BlockDecoder {527 pub fn new(sf_index: u8) -> BlockDecoder {
508 BlockDecoder {528 BlockDecoder {
@@ -512,10 +532,43 @@ impl BlockDecoder {
512 noise: Noise(0x1f2e_3d4c),532 noise: Noise(0x1f2e_3d4c),
513 sf_index,533 sf_index,
514 sbr: None,534 sbr: None,
535+ implicit_core: None,
536+ implicit_on: false,
537+ implicit_off: false,
538+ implicit_ps: false,
515 pns_aus: 0,539 pns_aus: 0,
540+ pce: None,
541+ plane_speakers: None,
516 }542 }
517 }543 }
518 544
545+ /// The output order of the last block's planes, as the plane index each output
546+ /// channel takes, in FFmpeg's channel-mask order. `None` when no PCE named them.
547+ pub fn plane_order(&self, channels: usize) -> Option<Vec<usize>> {
548+ let speakers = self.plane_speakers.as_ref()?;
549+ if speakers.len() != channels {
550+ return None;
551+ }
552+ let mut order: Vec<usize> = (0..channels).collect();
553+ order.sort_by_key(|&i| (speakers[i], i));
554+ Some(order)
555+ }
556+
557+ /// Sets the program config element a config carries, for raw blocks that omit it.
558+ pub fn set_pce(&mut self, pce: Vec<crate::config::PceElement>) {
559+ self.pce = (!pce.is_empty()).then_some(pce);
560+ }
561+
562+ /// The speakers of the channels one element of kind `kind` (`0` SCE, `1` CPE, `3` LFE)
563+ /// and instance `tag` carries, per the last PCE. `None` when no PCE names it.
564+ fn pce_speakers(&self, kind: u8, tag: u8) -> Option<&[crate::config::Speaker]> {
565+ self.pce
566+ .as_ref()?
567+ .iter()
568+ .find(|e| e.kind == kind && e.tag == tag && !e.speakers.is_empty())
569+ .map(|e| e.speakers.as_slice())
570+ }
571+
519 pub fn pns_aus(&self) -> usize {572 pub fn pns_aus(&self) -> usize {
520 self.pns_aus573 self.pns_aus
521 }574 }
@@ -529,6 +582,41 @@ impl BlockDecoder {
529 self.sbr = rate.map(crate::sbr_chain::SbrChain::new);582 self.sbr = rate.map(crate::sbr_chain::SbrChain::new);
530 }583 }
531 584
585+ /// Marks Parametric Stereo as signalled by the config, for the SBR chain
586+ /// (if one is armed): its elements then decode to two channels.
587+ pub fn set_sbr_ps(&mut self, on: bool) {
588+ if let Some(sbr) = self.sbr.as_mut() {
589+ sbr.set_ps_config(on);
590+ }
591+ }
592+
593+ /// Arms implicit SBR for a stream whose config does not signal it, at the
594+ /// given core rate. Above 24 kHz (or once SBR is already set) it is a no-op:
595+ /// an SBR payload there is skipped, and the output stays at the core rate.
596+ pub fn set_implicit_core(&mut self, core_rate: u32) {
597+ if self.sbr.is_none() && !self.implicit_off {
598+ self.implicit_core = (core_rate <= IMPLICIT_SBR_MAX_CORE_RATE).then_some(core_rate);
599+ }
600+ }
601+
602+ /// Keeps implicit SBR off for good: an SBR payload is skipped and the output
603+ /// stays at the core rate. For core-only decoding of a stream that carries SBR.
604+ pub fn disable_implicit_sbr(&mut self) {
605+ self.implicit_off = true;
606+ self.implicit_core = None;
607+ }
608+
609+ /// Whether SBR was switched on by an implicit payload, not by the config.
610+ pub fn implicit_sbr(&self) -> bool {
611+ self.implicit_on
612+ }
613+
614+ /// Whether a Parametric Stereo extension was decoded in a stream whose SBR
615+ /// is implicit (see [`BlockDecoder::implicit_sbr`]).
616+ pub fn implicit_ps(&self) -> bool {
617+ self.implicit_ps
618+ }
619+
532 fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> {620 fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> {
533 let bits = if ics.window_sequence.is_short() { 3 } else { 5 };621 let bits = if ics.window_sequence.is_short() { 3 } else { 5 };
534 let esc = (1u32 << bits) - 1;622 let esc = (1u32 << bits) - 1;
@@ -758,6 +846,9 @@ impl BlockDecoder {
758 0846 0
759 };847 };
760 let mut pns = false;848 let mut pns = false;
849+ // Speaker per plane so far; `named` drops to false at the first element a PCE does not name.
850+ let mut speakers: Vec<crate::config::Speaker> = Vec::new();
851+ let mut named = self.pce.is_some();
761 loop {852 loop {
762 if r.bits_remaining() < 3 {853 if r.bits_remaining() < 3 {
763 break;854 break;
@@ -776,6 +867,10 @@ impl BlockDecoder {
776 log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None));867 log_tool_sideinfo(tool_row(au, tag, false, &ch[0], None));
777 }868 }
778 self.finish(&mut ch, None, &mut out);869 self.finish(&mut ch, None, &mut out);
870+ if let (3, Some(sbr), Some(plane)) = (id, self.sbr.as_mut(), out.get_mut(start)) {
871+ sbr.bypass_plane(tag, plane);
872+ }
873+ named &= self.note_speakers(id, tag, 1, &mut speakers);
779 // §4.6.18.1: SBR is never applied to the LFE channel (no874 // §4.6.18.1: SBR is never applied to the LFE channel (no
780 // FIL/SBR payload follows it), so it must not become a875 // FIL/SBR payload follows it), so it must not become a
781 // pending SBR target -- otherwise a later fallback876 // pending SBR target -- otherwise a later fallback
@@ -822,6 +917,7 @@ impl BlockDecoder {
822 log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));917 log_tool_sideinfo(tool_row(au, tag, true, &pair[0], Some(&mask)));
823 }918 }
824 self.finish(&mut pair, Some(&mask), &mut out);919 self.finish(&mut pair, Some(&mask), &mut out);
920+ named &= self.note_speakers(1, tag, 2, &mut speakers);
825 pending = Some((tag, start, 2, true));921 pending = Some((tag, start, 2, true));
826 }922 }
827 2 => return Err(Error::unsupported("aac", "coupling channel element")),923 2 => return Err(Error::unsupported("aac", "coupling channel element")),
@@ -839,22 +935,41 @@ impl BlockDecoder {
839 pending = None;935 pending = None;
840 }936 }
841 5 => {937 5 => {
842- crate::config::skip_program_config(r)?;938+ let pce = crate::config::parse_program_config(r)?;
939+ self.pce = Some(pce.elements);
940+ named = self.pce.is_some();
941+ speakers.clear();
843 pending = None;942 pending = None;
844 }943 }
845 6 => {944 6 => {
846 let mut count = r.read_bits(4)? as u64;945 let mut count = r.read_bits(4)? as u64;
847 if count == 15 {946 if count == 15 {
848- count += r.read_bits(8)? as u64 - 1;947+ // 15 + esc - 1, written so an escape of 0 cannot underflow.
948+ count = 14 + r.read_bits(8)? as u64;
849 }949 }
850 let end_bit = r.bit_position() + count * 8;950 let end_bit = r.bit_position() + count * 8;
951+ // Implicit SBR: no SBR in the config, but this FIL is the first
952+ // to carry an SBR extension right after an element. Arm the
953+ // chain for it; if its payload does not parse, disarm again.
954+ let arming = match self.implicit_core {
955+ Some(core)
956+ if self.sbr.is_none()
957+ && pending.is_some()
958+ && r.bits_remaining() >= 4
959+ && matches!(r.peek_bits(4)?, 13 | 14) =>
960+ {
961+ self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2));
962+ true
963+ }
964+ _ => false,
965+ };
966+ let mut applied = false;
851 if let (Some(sbr), Some((tag, start, n, is_cpe))) =967 if let (Some(sbr), Some((tag, start, n, is_cpe))) =
852 (self.sbr.as_mut(), pending.take())968 (self.sbr.as_mut(), pending.take())
853 {969 {
854 // extension_payload(): bs_extension_type(4), then970 // extension_payload(): bs_extension_type(4), then
855 // (for SBR) an optional 10-bit CRC, then971 // (for SBR) an optional 10-bit CRC, then
856 // sbr_extension_data() itself.972 // sbr_extension_data() itself.
857- let mut applied = false;
858 if r.bits_remaining() >= 4 {973 if r.bits_remaining() >= 4 {
859 let ext_type = r.peek_bits(4)?;974 let ext_type = r.peek_bits(4)?;
860 if ext_type == 13 || ext_type == 14 {975 if ext_type == 13 || ext_type == 14 {
@@ -863,7 +978,10 @@ impl BlockDecoder {
863 r.skip_bits(10)?; // bs_sbr_crc_bits978 r.skip_bits(10)?; // bs_sbr_crc_bits
864 }979 }
865 if let Some(data) = sbr.parse(r, tag, is_cpe) {980 if let Some(data) = sbr.parse(r, tag, is_cpe) {
866- sbr.apply(tag, is_cpe, &data, &mut out[start..start + n]);981+ if data.ps.is_some() && (arming || self.implicit_on) {
982+ self.implicit_ps = true;
983+ }
984+ sbr.apply_planes(tag, is_cpe, &data, &mut out, start, n)?;
867 applied = true;985 applied = true;
868 }986 }
869 }987 }
@@ -874,7 +992,16 @@ impl BlockDecoder {
874 // SBR, or a parse failure): §4.6.18 still992 // SBR, or a parse failure): §4.6.18 still
875 // requires doubled-rate reconstruction, using993 // requires doubled-rate reconstruction, using
876 // the last successfully parsed frame's data.994 // the last successfully parsed frame's data.
877- sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);995+ sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?;
996+ }
997+ }
998+ if arming {
999+ if applied {
1000+ self.implicit_on = true;
1001+ self.implicit_core = None;
1002+ } else {
1003+ // The payload did not parse: this was not SBR after all.
1004+ self.sbr = None;
878 }1005 }
879 }1006 }
880 // Resync to the FIL's declared byte boundary regardless1007 // Resync to the FIL's declared byte boundary regardless
@@ -895,7 +1022,7 @@ impl BlockDecoder {
895 // the last known SBR data the same way.1022 // the last known SBR data the same way.
896 if let (Some(sbr), Some((tag, start, n, is_cpe))) = (self.sbr.as_mut(), pending)1023 if let (Some(sbr), Some((tag, start, n, is_cpe))) = (self.sbr.as_mut(), pending)
897 {1024 {
898- sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);1025+ sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?;
899 }1026 }
900 break;1027 break;
901 }1028 }
@@ -904,9 +1031,33 @@ impl BlockDecoder {
904 if pns {1031 if pns {
905 self.pns_aus += 1;1032 self.pns_aus += 1;
906 }1033 }
1034+ self.plane_speakers = (named && speakers.len() == out.len()).then_some(speakers);
907 r.align_to_byte();1035 r.align_to_byte();
908 Ok(out)1036 Ok(out)
909 }1037 }
1038+
1039+ /// Records the speakers of `count` planes that element `(id, tag)` adds. Returns whether
1040+ /// the PCE named them, which keeps the block's ordering known.
1041+ fn note_speakers(
1042+ &self,
1043+ id: u32,
1044+ tag: u8,
1045+ count: usize,
1046+ speakers: &mut Vec<crate::config::Speaker>,
1047+ ) -> bool {
1048+ let kind = match id {
1049+ 0 => 0,
1050+ 1 => 1,
1051+ _ => 3,
1052+ };
1053+ match self.pce_speakers(kind, tag) {
1054+ Some(named) if named.len() == count => {
1055+ speakers.extend_from_slice(named);
1056+ true
1057+ }
1058+ _ => false,
1059+ }
1060+ }
910 }1061 }
911 1062
912 #[derive(Debug)]1063 #[derive(Debug)]
@@ -1042,7 +1193,7 @@ fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
1042 fn has_pns(ch: &Ics) -> bool {1193 fn has_pns(ch: &Ics) -> bool {
1043 ch.cb1194 ch.cb
1044 .iter()1195 .iter()
1045- .any(|group| group.iter().any(|&codebook| codebook == NOISE_HCB))1196+ .any(|group| group.contains(&NOISE_HCB))
1046 }1197 }
1047 1198
1048 fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {1199 fn tool_row(au: usize, tag: u8, is_cpe: bool, ch: &Ics, mask: Option<&MsMask>) -> ToolSideInfoRow {
crates/ec-aac/src/encode.rsmodified+31 -8
@@ -42,6 +42,10 @@ const MAX_QUANT: i32 = 8191;
42 /// Masking floor relative to the loudest band of the frame, standing in for the42 /// Masking floor relative to the loudest band of the frame, standing in for the
43 /// absolute threshold of hearing (see [`AacEncoder::psychoacoustics`]).43 /// absolute threshold of hearing (see [`AacEncoder::psychoacoustics`]).
44 const ATH_FLOOR: f32 = 1e-7;44 const ATH_FLOOR: f32 = 1e-7;
45+/// How far each band's allowed noise moves from its masking estimate toward the
46+/// frame's mean level: 0 keeps the masking threshold, 1 gives every band the same
47+/// absolute noise (the minimum-MSE allocation the correlation bar measures).
48+const MSE_BLEND: f32 = 0.3;
45 49
46 /// Which window shape the encoder asks for.50 /// Which window shape the encoder asks for.
47 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]51 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -311,8 +315,13 @@ impl AacEncoder {
311 c.drain(..FRAME_LEN);315 c.drain(..FRAME_LEN);
312 }316 }
313 317
314- let target = (u64::from(self.config.bitrate_bps) * FRAME_LEN as u64318+ // The stream's bitrate counts every byte written, so with ADTS on the 56-bit header
315- / u64::from(self.sample_rate.max(1))) as i32;319+ // comes out of this frame's share before the raw block gets its bits.
320+ let header_bits = if self.config.adts { 56 } else { 0 };
321+ let target = ((u64::from(self.config.bitrate_bps) * FRAME_LEN as u64
322+ / u64::from(self.sample_rate.max(1))) as i32
323+ - header_bits)
324+ .max(0);
316 let budget = target325 let budget = target
317 + self326 + self
318 .reservoir327 .reservoir
@@ -480,12 +489,21 @@ impl AacEncoder {
480 // filterbank's own leakage does, so an encoder spends its whole budget489 // filterbank's own leakage does, so an encoder spends its whole budget
481 // coding the skirts of a tone at full precision.490 // coding the skirts of a tone at full precision.
482 let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR;491 let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR;
492+ // The frame's mean level per coefficient, the reference for the MSE blend.
493+ let mean_level = (0..bands)
494+ .map(|b| f64::from(energy[b]) * f64::from(swb[b + 1] - swb[b]))
495+ .sum::<f64>()
496+ / FRAME_LEN as f64;
497+ let mean_level = (mean_level as f32).max(1e-3);
483 (0..bands)498 (0..bands)
484 .map(|b| {499 .map(|b| {
485 // Flat (noise-like) bands mask well, peaky (tonal) ones badly.500 // Flat (noise-like) bands mask well, peaky (tonal) ones badly.
486 let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0);501 let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0);
487 let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0);502 let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0);
488- (spread[b] / smr).max(floor).max(1e-3)503+ let mask = (spread[b] / smr).max(1e-3);
504+ // Geometric blend of the mask and the frame's mean level.
505+ let blended = mask.powf(1.0 - MSE_BLEND) * mean_level.powf(MSE_BLEND);
506+ blended.max(floor).max(1e-3)
489 })507 })
490 .collect()508 .collect()
491 }509 }
@@ -650,14 +668,18 @@ impl AacEncoder {
650 668
651 let mut w = BitWriter::new();669 let mut w = BitWriter::new();
652 let mut at = 0usize;670 let mut at = 0usize;
671+ // element_instance_tag numbers the elements of each type in order (ISO/IEC
672+ // 14496-3 4.5.2.1), so a layout with two CPEs or two SCEs carries distinct tags.
673+ let mut tags = [0u32; 3];
653 for plan in &elements {674 for plan in &elements {
654- let id = match plan.element {675+ let (id, kind) = match plan.element {
655- Element::Sce => 0u32,676+ Element::Sce => (0u32, 0usize),
656- Element::Cpe => 1,677+ Element::Cpe => (1, 1),
657- Element::Lfe => 3,678+ Element::Lfe => (3, 2),
658 };679 };
659 w.write_bits(id, 3);680 w.write_bits(id, 3);
660- w.write_bits(0, 4); // element_instance_tag681+ w.write_bits(tags[kind], 4); // element_instance_tag
682+ tags[kind] += 1;
661 if plan.element == Element::Cpe {683 if plan.element == Element::Cpe {
662 w.write_bit(true); // common_window684 w.write_bit(true); // common_window
663 write_ics_info(&mut w, &coded[at]);685 write_ics_info(&mut w, &coded[at]);
@@ -687,6 +709,7 @@ impl AacEncoder {
687 /// bitstream cannot carry would come back at the wrong gain, and chaining709 /// bitstream cannot carry would come back at the wrong gain, and chaining
688 /// the constraint through *silent* bands is what drags a fine scalefactor710 /// the constraint through *silent* bands is what drags a fine scalefactor
689 /// into the empty top of the spectrum and spends the frame on leakage.711 /// into the empty top of the spectrum and spends the frame on leakage.
712+ #[allow(clippy::too_many_arguments)] // the encoder passes its per-frame inputs flat; a bundling struct only moves them
690 fn quantise(713 fn quantise(
691 &self,714 &self,
692 frame: &ChannelFrame,715 frame: &ChannelFrame,
crates/ec-aac/src/knobs.rsadded+104 -0
@@ -0,0 +1,104 @@
1+//! Debug switches the AAC/SBR decoder reads from the environment, with a
2+//! per-thread override that tests set instead of editing the process
3+//! environment (which is `unsafe` in Rust 2024).
4+//!
5+//! The decoder reads these on the thread that calls `decode`, so an override
6+//! set on a test's own thread covers exactly that test's decodes and nothing
7+//! running in parallel. With no override set, each reader answers from the
8+//! environment exactly as it always has, so manual runs with `EC_AAC_*` set
9+//! behave as before.
10+
11+use std::cell::Cell;
12+use std::thread::LocalKey;
13+
14+type Slot = Cell<Option<bool>>;
15+
16+thread_local! {
17+ static TOOL_SIDEINFO_DEBUG: Slot = const { Cell::new(None) };
18+ static SBR_SIDEINFO_DEBUG: Slot = const { Cell::new(None) };
19+ static SBR_HF_BYPASS: Slot = const { Cell::new(None) };
20+ static SBR_NOISE_ZERO: Slot = const { Cell::new(None) };
21+ static SBR_NOISE_FRACTION: Slot = const { Cell::new(None) };
22+}
23+
24+/// The override on this thread if one is set, else whether `var` is set.
25+fn enabled(slot: &'static LocalKey<Slot>, var: &str) -> bool {
26+ slot.with(Cell::get)
27+ .unwrap_or_else(|| std::env::var(var).is_ok())
28+}
29+
30+fn force(slot: &'static LocalKey<Slot>, on: Option<bool>) -> Override<Option<bool>> {
31+ let prev = slot.with(|c| c.replace(on));
32+ Override { slot, prev }
33+}
34+
35+/// Restores the value a knob had before [`set_tool_sideinfo_debug`] and its
36+/// siblings were called, when dropped.
37+#[doc(hidden)]
38+#[must_use = "the override ends as soon as this guard is dropped"]
39+pub struct Override<T: Copy + 'static> {
40+ slot: &'static LocalKey<Cell<T>>,
41+ prev: T,
42+}
43+
44+impl<T: Copy + 'static> Drop for Override<T> {
45+ fn drop(&mut self) {
46+ self.slot.with(|c| c.set(self.prev));
47+ }
48+}
49+
50+/// `EC_AAC_TOOL_SIDEINFO_DEBUG`.
51+pub(crate) fn tool_sideinfo_debug() -> bool {
52+ enabled(&TOOL_SIDEINFO_DEBUG, "EC_AAC_TOOL_SIDEINFO_DEBUG")
53+}
54+
55+/// `EC_AAC_SBR_SIDEINFO_DEBUG`.
56+pub(crate) fn sbr_sideinfo_debug() -> bool {
57+ enabled(&SBR_SIDEINFO_DEBUG, "EC_AAC_SBR_SIDEINFO_DEBUG")
58+}
59+
60+/// `EC_AAC_SBR_HF_BYPASS`.
61+pub(crate) fn sbr_hf_bypass() -> bool {
62+ enabled(&SBR_HF_BYPASS, "EC_AAC_SBR_HF_BYPASS")
63+}
64+
65+/// `EC_AAC_SBR_NOISE_ZERO`.
66+pub(crate) fn sbr_noise_zero() -> bool {
67+ enabled(&SBR_NOISE_ZERO, "EC_AAC_SBR_NOISE_ZERO")
68+}
69+
70+/// `EC_AAC_SBR_NOISE_FRACTION`.
71+pub(crate) fn sbr_noise_fraction() -> bool {
72+ enabled(&SBR_NOISE_FRACTION, "EC_AAC_SBR_NOISE_FRACTION")
73+}
74+
75+/// Forces `EC_AAC_TOOL_SIDEINFO_DEBUG` on (`Some(true)`), off (`Some(false)`)
76+/// or back to the environment (`None`) on this thread, until the guard drops.
77+#[doc(hidden)]
78+pub fn set_tool_sideinfo_debug(on: Option<bool>) -> Override<Option<bool>> {
79+ force(&TOOL_SIDEINFO_DEBUG, on)
80+}
81+
82+/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_SIDEINFO_DEBUG`.
83+#[doc(hidden)]
84+pub fn set_sbr_sideinfo_debug(on: Option<bool>) -> Override<Option<bool>> {
85+ force(&SBR_SIDEINFO_DEBUG, on)
86+}
87+
88+/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_HF_BYPASS`.
89+#[doc(hidden)]
90+pub fn set_sbr_hf_bypass(on: Option<bool>) -> Override<Option<bool>> {
91+ force(&SBR_HF_BYPASS, on)
92+}
93+
94+/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_ZERO`.
95+#[doc(hidden)]
96+pub fn set_sbr_noise_zero(on: Option<bool>) -> Override<Option<bool>> {
97+ force(&SBR_NOISE_ZERO, on)
98+}
99+
100+/// [`set_tool_sideinfo_debug`] for `EC_AAC_SBR_NOISE_FRACTION`.
101+#[doc(hidden)]
102+pub fn set_sbr_noise_fraction(on: Option<bool>) -> Override<Option<bool>> {
103+ force(&SBR_NOISE_FRACTION, on)
104+}
crates/ec-aac/src/lib.rsmodified+98 -24
@@ -18,11 +18,11 @@
18 //! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE,18 //! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE,
19 //! LFE, DSE, PCE and FIL elements. HE-AAC v1 (SBR) is reconstructed: the core19 //! LFE, DSE, PCE and FIL elements. HE-AAC v1 (SBR) is reconstructed: the core
20 //! decodes, its low bands feed the SBR QMF/HF/envelope chain, and the output20 //! decodes, its low bands feed the SBR QMF/HF/envelope chain, and the output
21-//! is at the extension rate. Parametric Stereo is **not** implemented; a21+//! is at the extension rate. HE-AAC v2 adds Parametric Stereo (ISO/IEC
22-//! stream that signals it decodes to its AAC-LC core, at the core sample22+//! 14496-3 subpart 8), reconstructed as FFmpeg does: a PS stream decodes to
23-//! rate, and says so through [`AacDecoder::sbr_support`] and23+//! two channels at the extension rate. A PS element whose PS header has not
24-//! [`AacDecoder::output_sample_rate`] rather than silently claiming the24+//! been decoded yet outputs its mono SBR signal on both channels. Malformed
25-//! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests.25+//! PS data disables PS for that frame, with the same fallback.
26 26
27 #![forbid(unsafe_code)]27 #![forbid(unsafe_code)]
28 28
@@ -37,8 +37,13 @@ mod sbr_hf;
37 mod sbr_payload;37 mod sbr_payload;
38 pub mod sbr_qmf;38 pub mod sbr_qmf;
39 mod sbr_qmf_window;39 mod sbr_qmf_window;
40+mod ps_data;
41+mod ps_dsp;
42+mod ps_huff;
40 mod sbr_tables;43 mod sbr_tables;
41 pub mod tables;44 pub mod tables;
45+#[doc(hidden)]
46+pub mod knobs;
42 47
43 pub use config::{48 pub use config::{
44 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,49 AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
@@ -69,9 +74,8 @@ pub enum SbrSupport {
69 /// SBR is signalled and **is** reconstructed: the decoded audio spans74 /// SBR is signalled and **is** reconstructed: the decoded audio spans
70 /// the full extension bandwidth at the extension sample rate.75 /// the full extension bandwidth at the extension sample rate.
71 V1,76 V1,
72- /// SBR is signalled but not reconstructed (Parametric Stereo streams:77+ /// SBR is signalled but not reconstructed. Not produced by this decoder
73- /// PS itself is still unimplemented). The AAC-LC core decodes, at the78+ /// any more: Parametric Stereo streams report [`SbrSupport::V1`].
74- /// core rate, half the signalled bandwidth.
75 CoreOnly,79 CoreOnly,
76 }80 }
77 81
@@ -134,19 +138,41 @@ impl AacDecoder {
134 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {138 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
135 let mut d = AacDecoder::new();139 let mut d = AacDecoder::new();
136 d.block.set_sf_index(cfg.sf_index);140 d.block.set_sf_index(cfg.sf_index);
141+ d.block.set_pce(cfg.pce.clone());
137 d.sample_rate = cfg.sample_rate;142 d.sample_rate = cfg.sample_rate;
138 d.channels = cfg.channels;143 d.channels = cfg.channels;
139- // PS is not reconstructed; SBR is. Both still need the core144+ // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the
140- // decoded first, but only a plain-SBR (non-PS) stream gets the145+ // core is decoded first, then the extension-rate chain runs on it.
141- // extension-rate QMF chain wired in.146+ if cfg.sbr_present {
142- if cfg.sbr_present && !cfg.ps_present {
143 let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);147 let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2);
144 d.block.set_sbr_rate(Some(rate));148 d.block.set_sbr_rate(Some(rate));
149+ d.block.set_sbr_ps(cfg.ps_present);
150+ } else if !cfg.ps_present {
151+ // Plain AAC-LC config: an SBR payload may still follow (implicit signalling).
152+ d.block.set_implicit_core(cfg.sample_rate);
153+ }
154+ if cfg.ps_present {
155+ // PS output is stereo whatever the core's channel count.
156+ d.channels = 2;
145 }157 }
146 d.config = Some(cfg);158 d.config = Some(cfg);
147 d159 d
148 }160 }
149 161
162+ /// Core-only decoding: SBR and PS are never applied. An explicit SBR or PS
163+ /// config is dropped, and implicit SBR is never armed, so every SBR extension
164+ /// payload is skipped and the output stays at the core rate.
165+ pub fn core_only(mut self) -> AacDecoder {
166+ self.block.set_sbr_rate(None);
167+ self.block.disable_implicit_sbr();
168+ if let Some(c) = self.config.as_mut() {
169+ c.sbr_present = false;
170+ c.ps_present = false;
171+ c.extension_sample_rate = None;
172+ }
173+ self
174+ }
175+
150 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4176 /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
151 /// `esds` payload or a Matroska `CodecPrivate`.177 /// `esds` payload or a Matroska `CodecPrivate`.
152 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {178 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
@@ -163,23 +189,57 @@ impl AacDecoder {
163 self.config.as_ref()189 self.config.as_ref()
164 }190 }
165 191
166- /// Whether the stream asked for SBR, and what became of it.192+ /// Whether the stream asked for SBR, and what became of it. A plain AAC-LC
193+ /// stream whose frames carry an SBR payload (implicit signalling) reports
194+ /// [`SbrSupport::V1`] once the first such payload has been decoded; see
195+ /// [`AacDecoder::sbr_implicit`].
167 pub fn sbr_support(&self) -> SbrSupport {196 pub fn sbr_support(&self) -> SbrSupport {
197+ if self.block.implicit_sbr() {
198+ return SbrSupport::V1;
199+ }
168 match &self.config {200 match &self.config {
169- Some(c) if c.ps_present => SbrSupport::CoreOnly,201+ Some(c) if c.ps_present || c.sbr_present => SbrSupport::V1,
170- Some(c) if c.sbr_present => SbrSupport::V1,
171 _ => SbrSupport::NotSignalled,202 _ => SbrSupport::NotSignalled,
172 }203 }
173 }204 }
174 205
206+ /// Whether SBR was switched on by an implicit payload: a stream that
207+ /// signals plain AAC-LC (config or ADTS header) but carries an SBR
208+ /// extension payload, decoded at twice the core rate as ffmpeg and the
209+ /// ISO reference do. Only ever true once the first such payload has been
210+ /// decoded, and only for a core rate of at most 24 kHz. Explicit SBR
211+ /// signalling is reported by [`AacDecoder::sbr_support`] alone.
212+ pub fn sbr_implicit(&self) -> bool {
213+ self.block.implicit_sbr()
214+ }
215+
216+ /// Whether Parametric Stereo was switched on by an implicit payload: a
217+ /// stream that signals plain AAC-LC but whose SBR extension carries a PS
218+ /// extension (the HE-AACv2 form with no explicit signalling). Only true once
219+ /// such a PS extension has been decoded, so a caller reads it after the
220+ /// first frames. Implies [`AacDecoder::sbr_implicit`].
221+ pub fn ps_implicit(&self) -> bool {
222+ self.block.implicit_ps()
223+ }
224+
175 /// The rate the samples this decoder hands back are actually at: the225 /// The rate the samples this decoder hands back are actually at: the
176- /// extension rate for a reconstructed (V1) HE-AAC stream, the core226+ /// extension rate for a reconstructed (V1) HE-AAC or HE-AACv2 stream,
177- /// rate for plain AAC-LC or an unreconstructed (PS) stream -- claiming227+ /// the core rate for plain AAC-LC -- claiming bandwidth that was not
178- /// bandwidth that was not actually rebuilt would be a lie.228+ /// actually rebuilt would be a lie.
229+ ///
230+ /// For a decoder built from an ADTS header (no config), this is `None`
231+ /// until the first frame has been decoded. After that it is the core
232+ /// rate, or twice it once implicit SBR has switched on, so a caller
233+ /// should read it again after each packet.
179 pub fn output_sample_rate(&self) -> Option<u32> {234 pub fn output_sample_rate(&self) -> Option<u32> {
180- self.config.as_ref().map(|c| match self.sbr_support() {235+ let (core, ext) = match &self.config {
181- SbrSupport::V1 => c.extension_sample_rate.unwrap_or(c.sample_rate * 2),236+ Some(c) => (c.sample_rate, c.extension_sample_rate),
182- _ => c.sample_rate,237+ None if self.sample_rate != 0 => (self.sample_rate, None),
238+ None => return None,
239+ };
240+ Some(match self.sbr_support() {
241+ SbrSupport::V1 => ext.unwrap_or(core * 2),
242+ _ => core,
183 })243 })
184 }244 }
185 245
@@ -191,11 +251,13 @@ impl AacDecoder {
191 while at + 7 <= packet.len() {251 while at + 7 <= packet.len() {
192 let header = parse_adts(&packet[at..])?;252 let header = parse_adts(&packet[at..])?;
193 let end = (at + header.frame_length).min(packet.len());253 let end = (at + header.frame_length).min(packet.len());
194- let body = &packet[at + header.header_len..end];254+ // A truncated frame can end before its header does; clamp so the slice cannot invert.
255+ let body = &packet[(at + header.header_len).min(end)..end];
195 if self.config.is_none() {256 if self.config.is_none() {
196 self.sample_rate = header.sample_rate;257 self.sample_rate = header.sample_rate;
197 self.channels = header.channels;258 self.channels = header.channels;
198 self.block.set_sf_index(header.sf_index);259 self.block.set_sf_index(header.sf_index);
260+ self.block.set_implicit_core(header.sample_rate);
199 }261 }
200 let mut r = BitReader::new(body);262 let mut r = BitReader::new(body);
201 for _ in 0..header.raw_blocks {263 for _ in 0..header.raw_blocks {
@@ -214,6 +276,12 @@ impl AacDecoder {
214 let mut r = BitReader::new(packet);276 let mut r = BitReader::new(packet);
215 planes = self.block.raw_data_block(&mut r)?;277 planes = self.block.raw_data_block(&mut r)?;
216 }278 }
279+ // ffmpeg decodes an HE-AAC mono stream with no PS payload (SBR reconstructed, one
280+ // plane) as two identical channels ("Treating HE-AAC mono as stereo"). Match it.
281+ if planes.len() == 1 && self.sbr_support() == SbrSupport::V1 {
282+ let dup = planes[0].clone();
283+ planes.push(dup);
284+ }
217 let channels = planes.len();285 let channels = planes.len();
218 if channels == 0 {286 if channels == 0 {
219 return Ok(DecodedAudio {287 return Ok(DecodedAudio {
@@ -226,12 +294,18 @@ impl AacDecoder {
226 if self.channels == 0 {294 if self.channels == 0 {
227 self.channels = channels as u16;295 self.channels = channels as u16;
228 }296 }
229- let order = film_order(channels);297+ // A PCE names each plane's speaker, which orders the output; otherwise the
298+ // channel configuration's bitstream order does.
299+ let order = self
300+ .block
301+ .plane_order(channels)
302+ .unwrap_or_else(|| film_order(channels).to_vec());
230 let frames = planes[0].len();303 let frames = planes[0].len();
231 let mut samples = vec![0.0f32; frames * channels];304 let mut samples = vec![0.0f32; frames * channels];
232 for (out_ch, &src) in order.iter().take(channels).enumerate() {305 for (out_ch, &src) in order.iter().take(channels).enumerate() {
233 let plane = &planes[src.min(channels - 1)];306 let plane = &planes[src.min(channels - 1)];
234- for (i, &v) in plane.iter().enumerate() {307+ // Planes can differ in length after `merge`; only the first `frames` samples fit.
308+ for (i, &v) in plane.iter().take(frames).enumerate() {
235 samples[i * channels + out_ch] = v;309 samples[i * channels + out_ch] = v;
236 }310 }
237 }311 }
crates/ec-aac/src/ps_data.rsadded+532 -0
@@ -0,0 +1,532 @@
1+//! Parametric Stereo (ISO/IEC 14496-3 subpart 8): the `ps_data()` parser.
2+//!
3+//! PS rides inside an SBR extension payload (`bs_extension_id` 2, see
4+//! [`crate::sbr_payload`]). Its state persists across frames: a frame whose
5+//! header bit is clear keeps the previous frame's stereo band configuration,
6+//! and the delta-coded parameters refer back to the previous envelope. The
7+//! structure follows FFmpeg's `aacps_common.c` (`ff_ps_read_data`), including
8+//! its handling of stale fields, so that the decoded parameters match the
9+//! reference decoder frame for frame.
10+
11+use crate::ps_huff;
12+use ec_core::{BitReader, Error, Result};
13+use std::sync::OnceLock;
14+
15+/// Envelopes per frame, at most (`PS_MAX_NUM_ENV`, plus one fake envelope).
16+pub const MAX_ENV: usize = 5;
17+/// Stereo parameter bands, at most (34-band mode).
18+pub const MAX_PAR: usize = 34;
19+
20+/// Envelope count per frame class (FIXFIX, VARVAR table of `bs_num_env`).
21+const NUM_ENV_TAB: [[usize; 4]; 2] = [[0, 1, 2, 4], [1, 2, 3, 4]];
22+/// IID/ICC parameter band count per `iid_mode`/`icc_mode`.
23+const NR_IIDICC_PAR_TAB: [usize; 6] = [10, 20, 34, 10, 20, 34];
24+/// IPD/OPD parameter band count per `iid_mode`.
25+const NR_IIDOPD_PAR_TAB: [usize; 6] = [5, 11, 17, 5, 11, 17];
26+
27+/// Huffman table indices into [`ps_huff::TABLES`].
28+const HUFF_IID_DF1: usize = 0;
29+const HUFF_IID_DT1: usize = 1;
30+const HUFF_IID_DF0: usize = 2;
31+const HUFF_IID_DT0: usize = 3;
32+const HUFF_ICC_DF: usize = 4;
33+const HUFF_ICC_DT: usize = 5;
34+const HUFF_IPD_DF: usize = 6;
35+const HUFF_IPD_DT: usize = 7;
36+const HUFF_OPD_DF: usize = 8;
37+const HUFF_OPD_DT: usize = 9;
38+
39+/// `huff_iid[2 * dt + iid_quant]`: which IID table a delta/quant pair selects.
40+const HUFF_IID: [usize; 4] = [HUFF_IID_DF0, HUFF_IID_DF1, HUFF_IID_DT0, HUFF_IID_DT1];
41+
42+/// The persistent PS parser state (FFmpeg's `PSCommonContext`).
43+#[derive(Clone, Debug, PartialEq)]
44+pub struct PsCommon {
45+ /// A PS header has been parsed and the stereo processing is active.
46+ pub start: bool,
47+ pub enable_iid: bool,
48+ pub iid_quant: bool,
49+ pub nr_iid_par: usize,
50+ pub nr_ipdopd_par: usize,
51+ pub enable_icc: bool,
52+ pub icc_mode: usize,
53+ pub nr_icc_par: usize,
54+ pub enable_ext: bool,
55+ pub frame_class: usize,
56+ pub num_env_old: usize,
57+ pub num_env: usize,
58+ pub enable_ipdopd: bool,
59+ /// Envelope borders in QMF slots; entry 0 is -1 and the last is 31.
60+ pub border_position: [i32; MAX_ENV + 1],
61+ pub iid_par: [[i8; MAX_PAR]; MAX_ENV],
62+ pub icc_par: [[i8; MAX_PAR]; MAX_ENV],
63+ pub ipd_par: [[i8; MAX_PAR]; MAX_ENV],
64+ pub opd_par: [[i8; MAX_PAR]; MAX_ENV],
65+ pub is34bands: bool,
66+ pub is34bands_old: bool,
67+}
68+
69+impl Default for PsCommon {
70+ fn default() -> PsCommon {
71+ PsCommon {
72+ start: false,
73+ enable_iid: false,
74+ iid_quant: false,
75+ nr_iid_par: 0,
76+ nr_ipdopd_par: 0,
77+ enable_icc: false,
78+ icc_mode: 0,
79+ nr_icc_par: 0,
80+ enable_ext: false,
81+ frame_class: 0,
82+ num_env_old: 0,
83+ num_env: 0,
84+ enable_ipdopd: false,
85+ border_position: [0; MAX_ENV + 1],
86+ iid_par: [[0; MAX_PAR]; MAX_ENV],
87+ icc_par: [[0; MAX_PAR]; MAX_ENV],
88+ ipd_par: [[0; MAX_PAR]; MAX_ENV],
89+ opd_par: [[0; MAX_PAR]; MAX_ENV],
90+ is34bands: false,
91+ is34bands_old: false,
92+ }
93+ }
94+}
95+
96+/// One prefix-code table: every codeword as (length, code, parameter value).
97+struct Vlc {
98+ codes: Vec<(u32, u32, i32)>,
99+ max_len: u32,
100+}
101+
102+/// The ten PS Huffman tables, with canonical codes assigned from the lengths.
103+fn vlcs() -> &'static [Vlc] {
104+ static VLCS: OnceLock<Vec<Vlc>> = OnceLock::new();
105+ VLCS.get_or_init(|| {
106+ ps_huff::TABLES
107+ .iter()
108+ .zip(ps_huff::OFFSETS)
109+ .map(|(table, offset)| build_codes(table, offset))
110+ .collect()
111+ })
112+}
113+
114+/// Assigns the codewords of one table the way FFmpeg does
115+/// (`ff_vlc_init_from_lengths`): each entry takes the next free slice of the
116+/// code space in table order, so the codes are not sorted by length. The
117+/// lengths alone do not fix the codes, which is why sorting them canonically
118+/// misreads every fine-IID and ICC frame. Every table in the standard is a
119+/// complete prefix code, which the unit tests check.
120+fn build_codes(table: &[(u8, u8)], offset: i32) -> Vlc {
121+ let mut codes = Vec::with_capacity(table.len());
122+ // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow).
123+ let mut next: u64 = 0;
124+ let mut max_len = 0;
125+ for &(value, len) in table {
126+ let len = u32::from(len).clamp(1, 32);
127+ let code = (next >> (32 - len)) as u32;
128+ codes.push((len, code, i32::from(value) + offset));
129+ next += 1u64 << (32 - len);
130+ max_len = max_len.max(len);
131+ }
132+ Vlc { codes, max_len }
133+}
134+
135+/// Reads one codeword of table `which` and returns its parameter value.
136+fn read_vlc(r: &mut BitReader<'_>, which: usize) -> Result<i32> {
137+ let table = &vlcs()[which];
138+ let mut code: u32 = 0;
139+ for len in 1..=table.max_len {
140+ code = (code << 1) | u32::from(r.read_bit()?);
141+ if let Some(&(_, _, value)) = table
142+ .codes
143+ .iter()
144+ .find(|&&(l, c, _)| l == len && c == code)
145+ {
146+ return Ok(value);
147+ }
148+ }
149+ Err(Error::corrupt("ps: no codeword matches the bitstream"))
150+}
151+
152+/// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`).
153+///
154+/// `dt` selects time-differential coding against the previous envelope (the
155+/// last envelope of the previous frame for `e == 0`), otherwise the values are
156+/// frequency-differential, accumulated across the bands. `mask` (IPD/OPD) keeps
157+/// only the low three bits; `invalid` rejects a value the spec does not allow.
158+#[allow(clippy::too_many_arguments)] // mirrors FFmpeg's READ_PAR_DATA parameters
159+fn read_par(
160+ r: &mut BitReader<'_>,
161+ par: &mut [[i8; MAX_PAR]; MAX_ENV],
162+ table: usize,
163+ num: usize,
164+ e: usize,
165+ dt: bool,
166+ num_env_old: usize,
167+ mask: Option<i32>,
168+ invalid: impl Fn(i32) -> bool,
169+) -> Result<()> {
170+ if dt {
171+ let e_prev = if e > 0 { e - 1 } else { num_env_old.saturating_sub(1) };
172+ let prev = par[e_prev];
173+ for (b, slot) in par[e].iter_mut().enumerate().take(num) {
174+ let mut val = i32::from(prev[b]) + read_vlc(r, table)?;
175+ if let Some(m) = mask {
176+ val &= m;
177+ }
178+ *slot = val as i8;
179+ if invalid(i32::from(*slot)) {
180+ return Err(Error::corrupt("ps: parameter out of range"));
181+ }
182+ }
183+ } else {
184+ let mut val = 0i32;
185+ for slot in par[e].iter_mut().take(num) {
186+ val += read_vlc(r, table)?;
187+ if let Some(m) = mask {
188+ val &= m;
189+ }
190+ *slot = val as i8;
191+ if invalid(i32::from(*slot)) {
192+ return Err(Error::corrupt("ps: parameter out of range"));
193+ }
194+ }
195+ }
196+ Ok(())
197+}
198+
199+/// Skips `n` bits, stopping at the end of the buffer rather than failing.
200+fn skip_clamped(r: &mut BitReader<'_>, n: u64) {
201+ let n = n.min(r.bits_remaining());
202+ // `n` is clamped to what remains, so the skip cannot run past the buffer.
203+ let _ = r.skip_bits(n);
204+}
205+
206+impl PsCommon {
207+ /// Parses one `ps_data()` from `r`, which holds `bits_left` bits of SBR
208+ /// extension payload after the 2-bit extension id. Returns the bits the
209+ /// PS data occupies. Malformed data disables PS for the frame (the
210+ /// stereo state is cleared and the PS payload is skipped), as FFmpeg does:
211+ /// the caller then reconstructs the mono SBR output on both channels.
212+ pub fn read_data(&mut self, r: &mut BitReader<'_>, bits_left: u64) -> u64 {
213+ let mut trial = r.clone();
214+ match self.parse(&mut trial) {
215+ Ok(consumed) if consumed <= bits_left => {
216+ *r = trial;
217+ consumed
218+ }
219+ _ => {
220+ self.start = false;
221+ self.iid_par = [[0; MAX_PAR]; MAX_ENV];
222+ self.icc_par = [[0; MAX_PAR]; MAX_ENV];
223+ self.ipd_par = [[0; MAX_PAR]; MAX_ENV];
224+ self.opd_par = [[0; MAX_PAR]; MAX_ENV];
225+ skip_clamped(r, bits_left);
226+ bits_left
227+ }
228+ }
229+ }
230+
231+ /// The body of `ps_data()`; returns the bits consumed, leaving `r` after them.
232+ fn parse(&mut self, r: &mut BitReader<'_>) -> Result<u64> {
233+ let start_bit = r.bit_position();
234+ let header = r.read_bit()?;
235+ if header {
236+ self.enable_iid = r.read_bit()?;
237+ if self.enable_iid {
238+ let iid_mode = r.read_bits(3)? as usize;
239+ if iid_mode > 5 {
240+ return Err(Error::corrupt("ps: reserved iid_mode"));
241+ }
242+ self.nr_iid_par = NR_IIDICC_PAR_TAB[iid_mode];
243+ self.iid_quant = iid_mode > 2;
244+ self.nr_ipdopd_par = NR_IIDOPD_PAR_TAB[iid_mode];
245+ }
246+ self.enable_icc = r.read_bit()?;
247+ if self.enable_icc {
248+ self.icc_mode = r.read_bits(3)? as usize;
249+ if self.icc_mode > 5 {
250+ return Err(Error::corrupt("ps: reserved icc_mode"));
251+ }
252+ self.nr_icc_par = NR_IIDICC_PAR_TAB[self.icc_mode];
253+ }
254+ self.enable_ext = r.read_bit()?;
255+ }
256+ self.frame_class = usize::from(r.read_bit()?);
257+ self.num_env_old = self.num_env;
258+ self.num_env = NUM_ENV_TAB[self.frame_class][r.read_bits(2)? as usize];
259+ self.border_position[0] = -1;
260+ if self.frame_class == 1 {
261+ for e in 1..=self.num_env {
262+ self.border_position[e] = r.read_bits(5)? as i32;
263+ if self.border_position[e] < self.border_position[e - 1] {
264+ return Err(Error::corrupt("ps: envelope borders out of order"));
265+ }
266+ }
267+ } else {
268+ let log2 = match self.num_env {
269+ 0 | 1 => 0,
270+ 2 | 3 => 1,
271+ _ => 2,
272+ };
273+ for e in 1..=self.num_env {
274+ self.border_position[e] = ((e * 32) >> log2) as i32 - 1;
275+ }
276+ }
277+
278+ if self.enable_iid {
279+ let quant = usize::from(self.iid_quant);
280+ let limit = 7 + 8 * quant as i32;
281+ for e in 0..self.num_env {
282+ let dt = r.read_bit()?;
283+ let table = HUFF_IID[2 * usize::from(dt) + quant];
284+ read_par(
285+ r,
286+ &mut self.iid_par,
287+ table,
288+ self.nr_iid_par,
289+ e,
290+ dt,
291+ self.num_env_old,
292+ None,
293+ |v| v.abs() > limit,
294+ )?;
295+ }
296+ } else {
297+ self.iid_par = [[0; MAX_PAR]; MAX_ENV];
298+ }
299+
300+ if self.enable_icc {
301+ for e in 0..self.num_env {
302+ let dt = r.read_bit()?;
303+ let table = if dt { HUFF_ICC_DT } else { HUFF_ICC_DF };
304+ read_par(
305+ r,
306+ &mut self.icc_par,
307+ table,
308+ self.nr_icc_par,
309+ e,
310+ dt,
311+ self.num_env_old,
312+ None,
313+ |v| !(0..=7).contains(&v),
314+ )?;
315+ }
316+ } else {
317+ self.icc_par = [[0; MAX_PAR]; MAX_ENV];
318+ }
319+
320+ if self.enable_ext {
321+ let mut cnt = i64::from(r.read_bits(4)?);
322+ if cnt == 15 {
323+ cnt += i64::from(r.read_bits(8)?);
324+ }
325+ cnt *= 8;
326+ while cnt > 7 {
327+ let ext_id = r.read_bits(2)?;
328+ let used = self.read_extension(r, ext_id)?;
329+ let used = i64::try_from(used).map_err(|_| Error::corrupt("ps: extension size overflow"))?;
330+ cnt -= 2 + used;
331+ }
332+ if cnt < 0 {
333+ return Err(Error::corrupt("ps: extension overruns its payload"));
334+ }
335+ skip_clamped(r, cnt as u64);
336+ }
337+
338+ // The spec allows the last envelope to end early; the decoder then
339+ // holds the last parameter set until the end of the frame (a fake
340+ // envelope at slot 31), as FFmpeg does.
341+ if self.num_env == 0 || self.border_position[self.num_env] < 31 {
342+ let source = if self.num_env > 0 {
343+ Some(self.num_env - 1)
344+ } else {
345+ self.num_env_old.checked_sub(1)
346+ };
347+ if let Some(src) = source.filter(|&s| s != self.num_env) {
348+ let n = self.num_env;
349+ if self.enable_iid {
350+ self.iid_par[n] = self.iid_par[src];
351+ }
352+ if self.enable_icc {
353+ self.icc_par[n] = self.icc_par[src];
354+ }
355+ if self.enable_ipdopd {
356+ self.ipd_par[n] = self.ipd_par[src];
357+ self.opd_par[n] = self.opd_par[src];
358+ }
359+ }
360+ if self.enable_iid {
361+ let limit = 7 + 8 * i32::from(self.iid_quant);
362+ for b in 0..self.nr_iid_par {
363+ if i32::from(self.iid_par[self.num_env][b]).abs() > limit {
364+ return Err(Error::corrupt("ps: fake envelope iid out of range"));
365+ }
366+ }
367+ }
368+ if self.enable_icc {
369+ for b in 0..self.nr_iid_par {
370+ if !(0..=7).contains(&i32::from(self.icc_par[self.num_env][b])) {
371+ return Err(Error::corrupt("ps: fake envelope icc out of range"));
372+ }
373+ }
374+ }
375+ self.num_env += 1;
376+ self.border_position[self.num_env] = 31;
377+ }
378+
379+ self.is34bands_old = self.is34bands;
380+ if self.enable_iid || self.enable_icc {
381+ self.is34bands = (self.enable_iid && self.nr_iid_par == 34)
382+ || (self.enable_icc && self.nr_icc_par == 34);
383+ }
384+ if !self.enable_ipdopd {
385+ self.ipd_par = [[0; MAX_PAR]; MAX_ENV];
386+ self.opd_par = [[0; MAX_PAR]; MAX_ENV];
387+ }
388+ if header {
389+ self.start = true;
390+ }
391+ Ok(r.bit_position() - start_bit)
392+ }
393+
394+ /// One `ps_extension()` element of id `ext_id`; only id 0 carries data
395+ /// (the IPD/OPD phase parameters). Other ids are skipped by the caller.
396+ fn read_extension(&mut self, r: &mut BitReader<'_>, ext_id: u32) -> Result<u64> {
397+ if ext_id != 0 {
398+ return Ok(0);
399+ }
400+ let start = r.bit_position();
401+ self.enable_ipdopd = r.read_bit()?;
402+ if self.enable_ipdopd {
403+ for e in 0..self.num_env {
404+ let dt = r.read_bit()?;
405+ let table = if dt { HUFF_IPD_DT } else { HUFF_IPD_DF };
406+ read_par(
407+ r,
408+ &mut self.ipd_par,
409+ table,
410+ self.nr_ipdopd_par,
411+ e,
412+ dt,
413+ self.num_env_old,
414+ Some(0x07),
415+ |_| false,
416+ )?;
417+ let dt = r.read_bit()?;
418+ let table = if dt { HUFF_OPD_DT } else { HUFF_OPD_DF };
419+ read_par(
420+ r,
421+ &mut self.opd_par,
422+ table,
423+ self.nr_ipdopd_par,
424+ e,
425+ dt,
426+ self.num_env_old,
427+ Some(0x07),
428+ |_| false,
429+ )?;
430+ }
431+ }
432+ r.skip_bits(1)?; // reserved_ps
433+ Ok(r.bit_position() - start)
434+ }
435+}
436+
437+#[cfg(test)]
438+mod tests {
439+ use super::*;
440+
441+ #[test]
442+ fn every_ps_codebook_is_a_complete_prefix_code() {
443+ // Kraft sum exactly 1: the tables are complete, so every bit string
444+ // decodes to some codeword and the canonical assignment is consistent.
445+ for (i, table) in ps_huff::TABLES.iter().enumerate() {
446+ let kraft: f64 = table.iter().map(|&(_, len)| 0.5f64.powi(i32::from(len))).sum();
447+ assert!((kraft - 1.0).abs() < 1e-12, "table {i} Kraft sum {kraft}");
448+ // Codeword counts of FFmpeg's aacps_huff_tabs, in table order.
449+ const SIZES: [usize; 10] = [61, 61, 29, 29, 15, 15, 8, 8, 8, 8];
450+ assert_eq!(table.len(), SIZES[i], "table {i} size");
451+ }
452+ }
453+
454+ #[test]
455+ fn codes_follow_table_order_as_ffmpeg_assigns_them() {
456+ // FFmpeg takes each entry's code as the next free slice of the code
457+ // space in table order. The first two IID fine entries are (value -2,
458+ // length 4) and (value +2, length 4), so they get codes 0000 and 0001,
459+ // not the canonical order a length sort would give.
460+ let v = build_codes(ps_huff::TABLES[HUFF_IID_DF1], ps_huff::OFFSETS[HUFF_IID_DF1]);
461+ assert_eq!(v.codes[0], (4, 0b0000, -2));
462+ assert_eq!(v.codes[1], (4, 0b0001, 2));
463+ assert_eq!(v.codes[2], (3, 0b001, -1));
464+ }
465+
466+ #[test]
467+ fn codes_are_prefix_free_and_values_cover_the_range() {
468+ for (i, table) in ps_huff::TABLES.iter().enumerate() {
469+ let v = build_codes(table, ps_huff::OFFSETS[i]);
470+ for (a, &(la, ca, _)) in v.codes.iter().enumerate() {
471+ for &(lb, cb, _) in v.codes.iter().skip(a + 1) {
472+ let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) };
473+ assert!(cl >> (long - short) != cs, "table {i} codes collide");
474+ }
475+ }
476+ }
477+ }
478+
479+ #[test]
480+ fn a_zero_delta_iid_stream_round_trips_through_read_data() {
481+ // Header on, IID on (mode 0: 10 bands, fine quant off), ICC off, no
482+ // extension, FIXFIX, one envelope, IID df0 with all-zero deltas.
483+ // df0 symbol for delta 0 is 14 (value 0 after the -14 offset) with a
484+ // one-bit code: a stream of 1s for each of 10 bands.
485+ let mut bits: Vec<bool> = Vec::new();
486+ let push = |bits: &mut Vec<bool>, v: u32, n: u32| {
487+ for i in (0..n).rev() {
488+ bits.push((v >> i) & 1 == 1);
489+ }
490+ };
491+ push(&mut bits, 1, 1); // header
492+ push(&mut bits, 1, 1); // enable_iid
493+ push(&mut bits, 0, 3); // iid_mode 0
494+ push(&mut bits, 0, 1); // enable_icc
495+ push(&mut bits, 0, 1); // enable_ext
496+ push(&mut bits, 0, 1); // frame_class FIXFIX
497+ push(&mut bits, 1, 2); // num_env index 1 -> 1 envelope
498+ push(&mut bits, 0, 1); // dt = 0 for the envelope
499+ let code_for_zero = {
500+ let v = build_codes(ps_huff::TABLES[HUFF_IID_DF0], ps_huff::OFFSETS[HUFF_IID_DF0]);
501+ *v.codes.iter().find(|c| c.2 == 0).expect("zero is a codeword")
502+ };
503+ for _ in 0..10 {
504+ push(&mut bits, code_for_zero.1, code_for_zero.0);
505+ }
506+ let mut bytes = vec![0u8; bits.len().div_ceil(8) + 1];
507+ for (i, &bit) in bits.iter().enumerate() {
508+ if bit {
509+ bytes[i / 8] |= 0x80 >> (i % 8);
510+ }
511+ }
512+ let mut r = BitReader::new(&bytes);
513+ let mut ps = PsCommon::default();
514+ let used = ps.read_data(&mut r, bits.len() as u64 + 16);
515+ assert_eq!(used, bits.len() as u64, "consumes exactly the coded bits");
516+ assert!(ps.start);
517+ assert_eq!(ps.num_env, 1);
518+ assert_eq!(ps.nr_iid_par, 10);
519+ assert!(ps.iid_par[0][..10].iter().all(|&v| v == 0));
520+ }
521+
522+ #[test]
523+ fn malformed_ps_clears_the_stereo_state_and_skips_its_payload() {
524+ // iid_mode 6 is reserved: the frame's PS is dropped, bits skipped.
525+ let bytes = [0b1111_0110u8, 0, 0, 0];
526+ let mut r = BitReader::new(&bytes);
527+ let mut ps = PsCommon { start: true, ..PsCommon::default() };
528+ let used = ps.read_data(&mut r, 32);
529+ assert_eq!(used, 32);
530+ assert!(!ps.start);
531+ }
532+}
crates/ec-aac/src/ps_dsp.rsadded+922 -0
@@ -0,0 +1,922 @@
1+//! Parametric Stereo reconstruction (ISO/IEC 14496-3 subpart 8.6.4).
2+//!
3+//! This is a port of FFmpeg's `aacps.c` and `aacpsdsp_template.c`, with the
4+//! same index conventions and the same closed-form tables (`aacps_tablegen.h`),
5+//! computed here in `f64`. The mono SBR QMF output is complex-valued: a QMF
6+//! sample is `Complex { re, im }`, and the reference stores it as `[re, im]`.
7+//!
8+//! Per frame: the low QMF bands go through a hybrid filterbank (bands 0..2 are
9+//! split into 6+2+2 subbands in 20-band mode, 12+8+4+4+4 in 34-band mode),
10+//! a decorrelator makes a second signal `d` from the mono signal `s`, and per
11+//! stereo band the IID/ICC (optionally IPD/OPD) parameters mix `(s, d)` into
12+//! the left and right signals. Envelope borders interpolate the mixing matrices
13+//! linearly. The hybrid synthesis folds the subbands back to QMF bands.
14+
15+use crate::ps_data::{MAX_ENV, MAX_PAR, PsCommon};
16+use crate::ps_huff::{K_TO_I_20, K_TO_I_34};
17+use ec_dsp::Complex;
18+use std::f64::consts::{FRAC_1_SQRT_2, PI, SQRT_2};
19+use std::ops::Range;
20+use std::sync::OnceLock;
21+
22+type Cx = Complex<f64>;
23+
24+/// QMF time slots per SBR frame (`PS_QMF_TIME_SLOTS`).
25+const SLOTS: usize = 32;
26+/// Slots the SBR hands to PS per frame: the frame plus the 6-slot lookahead.
27+pub const IN_SLOTS: usize = 38;
28+/// QMF bands of the SBR synthesis.
29+pub const QMF_BANDS: usize = 64;
30+/// Lookahead of the hybrid filter, in slots.
31+const HIST: usize = 6;
32+/// Hybrid input window per low band: history plus the 38 new slots.
33+const IN_BUF_LEN: usize = HIST + IN_SLOTS;
34+/// Low QMF bands that the hybrid filterbank splits.
35+const LOW_BANDS: usize = 5;
36+/// Subband rows of the hybrid filterbank.
37+const MAX_SUB: usize = 91;
38+const MAX_DELAY: usize = 14;
39+const MAX_AP_DELAY: usize = 5;
40+const AP_LINKS: usize = 3;
41+const MAX_ALLPASS: usize = 50;
42+
43+const NR_PAR_BANDS: [usize; 2] = [20, 34];
44+const NR_IPDOPD_BANDS: [usize; 2] = [11, 17];
45+const NR_BANDS: [usize; 2] = [71, 91];
46+const DECAY_CUTOFF: [i32; 2] = [10, 32];
47+const NR_ALLPASS_BANDS: [usize; 2] = [30, 50];
48+const SHORT_DELAY_BAND: [usize; 2] = [42, 62];
49+/// All-pass decay slope per band above the cutoff.
50+const DECAY_SLOPE: f64 = 0.05;
51+const PEAK_DECAY_FACTOR: f64 = 0.765_928_338_364_65;
52+const TRANSIENT_IMPACT: f64 = 1.5;
53+const A_SMOOTH: f64 = 0.25;
54+/// All-pass feedback coefficients (`a[m]`).
55+const AP_A: [f64; AP_LINKS] = [0.651_439_057_531_06, 0.564_718_122_007_76, 0.489_541_659_556_95];
56+
57+/// Hybrid prototype filters (`g0_Q8`, `g0_Q12`, `g1_Q8`, `g2_Q4`, `g1_Q2`).
58+const G0_Q8: [f64; 7] = [0.007_460_829_498_12, 0.022_704_209_498_25, 0.045_468_659_304_73, 0.072_661_139_295_91, 0.098_851_085_752_64, 0.117_937_105_672_17, 0.125];
59+const G0_Q12: [f64; 7] = [0.040_811_799_246_92, 0.038_128_109_949_26, 0.051_449_081_356_99, 0.063_998_311_515_92, 0.074_283_138_011_06, 0.081_003_478_929_14, 0.083_333_333_333_33];
60+const G1_Q8: [f64; 7] = [0.015_656_756_001_22, 0.037_527_163_919_91, 0.054_178_913_787_82, 0.084_170_441_167_67, 0.103_073_441_580_36, 0.122_224_522_497_53, 0.125];
61+const G2_Q4: [f64; 7] = [-0.059_082_111_556_39, -0.048_714_983_749_46, 0.0, 0.077_787_239_158_51, 0.164_863_035_674_03, 0.232_798_566_629_96, 0.25];
62+const G1_Q2: [f64; 7] = [0.0, 0.018_994_875_260_49, 0.0, -0.072_931_391_675_38, 0.0, 0.305_966_305_451_68, 0.5];
63+
64+/// `iid_par_dequant_default` followed by `iid_par_dequant_fine` (46 values).
65+const IID_DEQUANT: [f64; 46] = [
66+ 0.056_234_132_519_03, 0.125_892_541_179_42, 0.199_526_231_496_89, 0.316_227_766_016_84,
67+ 0.446_683_592_150_96, 0.630_957_344_480_19, 0.794_328_234_724_28, 1.0,
68+ 1.258_925_411_794_17, 1.584_893_192_461_11, 2.238_721_138_568_34, 3.162_277_660_168_38,
69+ 5.011_872_336_272_72, 7.943_282_347_242_84, 17.782_794_100_389_2,
70+ 0.003_162_277_660_17, 0.005_623_413_251_90, 0.01, 0.017_782_794_100_39,
71+ 0.031_622_776_601_68, 0.056_234_132_519_03, 0.079_432_823_472_43, 0.112_201_845_430_20,
72+ 0.158_489_319_246_11, 0.223_872_113_856_83, 0.316_227_766_016_84, 0.398_107_170_553_50,
73+ 0.501_187_233_627_27, 0.630_957_344_480_19, 0.794_328_234_724_28, 1.0,
74+ 1.258_925_411_794_17, 1.584_893_192_461_11, 1.995_262_314_968_88, 2.511_886_431_509_58,
75+ 3.162_277_660_168_38, 4.466_835_921_509_63, 6.309_573_444_801_93, 8.912_509_381_337_45,
76+ 12.589_254_117_941_7, 17.782_794_100_389_2, 31.622_776_601_683_8, 56.234_132_519_034_9,
77+ 100.0, 177.827_941_003_892, 316.227_766_016_837,
78+];
79+const ICC_INVQ: [f64; 8] = [1.0, 0.937, 0.841_18, 0.600_92, 0.367_64, 0.0, -0.589, -1.0];
80+const ACOS_ICC_INVQ: [f64; 8] = [0.0, 0.356_855_27, 0.571_334_66, 0.926_144_72, 1.194_326_3, PI / 2.0, 2.200_617_1, PI];
81+const IPDOPD_SIN: [f64; 8] = [0.0, FRAC_1_SQRT_2, 1.0, FRAC_1_SQRT_2, 0.0, -FRAC_1_SQRT_2, -1.0, -FRAC_1_SQRT_2];
82+const IPDOPD_COS: [f64; 8] = [1.0, FRAC_1_SQRT_2, 0.0, -FRAC_1_SQRT_2, -1.0, -FRAC_1_SQRT_2, 0.0, FRAC_1_SQRT_2];
83+const F_CENTER_20: [f64; 10] = [-3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 10.0, 14.0, 18.0, 22.0];
84+const F_CENTER_34: [f64; 32] = [
85+ 2.0, 6.0, 10.0, 14.0, 18.0, 22.0, 26.0, 30.0, 34.0, -10.0, -6.0, -2.0, 51.0, 57.0, 15.0, 21.0,
86+ 27.0, 33.0, 39.0, 45.0, 54.0, 66.0, 78.0, 42.0, 102.0, 66.0, 78.0, 90.0, 102.0, 114.0, 126.0, 90.0,
87+];
88+const FRACTIONAL_DELAY_LINKS: [f64; AP_LINKS] = [0.43, 0.75, 0.347];
89+const FRACTIONAL_DELAY_GAIN: f64 = 0.39;
90+
91+/// The closed-form tables of `ps_tableinit()` (`aacps_tablegen.h`).
92+struct Tables {
93+ /// Phase smoothing, indexed by three 3-bit phase digits (`pd0*64+pd1*8+pd2`).
94+ pd_re: Vec<f64>,
95+ pd_im: Vec<f64>,
96+ /// IID/ICC to mixing matrix: `[iid][icc] = [h11, h12, h21, h22]`.
97+ ha: Vec<[[f64; 4]; 8]>,
98+ hb: Vec<[[f64; 4]; 8]>,
99+ /// Hybrid analysis filters: `[band][tap] = [re, im]`.
100+ f20_0_8: [[[f64; 2]; 8]; 8],
101+ f34_0_12: [[[f64; 2]; 8]; 12],
102+ f34_1_8: [[[f64; 2]; 8]; 8],
103+ f34_2_4: [[[f64; 2]; 8]; 4],
104+ /// Per mode and all-pass band: the link rotations and the overall phase.
105+ q_fract: [Vec<[[f64; 2]; AP_LINKS]>; 2],
106+ phi_fract: [Vec<[f64; 2]>; 2],
107+}
108+
109+fn tables() -> &'static Tables {
110+ static TABLES: OnceLock<Tables> = OnceLock::new();
111+ TABLES.get_or_init(build_tables)
112+}
113+
114+fn make_filters<const N: usize>(proto: &[f64; 7]) -> [[[f64; 2]; 8]; N] {
115+ let mut out = [[[0.0f64; 2]; 8]; N];
116+ for (q, band) in out.iter_mut().enumerate() {
117+ for (n, tap) in band.iter_mut().enumerate().take(7) {
118+ let theta = 2.0 * PI * (q as f64 + 0.5) * (n as f64 - 6.0) / N as f64;
119+ tap[0] = proto[n] * theta.cos();
120+ tap[1] = proto[n] * -theta.sin();
121+ }
122+ }
123+ out
124+}
125+
126+fn build_tables() -> Tables {
127+ let mut pd_re = vec![0.0; 512];
128+ let mut pd_im = vec![0.0; 512];
129+ for pd0 in 0..8 {
130+ for pd1 in 0..8 {
131+ for pd2 in 0..8 {
132+ let re = 0.25 * IPDOPD_COS[pd0] + 0.5 * IPDOPD_COS[pd1] + IPDOPD_COS[pd2];
133+ let im = 0.25 * IPDOPD_SIN[pd0] + 0.5 * IPDOPD_SIN[pd1] + IPDOPD_SIN[pd2];
134+ let mag = 1.0 / im.hypot(re);
135+ pd_re[pd0 * 64 + pd1 * 8 + pd2] = re * mag;
136+ pd_im[pd0 * 64 + pd1 * 8 + pd2] = im * mag;
137+ }
138+ }
139+ }
140+
141+ let mut ha = vec![[[0.0f64; 4]; 8]; 46];
142+ let mut hb = vec![[[0.0f64; 4]; 8]; 46];
143+ for (iid, &c) in IID_DEQUANT.iter().enumerate() {
144+ let c1 = SQRT_2 / (1.0 + c * c).sqrt();
145+ let c2 = c * c1;
146+ for icc in 0..8 {
147+ let alpha = 0.5 * ACOS_ICC_INVQ[icc];
148+ let beta = alpha * (c1 - c2) * FRAC_1_SQRT_2;
149+ ha[iid][icc] = [
150+ c2 * (beta + alpha).cos(),
151+ c1 * (beta - alpha).cos(),
152+ c2 * (beta + alpha).sin(),
153+ c1 * (beta - alpha).sin(),
154+ ];
155+
156+ let rho = ICC_INVQ[icc].max(0.05);
157+ let mut alpha = 0.5 * (2.0 * c * rho).atan2(c * c - 1.0);
158+ let mu0 = c + 1.0 / c;
159+ let mu = (1.0 + (4.0 * rho * rho - 4.0) / (mu0 * mu0)).sqrt();
160+ let gamma = (((1.0 - mu) / (1.0 + mu)).sqrt()).atan();
161+ if alpha < 0.0 {
162+ alpha += PI / 2.0;
163+ }
164+ let (ac, asn) = (alpha.cos(), alpha.sin());
165+ let (gc, gs) = (gamma.cos(), gamma.sin());
166+ hb[iid][icc] = [SQRT_2 * ac * gc, SQRT_2 * asn * gc, -SQRT_2 * asn * gs, SQRT_2 * ac * gs];
167+ }
168+ }
169+
170+ let mut q_fract: [Vec<[[f64; 2]; AP_LINKS]>; 2] = [Vec::new(), Vec::new()];
171+ let mut phi_fract: [Vec<[f64; 2]>; 2] = [Vec::new(), Vec::new()];
172+ for mode in 0..2 {
173+ for k in 0..NR_ALLPASS_BANDS[mode] {
174+ let f_center = if mode == 0 {
175+ F_CENTER_20.get(k).map_or(k as f64 - 6.5, |f| f * 0.125)
176+ } else {
177+ F_CENTER_34.get(k).map_or(k as f64 - 26.5, |f| f / 24.0)
178+ };
179+ let mut q = [[0.0f64; 2]; AP_LINKS];
180+ for (m, link) in q.iter_mut().enumerate() {
181+ let theta = -PI * FRACTIONAL_DELAY_LINKS[m] * f_center;
182+ *link = [theta.cos(), theta.sin()];
183+ }
184+ q_fract[mode].push(q);
185+ let theta = -PI * FRACTIONAL_DELAY_GAIN * f_center;
186+ phi_fract[mode].push([theta.cos(), theta.sin()]);
187+ }
188+ }
189+
190+ Tables {
191+ pd_re,
192+ pd_im,
193+ ha,
194+ hb,
195+ f20_0_8: make_filters::<8>(&G0_Q8),
196+ f34_0_12: make_filters::<12>(&G0_Q12),
197+ f34_1_8: make_filters::<8>(&G1_Q8),
198+ f34_2_4: make_filters::<4>(&G2_Q4),
199+ q_fract,
200+ phi_fract,
201+ }
202+}
203+
204+/// Maps a 10-band index to 20 bands (`map_idx_10_to_20`).
205+fn map_idx_10_to_20(dst: &mut [i8; MAX_PAR], par: &[i8; MAX_PAR], full: bool) {
206+ let mut b: isize = if full {
207+ 9
208+ } else {
209+ dst[10] = 0;
210+ 4
211+ };
212+ while b >= 0 {
213+ let v = par[b as usize];
214+ dst[2 * b as usize + 1] = v;
215+ dst[2 * b as usize] = v;
216+ b -= 1;
217+ }
218+}
219+
220+/// Maps a 34-band index to 20 bands (`map_idx_34_to_20`).
221+fn map_idx_34_to_20(dst: &mut [i8; MAX_PAR], par: &[i8; MAX_PAR], full: bool) {
222+ let p = |i: usize| i32::from(par[i]);
223+ let half = |a: i32, b: i32| (a + b) / 2;
224+ dst[0] = ((2 * p(0) + p(1)) / 3) as i8;
225+ dst[1] = ((p(1) + 2 * p(2)) / 3) as i8;
226+ dst[2] = ((2 * p(3) + p(4)) / 3) as i8;
227+ dst[3] = ((p(4) + 2 * p(5)) / 3) as i8;
228+ dst[4] = half(p(6), p(7)) as i8;
229+ dst[5] = half(p(8), p(9)) as i8;
230+ dst[6] = par[10];
231+ dst[7] = par[11];
232+ dst[8] = half(p(12), p(13)) as i8;
233+ dst[9] = half(p(14), p(15)) as i8;
234+ dst[10] = par[16];
235+ if full {
236+ dst[11] = par[17];
237+ dst[12] = par[18];
238+ dst[13] = par[19];
239+ dst[14] = half(p(20), p(21)) as i8;
240+ dst[15] = half(p(22), p(23)) as i8;
241+ dst[16] = half(p(24), p(25)) as i8;
242+ dst[17] = half(p(26), p(27)) as i8;
243+ dst[18] = ((p(28) + p(29) + p(30) + p(31)) / 4) as i8;
244+ dst[19] = half(p(32), p(33)) as i8;
245+ }
246+}
247+
248+/// Maps 34-band values to 20 bands in place (`map_val_34_to_20`).
249+fn map_val_34_to_20(par: &mut [f64; MAX_PAR]) {
250+ const THIRD: f64 = 0.333_333_33;
251+ let half = |a: f64, b: f64| (a + b) * 0.5;
252+ par[0] = (2.0 * par[0] + par[1]) * THIRD;
253+ par[1] = (par[1] + 2.0 * par[2]) * THIRD;
254+ par[2] = (2.0 * par[3] + par[4]) * THIRD;
255+ par[3] = (par[4] + 2.0 * par[5]) * THIRD;
256+ par[4] = half(par[6], par[7]);
257+ par[5] = half(par[8], par[9]);
258+ par[6] = par[10];
259+ par[7] = par[11];
260+ par[8] = half(par[12], par[13]);
261+ par[9] = half(par[14], par[15]);
262+ par[10] = par[16];
263+ par[11] = par[17];
264+ par[12] = par[18];
265+ par[13] = par[19];
266+ par[14] = half(par[20], par[21]);
267+ par[15] = half(par[22], par[23]);
268+ par[16] = half(par[24], par[25]);
269+ par[17] = half(par[26], par[27]);
270+ par[18] = (par[28] + par[29] + par[30] + par[31]) * 0.25;
271+ par[19] = half(par[32], par[33]);
272+}
273+
274+/// Maps a 10-band index to 34 bands (`map_idx_10_to_34`).
275+fn map_idx_10_to_34(dst: &mut [i8; MAX_PAR], par: &[i8; MAX_PAR], full: bool) {
276+ if full {
277+ dst[28..34].fill(par[9]);
278+ dst[24..28].fill(par[8]);
279+ dst[20..24].fill(par[7]);
280+ dst[19] = par[6];
281+ dst[18] = par[6];
282+ dst[17] = par[5];
283+ dst[16] = par[5];
284+ } else {
285+ dst[16] = 0;
286+ }
287+ dst[15] = par[4];
288+ dst[14] = par[4];
289+ dst[13] = par[4];
290+ dst[12] = par[4];
291+ dst[11] = par[3];
292+ dst[10] = par[3];
293+ dst[9] = par[2];
294+ dst[8] = par[2];
295+ dst[7] = par[2];
296+ dst[6] = par[2];
297+ dst[5] = par[1];
298+ dst[4] = par[1];
299+ dst[3] = par[1];
300+ dst[2] = par[0];
301+ dst[1] = par[0];
302+ dst[0] = par[0];
303+}
304+
305+/// Maps a 20-band index to 34 bands (`map_idx_20_to_34`).
306+fn map_idx_20_to_34(dst: &mut [i8; MAX_PAR], par: &[i8; MAX_PAR], full: bool) {
307+ let p = |i: usize| i32::from(par[i]);
308+ if full {
309+ dst[33] = par[19];
310+ dst[32] = par[19];
311+ dst[31] = par[18];
312+ dst[30] = par[18];
313+ dst[29] = par[18];
314+ dst[28] = par[18];
315+ dst[27] = par[17];
316+ dst[26] = par[17];
317+ dst[25] = par[16];
318+ dst[24] = par[16];
319+ dst[23] = par[15];
320+ dst[22] = par[15];
321+ dst[21] = par[14];
322+ dst[20] = par[14];
323+ dst[19] = par[13];
324+ dst[18] = par[12];
325+ dst[17] = par[11];
326+ }
327+ dst[16] = par[10];
328+ dst[15] = par[9];
329+ dst[14] = par[9];
330+ dst[13] = par[8];
331+ dst[12] = par[8];
332+ dst[11] = par[7];
333+ dst[10] = par[6];
334+ dst[9] = par[5];
335+ dst[8] = par[5];
336+ dst[7] = par[4];
337+ dst[6] = par[4];
338+ dst[5] = par[3];
339+ dst[4] = ((p(2) + p(3)) / 2) as i8;
340+ dst[3] = par[2];
341+ dst[2] = par[1];
342+ dst[1] = ((p(0) + p(1)) / 2) as i8;
343+ dst[0] = par[0];
344+}
345+
346+/// Maps 20-band values to 34 bands in place (`map_val_20_to_34`).
347+fn map_val_20_to_34(par: &mut [f64; MAX_PAR]) {
348+ par[33] = par[19];
349+ par[32] = par[19];
350+ par[31] = par[18];
351+ par[30] = par[18];
352+ par[29] = par[18];
353+ par[28] = par[18];
354+ par[27] = par[17];
355+ par[26] = par[17];
356+ par[25] = par[16];
357+ par[24] = par[16];
358+ par[23] = par[15];
359+ par[22] = par[15];
360+ par[21] = par[14];
361+ par[20] = par[14];
362+ par[19] = par[13];
363+ par[18] = par[12];
364+ par[17] = par[11];
365+ par[16] = par[10];
366+ par[15] = par[9];
367+ par[14] = par[9];
368+ par[13] = par[8];
369+ par[12] = par[8];
370+ par[11] = par[7];
371+ par[10] = par[6];
372+ par[9] = par[5];
373+ par[8] = par[5];
374+ par[7] = par[4];
375+ par[6] = par[4];
376+ par[5] = par[3];
377+ par[4] = (par[2] + par[3]) * 0.5;
378+ par[3] = par[2];
379+ par[2] = par[1];
380+ par[1] = (par[0] + par[1]) * 0.5;
381+}
382+
383+/// Remaps an index array onto the 34-band layout (`remap34`).
384+fn remap34(par: &[[i8; MAX_PAR]; MAX_ENV], num_par: usize, num_env: usize, full: bool) -> [[i8; MAX_PAR]; MAX_ENV] {
385+ let mut out = *par;
386+ if num_par == 20 || num_par == 11 {
387+ for e in 0..num_env.min(MAX_ENV) {
388+ map_idx_20_to_34(&mut out[e], &par[e], full);
389+ }
390+ } else if num_par == 10 || num_par == 5 {
391+ for e in 0..num_env.min(MAX_ENV) {
392+ map_idx_10_to_34(&mut out[e], &par[e], full);
393+ }
394+ }
395+ out
396+}
397+
398+/// Remaps an index array onto the 20-band layout (`remap20`).
399+fn remap20(par: &[[i8; MAX_PAR]; MAX_ENV], num_par: usize, num_env: usize, full: bool) -> [[i8; MAX_PAR]; MAX_ENV] {
400+ let mut out = *par;
401+ if num_par == 34 || num_par == 17 {
402+ for e in 0..num_env.min(MAX_ENV) {
403+ map_idx_34_to_20(&mut out[e], &par[e], full);
404+ }
405+ } else if num_par == 10 || num_par == 5 {
406+ for e in 0..num_env.min(MAX_ENV) {
407+ map_idx_10_to_20(&mut out[e], &par[e], full);
408+ }
409+ }
410+ out
411+}
412+
413+/// Lifts an SBR QMF sample (single precision) to the working precision.
414+fn lift(v: Complex<f32>) -> Cx {
415+ Cx { re: f64::from(v.re), im: f64::from(v.im) }
416+}
417+
418+/// Lowers a working-precision QMF slab back to the SBR's single precision.
419+fn narrow(v: &[[Cx; QMF_BANDS]; SLOTS]) -> [[Complex<f32>; QMF_BANDS]; SLOTS] {
420+ let mut out = [[Complex { re: 0.0f32, im: 0.0f32 }; QMF_BANDS]; SLOTS];
421+ for (o, row) in out.iter_mut().zip(v.iter()) {
422+ for (dst, src) in o.iter_mut().zip(row.iter()) {
423+ *dst = Complex { re: src.re as f32, im: src.im as f32 };
424+ }
425+ }
426+ out
427+}
428+
429+/// One output plane of the PS engine: `[slot][QMF band]`.
430+type QmfPlane = [[Complex<f32>; QMF_BANDS]; SLOTS];
431+
432+/// Symmetric-real filter bank of one hybrid band (`ps_hybrid_analysis_c`).
433+///
434+/// Output `i` is centred on input slot `i + 6`, reading slots `i..i + 13`.
435+fn analysis_bank<const N: usize>(inp: &[Cx; IN_BUF_LEN], filt: &[[[f64; 2]; 8]; N], out: &mut [[Cx; SLOTS]]) {
436+ for i in 0..SLOTS {
437+ let w = &inp[i..i + 13];
438+ let mut inre0 = [0.0f64; 6];
439+ let mut inre1 = [0.0f64; 6];
440+ let mut inim0 = [0.0f64; 6];
441+ let mut inim1 = [0.0f64; 6];
442+ for j in 0..6 {
443+ inre0[j] = w[j].re + w[12 - j].re;
444+ inre1[j] = w[j].im - w[12 - j].im;
445+ inim0[j] = w[j].im + w[12 - j].im;
446+ inim1[j] = w[j].re - w[12 - j].re;
447+ }
448+ for (n, row) in out.iter_mut().enumerate().take(N) {
449+ let f = &filt[n];
450+ let mut sum_re = f[6][0] * w[6].re;
451+ let mut sum_im = f[6][0] * w[6].im;
452+ for j in 0..6 {
453+ sum_re += f[j][0] * inre0[j] - f[j][1] * inre1[j];
454+ sum_im += f[j][0] * inim0[j] + f[j][1] * inim1[j];
455+ }
456+ row[i] = Cx { re: sum_re, im: sum_im };
457+ }
458+ }
459+}
460+
461+/// Splits one low band into two subbands with a symmetric real filter
462+/// (`hybrid2_re`). `reverse` selects which of the two rows gets the sum.
463+fn hybrid2(inp: &[Cx; IN_BUF_LEN], base: usize, reverse: bool, out: &mut [[Cx; SLOTS]; MAX_SUB]) {
464+ let r = usize::from(reverse);
465+ for i in 0..SLOTS {
466+ let w = &inp[i..];
467+ let re_in = G1_Q2[6] * w[6].re;
468+ let im_in = G1_Q2[6] * w[6].im;
469+ let mut re_op = 0.0;
470+ let mut im_op = 0.0;
471+ for j in [0usize, 2, 4] {
472+ re_op += G1_Q2[j + 1] * (w[j + 1].re + w[11 - j].re);
473+ im_op += G1_Q2[j + 1] * (w[j + 1].im + w[11 - j].im);
474+ }
475+ out[base + r][i] = Cx { re: re_in + re_op, im: im_in + im_op };
476+ out[base + 1 - r][i] = Cx { re: re_in - re_op, im: im_in - im_op };
477+ }
478+}
479+
480+/// Copies QMF bands `start..64` straight into subband rows `base + band`
481+/// (`hybrid_analysis_ileave`).
482+fn interleave(input: &[[Complex<f32>; QMF_BANDS]; IN_SLOTS], base: usize, start: usize, out: &mut [[Cx; SLOTS]; MAX_SUB]) {
483+ for band in start..QMF_BANDS {
484+ for j in 0..SLOTS {
485+ out[base + band][j] = lift(input[j][band]);
486+ }
487+ }
488+}
489+
490+/// Folds subband rows back into QMF bands (`hybrid_synthesis`).
491+fn hybrid_synthesis(sub: &[[Cx; SLOTS]; MAX_SUB], is34: bool) -> [[Cx; QMF_BANDS]; SLOTS] {
492+ let mut out = [[Cx::default(); QMF_BANDS]; SLOTS];
493+ let sum = |n: usize, rows: Range<usize>| {
494+ let mut acc = Cx::default();
495+ for r in rows {
496+ acc.re += sub[r][n].re;
497+ acc.im += sub[r][n].im;
498+ }
499+ acc
500+ };
501+ for (n, o) in out.iter_mut().enumerate() {
502+ if is34 {
503+ o[0] = sum(n, 0..12);
504+ o[1] = sum(n, 12..20);
505+ o[2] = sum(n, 20..24);
506+ o[3] = sum(n, 24..28);
507+ o[4] = sum(n, 28..32);
508+ for band in 5..QMF_BANDS {
509+ o[band] = sub[27 + band][n];
510+ }
511+ } else {
512+ o[0] = sum(n, 0..6);
513+ o[1] = sum(n, 6..8);
514+ o[2] = sum(n, 8..10);
515+ for band in 3..QMF_BANDS {
516+ o[band] = sub[7 + band][n];
517+ }
518+ }
519+ }
520+ out
521+}
522+
523+/// Shifts a decorrelator delay line by one frame and appends the new slots.
524+fn shift_delay(delay: &mut [Cx; SLOTS + MAX_DELAY], s: &[Cx; SLOTS]) {
525+ delay.copy_within(SLOTS..SLOTS + MAX_DELAY, 0);
526+ delay[MAX_DELAY..].copy_from_slice(s);
527+}
528+
529+/// One all-pass decorrelator band (`ps_decorrelate_c`).
530+///
531+/// `delay[n]` is the input two slots back for the all-pass bands (the caller
532+/// passes the delay line from offset `MAX_DELAY - 2`).
533+fn allpass_decorrelate(
534+ out: &mut [Cx; SLOTS],
535+ delay: &[Cx],
536+ ap: &mut [[Cx; SLOTS + MAX_AP_DELAY]; AP_LINKS],
537+ phi: [f64; 2],
538+ q: &[[f64; 2]; AP_LINKS],
539+ tg: &[f64; SLOTS],
540+ g: f64,
541+) {
542+ let ag = [AP_A[0] * g, AP_A[1] * g, AP_A[2] * g];
543+ for n in 0..SLOTS {
544+ let d = delay[n];
545+ let mut in_re = d.re * phi[0] - d.im * phi[1];
546+ let mut in_im = d.re * phi[1] + d.im * phi[0];
547+ for m in 0..AP_LINKS {
548+ let a_re = ag[m] * in_re;
549+ let a_im = ag[m] * in_im;
550+ let link = ap[m][n + 2 - m];
551+ let apd_re = in_re;
552+ let apd_im = in_im;
553+ in_re = link.re * q[m][0] - link.im * q[m][1] - a_re;
554+ in_im = link.re * q[m][1] + link.im * q[m][0] - a_im;
555+ ap[m][n + MAX_AP_DELAY] = Cx {
556+ re: apd_re + ag[m] * in_re,
557+ im: apd_im + ag[m] * in_im,
558+ };
559+ }
560+ out[n] = Cx { re: tg[n] * in_re, im: tg[n] * in_im };
561+ }
562+}
563+
564+/// The per-stream PS reconstruction state (FFmpeg's `PSContext`, minus the
565+/// parsed parameters, which live in [`PsCommon`]).
566+pub struct PsEngine {
567+ /// Hybrid input per low band: 6 history slots, then the frame and lookahead.
568+ in_buf: [[Cx; IN_BUF_LEN]; LOW_BANDS],
569+ /// Decorrelator delay lines per subband (14 history + 32 new slots).
570+ delay: Vec<[Cx; SLOTS + MAX_DELAY]>,
571+ /// All-pass delay lines per band and link (5 history + 32 new slots).
572+ ap_delay: Vec<[[Cx; SLOTS + MAX_AP_DELAY]; AP_LINKS]>,
573+ peak_decay_nrg: [f64; MAX_PAR],
574+ power_smooth: [f64; MAX_PAR],
575+ peak_decay_diff_smooth: [f64; MAX_PAR],
576+ /// Mixing matrices `[mat][ipd][envelope][band]`, mat = H11, H12, H21, H22.
577+ h: [[[[f64; MAX_PAR]; MAX_ENV + 1]; 2]; 4],
578+ opd_hist: [usize; MAX_PAR],
579+ ipd_hist: [usize; MAX_PAR],
580+}
581+
582+impl Default for PsEngine {
583+ fn default() -> PsEngine {
584+ PsEngine::new()
585+ }
586+}
587+
588+impl PsEngine {
589+ /// A fresh engine with all delay lines and mixing matrices cleared.
590+ pub fn new() -> PsEngine {
591+ PsEngine {
592+ in_buf: [[Cx::default(); IN_BUF_LEN]; LOW_BANDS],
593+ delay: vec![[Cx::default(); SLOTS + MAX_DELAY]; MAX_SUB],
594+ ap_delay: vec![[[Cx::default(); SLOTS + MAX_AP_DELAY]; AP_LINKS]; MAX_ALLPASS],
595+ peak_decay_nrg: [0.0; MAX_PAR],
596+ power_smooth: [0.0; MAX_PAR],
597+ peak_decay_diff_smooth: [0.0; MAX_PAR],
598+ h: [[[[0.0; MAX_PAR]; MAX_ENV + 1]; 2]; 4],
599+ opd_hist: [0; MAX_PAR],
600+ ipd_hist: [0; MAX_PAR],
601+ }
602+ }
603+
604+ /// Runs the stereo reconstruction over one SBR frame (`ff_ps_apply`).
605+ ///
606+ /// `input` is the SBR's 38-slot QMF buffer for the mono channel: the 32
607+ /// frame slots plus the 6 lookahead slots the hybrid filter reads ahead
608+ /// into. `top` is the first QMF band above the SBR range. Returns the left
609+ /// and right QMF slots for the frame's 32 slots.
610+ pub fn apply(
611+ &mut self,
612+ ps: &PsCommon,
613+ input: &[[Complex<f32>; QMF_BANDS]; IN_SLOTS],
614+ top: usize,
615+ ) -> (QmfPlane, QmfPlane) {
616+ let is34 = ps.is34bands;
617+ let m = usize::from(is34);
618+ let nr_bands = NR_BANDS[m];
619+ // Clear the delay state above the SBR range (`top += NR_BANDS - 64`).
620+ let top = (top as isize + nr_bands as isize - QMF_BANDS as isize).clamp(0, nr_bands as isize) as usize;
621+ for d in &mut self.delay[top..nr_bands] {
622+ *d = [Cx::default(); SLOTS + MAX_DELAY];
623+ }
624+ let n_allpass = NR_ALLPASS_BANDS[m];
625+ if top < n_allpass {
626+ for a in &mut self.ap_delay[top..n_allpass] {
627+ *a = [[Cx::default(); SLOTS + MAX_AP_DELAY]; AP_LINKS];
628+ }
629+ }
630+
631+ let mut s = [[Cx::default(); SLOTS]; MAX_SUB];
632+ let mut d = [[Cx::default(); SLOTS]; MAX_SUB];
633+ self.hybrid_analysis(input, is34, &mut s);
634+ self.decorrelation(ps, &s, &mut d);
635+ self.stereo_processing(ps, &mut s, &mut d);
636+ let left = hybrid_synthesis(&s, is34);
637+ let right = hybrid_synthesis(&d, is34);
638+ (narrow(&left), narrow(&right))
639+ }
640+
641+ /// Splits the low QMF bands into hybrid subbands (`hybrid_analysis`).
642+ fn hybrid_analysis(
643+ &mut self,
644+ input: &[[Complex<f32>; QMF_BANDS]; IN_SLOTS],
645+ is34: bool,
646+ out: &mut [[Cx; SLOTS]; MAX_SUB],
647+ ) {
648+ let t = tables();
649+ for (band, buf) in self.in_buf.iter_mut().enumerate() {
650+ for (j, slot) in input.iter().enumerate() {
651+ buf[j + HIST] = lift(slot[band]);
652+ }
653+ }
654+ {
655+ let buf = &self.in_buf;
656+ if is34 {
657+ analysis_bank(&buf[0], &t.f34_0_12, &mut out[0..12]);
658+ analysis_bank(&buf[1], &t.f34_1_8, &mut out[12..20]);
659+ analysis_bank(&buf[2], &t.f34_2_4, &mut out[20..24]);
660+ analysis_bank(&buf[3], &t.f34_2_4, &mut out[24..28]);
661+ analysis_bank(&buf[4], &t.f34_2_4, &mut out[28..32]);
662+ interleave(input, 27, 5, out);
663+ } else {
664+ let mut temp = [[Cx::default(); SLOTS]; 8];
665+ analysis_bank(&buf[0], &t.f20_0_8, &mut temp);
666+ for i in 0..SLOTS {
667+ out[0][i] = temp[6][i];
668+ out[1][i] = temp[7][i];
669+ out[2][i] = temp[0][i];
670+ out[3][i] = temp[1][i];
671+ out[4][i] = Cx {
672+ re: temp[2][i].re + temp[5][i].re,
673+ im: temp[2][i].im + temp[5][i].im,
674+ };
675+ out[5][i] = Cx {
676+ re: temp[3][i].re + temp[4][i].re,
677+ im: temp[3][i].im + temp[4][i].im,
678+ };
679+ }
680+ hybrid2(&buf[1], 6, true, out);
681+ hybrid2(&buf[2], 8, false, out);
682+ interleave(input, 7, 3, out);
683+ }
684+ }
685+ // Keep the last 6 slots of this frame as the next frame's history.
686+ for band in 0..LOW_BANDS {
687+ self.in_buf[band].copy_within(SLOTS..SLOTS + HIST, 0);
688+ }
689+ }
690+
691+ /// The all-pass decorrelator and the transient ducker (`decorrelation`).
692+ fn decorrelation(&mut self, ps: &PsCommon, s: &[[Cx; SLOTS]; MAX_SUB], out: &mut [[Cx; SLOTS]; MAX_SUB]) {
693+ let t = tables();
694+ let is34 = ps.is34bands;
695+ let m = usize::from(is34);
696+ let k_to_i: &[u8] = if is34 { &K_TO_I_34 } else { &K_TO_I_20 };
697+
698+ if is34 != ps.is34bands_old {
699+ self.peak_decay_nrg = [0.0; MAX_PAR];
700+ self.power_smooth = [0.0; MAX_PAR];
701+ self.peak_decay_diff_smooth = [0.0; MAX_PAR];
702+ for d in self.delay.iter_mut() {
703+ *d = [Cx::default(); SLOTS + MAX_DELAY];
704+ }
705+ for a in self.ap_delay.iter_mut() {
706+ *a = [[Cx::default(); SLOTS + MAX_AP_DELAY]; AP_LINKS];
707+ }
708+ }
709+
710+ // Band power per parameter band, over the subbands that map to it.
711+ let mut power = [[0.0f64; SLOTS]; MAX_PAR];
712+ for k in 0..NR_BANDS[m] {
713+ let i = usize::from(k_to_i[k]);
714+ for n in 0..SLOTS {
715+ power[i][n] += s[k][n].re * s[k][n].re + s[k][n].im * s[k][n].im;
716+ }
717+ }
718+
719+ // Transient detector: a per-band gain that ducks the decorrelated part.
720+ let mut transient = [[0.0f64; SLOTS]; MAX_PAR];
721+ for i in 0..NR_PAR_BANDS[m] {
722+ for n in 0..SLOTS {
723+ let decayed = PEAK_DECAY_FACTOR * self.peak_decay_nrg[i];
724+ self.peak_decay_nrg[i] = decayed.max(power[i][n]);
725+ self.power_smooth[i] += A_SMOOTH * (power[i][n] - self.power_smooth[i]);
726+ self.peak_decay_diff_smooth[i] +=
727+ A_SMOOTH * (self.peak_decay_nrg[i] - power[i][n] - self.peak_decay_diff_smooth[i]);
728+ let denom = TRANSIENT_IMPACT * self.peak_decay_diff_smooth[i];
729+ transient[i][n] = if denom > self.power_smooth[i] {
730+ self.power_smooth[i] / denom
731+ } else {
732+ 1.0
733+ };
734+ }
735+ }
736+
737+ for k in 0..NR_ALLPASS_BANDS[m] {
738+ let b = usize::from(k_to_i[k]);
739+ let g = (1.0 - DECAY_SLOPE * f64::from(k as i32 - DECAY_CUTOFF[m])).clamp(0.0, 1.0);
740+ shift_delay(&mut self.delay[k], &s[k]);
741+ for link in self.ap_delay[k].iter_mut() {
742+ link.copy_within(SLOTS..SLOTS + MAX_AP_DELAY, 0);
743+ }
744+ allpass_decorrelate(
745+ &mut out[k],
746+ &self.delay[k][MAX_DELAY - 2..],
747+ &mut self.ap_delay[k],
748+ t.phi_fract[m][k],
749+ &t.q_fract[m][k],
750+ &transient[b],
751+ g,
752+ );
753+ }
754+ for k in NR_ALLPASS_BANDS[m]..SHORT_DELAY_BAND[m] {
755+ let b = usize::from(k_to_i[k]);
756+ shift_delay(&mut self.delay[k], &s[k]);
757+ for n in 0..SLOTS {
758+ let dv = self.delay[k][n];
759+ out[k][n] = Cx { re: dv.re * transient[b][n], im: dv.im * transient[b][n] };
760+ }
761+ }
762+ for k in SHORT_DELAY_BAND[m]..NR_BANDS[m] {
763+ let b = usize::from(k_to_i[k]);
764+ shift_delay(&mut self.delay[k], &s[k]);
765+ for n in 0..SLOTS {
766+ let dv = self.delay[k][MAX_DELAY - 1 + n];
767+ out[k][n] = Cx { re: dv.re * transient[b][n], im: dv.im * transient[b][n] };
768+ }
769+ }
770+ }
771+
772+ /// Mixing matrices per envelope, then the mix of `(s, d)` into the stereo
773+ /// pair in place (`stereo_processing`). On return `l` holds the left and
774+ /// `r` the right subband signal.
775+ fn stereo_processing(
776+ &mut self,
777+ ps: &PsCommon,
778+ l: &mut [[Cx; SLOTS]; MAX_SUB],
779+ r: &mut [[Cx; SLOTS]; MAX_SUB],
780+ ) {
781+ let t = tables();
782+ let is34 = ps.is34bands;
783+ let m = usize::from(is34);
784+ let k_to_i: &[u8] = if is34 { &K_TO_I_34 } else { &K_TO_I_20 };
785+ let lut = if ps.icc_mode < 3 { &t.ha } else { &t.hb };
786+
787+ // The previous frame's last envelope becomes this frame's envelope 0.
788+ if ps.num_env_old != 0 {
789+ for mat in 0..4 {
790+ for ipd in 0..2 {
791+ self.h[mat][ipd][0] = self.h[mat][ipd][ps.num_env_old];
792+ }
793+ }
794+ }
795+
796+ let num_env = ps.num_env;
797+ let (iid, icc, ipd, opd) = if is34 {
798+ if !ps.is34bands_old {
799+ for mat in 0..4 {
800+ for ipd_row in 0..2 {
801+ map_val_20_to_34(&mut self.h[mat][ipd_row][0]);
802+ }
803+ }
804+ self.reset_ipdopd_hist();
805+ }
806+ (
807+ remap34(&ps.iid_par, ps.nr_iid_par, num_env, true),
808+ remap34(&ps.icc_par, ps.nr_icc_par, num_env, true),
809+ remap34(&ps.ipd_par, ps.nr_ipdopd_par, num_env, false),
810+ remap34(&ps.opd_par, ps.nr_ipdopd_par, num_env, false),
811+ )
812+ } else {
813+ if ps.is34bands_old {
814+ for mat in 0..4 {
815+ for ipd_row in 0..2 {
816+ map_val_34_to_20(&mut self.h[mat][ipd_row][0]);
817+ }
818+ }
819+ self.reset_ipdopd_hist();
820+ }
821+ (
822+ remap20(&ps.iid_par, ps.nr_iid_par, num_env, true),
823+ remap20(&ps.icc_par, ps.nr_icc_par, num_env, true),
824+ remap20(&ps.ipd_par, ps.nr_ipdopd_par, num_env, false),
825+ remap20(&ps.opd_par, ps.nr_ipdopd_par, num_env, false),
826+ )
827+ };
828+
829+ let quant = i32::from(ps.iid_quant) * 23;
830+ // Mixing matrices for each envelope and parameter band.
831+ for e in 0..num_env {
832+ for b in 0..NR_PAR_BANDS[m] {
833+ let idx = (i32::from(iid[e][b]) + 7 + quant).clamp(0, 45) as usize;
834+ let icc_idx = usize::from(icc[e][b].clamp(0, 7) as u8);
835+ let row = lut[idx][icc_idx];
836+ let mut mix = row;
837+ if ps.enable_ipdopd && b < NR_IPDOPD_BANDS[m] {
838+ let opd_idx = (self.opd_hist[b] * 8 + usize::from(opd[e][b].clamp(0, 7) as u8)).min(511);
839+ let ipd_idx = (self.ipd_hist[b] * 8 + usize::from(ipd[e][b].clamp(0, 7) as u8)).min(511);
840+ let (opd_re, opd_im) = (t.pd_re[opd_idx], t.pd_im[opd_idx]);
841+ let (ipd_re, ipd_im) = (t.pd_re[ipd_idx], t.pd_im[ipd_idx]);
842+ self.opd_hist[b] = opd_idx & 0x3F;
843+ self.ipd_hist[b] = ipd_idx & 0x3F;
844+ let ipd_adj_re = opd_re * ipd_re + opd_im * ipd_im;
845+ let ipd_adj_im = opd_im * ipd_re - opd_re * ipd_im;
846+ let [h11, h12, h21, h22] = mix;
847+ self.h[0][1][e + 1][b] = h11 * opd_im;
848+ self.h[1][1][e + 1][b] = h12 * ipd_adj_im;
849+ self.h[2][1][e + 1][b] = h21 * opd_im;
850+ self.h[3][1][e + 1][b] = h22 * ipd_adj_im;
851+ mix = [h11 * opd_re, h12 * ipd_adj_re, h21 * opd_re, h22 * ipd_adj_re];
852+ }
853+ for (h_mat, v) in self.h.iter_mut().zip(mix) {
854+ h_mat[0][e + 1][b] = v;
855+ }
856+ }
857+
858+ // Interpolate the matrices across this envelope's slots.
859+ let start = ps.border_position[e];
860+ let stop = ps.border_position[e + 1];
861+ let count = (stop - start).max(0) as usize;
862+ let width = 1.0 / if count == 0 { 1.0 } else { count as f64 };
863+ let first = (start + 1).max(0) as usize;
864+ for k in 0..NR_BANDS[m] {
865+ if count == 0 {
866+ break;
867+ }
868+ let b = usize::from(k_to_i[k]);
869+ let mut h0 = [0.0f64; 4];
870+ let mut hs0 = [0.0f64; 4];
871+ let mut h1 = [0.0f64; 4];
872+ let mut hs1 = [0.0f64; 4];
873+ let flip = (is34 && (9..=13).contains(&k)) || (!is34 && k <= 1);
874+ for mat in 0..4 {
875+ h0[mat] = self.h[mat][0][e][b];
876+ hs0[mat] = (self.h[mat][0][e + 1][b] - h0[mat]) * width;
877+ if ps.enable_ipdopd {
878+ let sign = if flip { -1.0 } else { 1.0 };
879+ h1[mat] = sign * self.h[mat][1][e][b];
880+ hs1[mat] = (self.h[mat][1][e + 1][b] - h1[mat]) * width;
881+ }
882+ }
883+ for n in 0..count {
884+ let slot = first + n;
885+ if slot >= SLOTS {
886+ break;
887+ }
888+ for mat in 0..4 {
889+ h0[mat] += hs0[mat];
890+ h1[mat] += hs1[mat];
891+ }
892+ let lv = l[k][slot];
893+ let rv = r[k][slot];
894+ if ps.enable_ipdopd {
895+ l[k][slot] = Cx {
896+ re: h0[0] * lv.re + h0[2] * rv.re - h1[0] * lv.im - h1[2] * rv.im,
897+ im: h0[0] * lv.im + h0[2] * rv.im + h1[0] * lv.re + h1[2] * rv.re,
898+ };
899+ r[k][slot] = Cx {
900+ re: h0[1] * lv.re + h0[3] * rv.re - h1[1] * lv.im - h1[3] * rv.im,
901+ im: h0[1] * lv.im + h0[3] * rv.im + h1[1] * lv.re + h1[3] * rv.re,
902+ };
903+ } else {
904+ l[k][slot] = Cx {
905+ re: h0[0] * lv.re + h0[2] * rv.re,
906+ im: h0[0] * lv.im + h0[2] * rv.im,
907+ };
908+ r[k][slot] = Cx {
909+ re: h0[1] * lv.re + h0[3] * rv.re,
910+ im: h0[1] * lv.im + h0[3] * rv.im,
911+ };
912+ }
913+ }
914+ }
915+ }
916+ }
917+
918+ fn reset_ipdopd_hist(&mut self) {
919+ self.opd_hist = [0; MAX_PAR];
920+ self.ipd_hist = [0; MAX_PAR];
921+ }
922+}
crates/ec-aac/src/ps_huff.rsadded+91 -0
@@ -0,0 +1,91 @@
1+//! Parametric Stereo Huffman code-length tables (ISO/IEC 14496-3 subpart 8).
2+//!
3+//! Generated by `scripts/aac-tables/gen-ps-huff.py` from the `aacps_huff_tabs`
4+//! array of FFmpeg's `libavcodec/aacpsdata.c`: one `(symbol, code length)` pair
5+//! per codeword, in table order. Codes are canonical: within each length they
6+//! are assigned in table order (see `ps_data::build_codes`). Do not edit by hand.
7+
8+/// Added to a decoded symbol to give the parameter value, per table.
9+pub const OFFSETS: [i32; 10] = [-30, -30, -14, -14, -7, -7, 0, 0, 0, 0];
10+/// `IID_DF1`: 61 codewords.
11+pub const T_IID_DF1: [(u8, u8); 61] = [
12+ (28, 4), (32, 4), (29, 3), (31, 3), (27, 5), (33, 5),
13+ (26, 6), (34, 6), (25, 7), (35, 7), (24, 8), (36, 8),
14+ (37, 9), (40, 11), (19, 12), (41, 12), (22, 10), (38, 10),
15+ (9, 17), (51, 17), (11, 17), (49, 17), (13, 16), (47, 16),
16+ (16, 14), (18, 13), (42, 13), (44, 14), (12, 17), (48, 17),
17+ (4, 18), (5, 18), (2, 18), (3, 18), (15, 15), (21, 11),
18+ (39, 11), (45, 15), (8, 18), (52, 18), (6, 18), (7, 18),
19+ (55, 18), (56, 18), (53, 18), (54, 18), (17, 14), (43, 14),
20+ (59, 18), (60, 18), (57, 18), (58, 18), (0, 18), (1, 18),
21+ (10, 18), (50, 18), (14, 16), (46, 16), (20, 12), (23, 10),
22+ (30, 1),
23+];
24+/// `IID_DT1`: 61 codewords.
25+pub const T_IID_DT1: [(u8, u8); 61] = [
26+ (31, 2), (26, 7), (34, 7), (27, 6), (33, 6), (35, 8),
27+ (24, 9), (36, 9), (39, 11), (41, 12), (9, 15), (10, 15),
28+ (48, 15), (49, 15), (17, 13), (23, 10), (37, 10), (43, 13),
29+ (11, 15), (12, 15), (4, 16), (56, 16), (2, 16), (3, 16),
30+ (59, 16), (60, 16), (57, 16), (58, 16), (0, 16), (1, 16),
31+ (5, 16), (55, 16), (6, 16), (54, 16), (13, 15), (15, 14),
32+ (20, 12), (40, 12), (22, 11), (38, 11), (45, 14), (47, 15),
33+ (7, 16), (53, 16), (18, 13), (42, 13), (16, 14), (44, 14),
34+ (8, 16), (52, 16), (14, 15), (46, 15), (50, 16), (51, 16),
35+ (19, 13), (21, 12), (25, 9), (28, 5), (32, 5), (29, 3),
36+ (30, 1),
37+];
38+/// `IID_DF0`: 29 codewords.
39+pub const T_IID_DF0: [(u8, u8); 29] = [
40+ (14, 1), (15, 3), (13, 3), (16, 4), (12, 4), (17, 5),
41+ (11, 5), (10, 6), (18, 6), (19, 6), (9, 7), (20, 8),
42+ (8, 9), (7, 10), (21, 11), (22, 13), (6, 13), (23, 14),
43+ (24, 14), (5, 15), (25, 15), (4, 16), (3, 17), (0, 17),
44+ (1, 17), (2, 17), (26, 17), (27, 18), (28, 18),
45+];
46+/// `IID_DT0`: 29 codewords.
47+pub const T_IID_DT0: [(u8, u8); 29] = [
48+ (14, 1), (13, 2), (15, 3), (12, 4), (16, 5), (11, 6),
49+ (17, 7), (10, 8), (18, 9), (9, 10), (19, 11), (8, 12),
50+ (20, 13), (21, 14), (7, 15), (22, 17), (6, 17), (23, 19),
51+ (0, 19), (1, 19), (2, 19), (3, 20), (4, 20), (5, 20),
52+ (24, 20), (25, 20), (26, 20), (27, 20), (28, 20),
53+];
54+/// `ICC_DF`: 15 codewords.
55+pub const T_ICC_DF: [(u8, u8); 15] = [
56+ (7, 1), (8, 2), (6, 3), (9, 4), (5, 5), (10, 6),
57+ (4, 7), (11, 8), (12, 9), (3, 10), (13, 11), (2, 12),
58+ (14, 13), (1, 14), (0, 14),
59+];
60+/// `ICC_DT`: 15 codewords.
61+pub const T_ICC_DT: [(u8, u8); 15] = [
62+ (7, 1), (8, 2), (6, 3), (9, 4), (5, 5), (10, 6),
63+ (4, 7), (11, 8), (3, 9), (12, 10), (2, 11), (13, 12),
64+ (1, 13), (0, 14), (14, 14),
65+];
66+/// `IPD_DF`: 8 codewords.
67+pub const T_IPD_DF: [(u8, u8); 8] = [
68+ (1, 3), (4, 4), (5, 4), (3, 4), (6, 4), (2, 4),
69+ (7, 4), (0, 1),
70+];
71+/// `IPD_DT`: 8 codewords.
72+pub const T_IPD_DT: [(u8, u8); 8] = [
73+ (5, 4), (4, 5), (3, 5), (2, 4), (6, 4), (1, 3),
74+ (7, 3), (0, 1),
75+];
76+/// `OPD_DF`: 8 codewords.
77+pub const T_OPD_DF: [(u8, u8); 8] = [
78+ (7, 3), (1, 3), (3, 4), (6, 4), (2, 4), (5, 5),
79+ (4, 5), (0, 1),
80+];
81+/// `OPD_DT`: 8 codewords.
82+pub const T_OPD_DT: [(u8, u8); 8] = [
83+ (5, 4), (2, 4), (6, 4), (4, 5), (3, 5), (1, 3),
84+ (7, 3), (0, 1),
85+];
86+/// The ten tables indexed by the `T_*` order above.
87+pub const TABLES: [&[(u8, u8)]; 10] = [&T_IID_DF1, &T_IID_DT1, &T_IID_DF0, &T_IID_DT0, &T_ICC_DF, &T_ICC_DT, &T_IPD_DF, &T_IPD_DT, &T_OPD_DF, &T_OPD_DT];
88+/// Table 8.48: sub-subband `k` (0..71) to the 20-band parameter index.
89+pub const K_TO_I_20: [u8; 71] = [1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19];
90+/// Table 8.49: sub-subband `k` (0..91) to the 34-band parameter index.
91+pub const K_TO_I_34: [u8; 91] = [0, 1, 2, 3, 4, 5, 6, 6, 7, 2, 1, 0, 10, 10, 4, 5, 6, 7, 8, 9, 10, 11, 12, 9, 14, 11, 12, 13, 14, 15, 16, 13, 16, 17, 18, 19, 20, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33];
crates/ec-aac/src/sbr_bands.rsdeleted+0 -6343

Diff too large; view file

@@ -1,6343 +0,0 @@
1-//! SBR frequency band tables (ISO/IEC 14496-3 §4.6.18.3.2.1): `f_master`,
2-//! `f_high`, `f_low`, `f_noise` from a header's `bs_start_freq`/`bs_stop_freq`/
3-//! `bs_freq_scale`/`bs_alter_scale`/`bs_xover_band`/`bs_noise_bands`.
4-//!
5-//! This is a direct port of `scripts/aac-tables/sbrtables.py`'s `freq_tables`/
6-//! `f_master`/`make_bands`, which was checked against a reference decoder over
7-//! 6387 header configurations (recorded in the project ledger). The port itself
8-//! is re-checked here against 500 configurations run through that same Python
9-//! function, embedded as literal test vectors so the check needs no Python at
10-//! test time -- only the numbers it once printed.
11-#![allow(dead_code)]
12-
13-/// `k0` offset by SBR sample rate and `bs_start_freq`, ten rates the reference
14-/// decoder was probed at (`--stage k0`).
15-fn k0_offsets(rate: u32) -> Option<[i32; 16]> {
16- Some(match rate {
17- 16000 => [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7],
18- 22050 => [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13],
19- 24000 => [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
20- 32000 => [-6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
21- 44100 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
22- 48000 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
23- 64000 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
24- 88200 => [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
25- 96000 => [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
26- _ => return None,
27- })
28-}
29-
30-/// The QMF band a 3, 4 or 5 kHz border falls in: `(start_min, stop_min)`.
31-fn start_stop_min(rate: u32) -> (i64, i64) {
32- let temp: i64 = if rate < 32000 {
33- 3000
34- } else if rate < 64000 {
35- 4000
36- } else {
37- 5000
38- };
39- let rate = rate as i64;
40- (
41- ((temp << 7) + (rate >> 1)) / rate,
42- ((temp << 8) + (rate >> 1)) / rate,
43- )
44-}
45-
46-/// The widest `k2 - k0` reconstructed at this rate.
47-fn span_limit(rate: u32) -> i64 {
48- if rate < 32000 {
49- 48
50- } else if rate < 64000 {
51- 35
52- } else {
53- 32
54- }
55-}
56-
57-/// `num` band widths geometrically spaced from `start` to `stop`.
58-fn make_bands(start: i64, stop: i64, num: i64) -> Vec<i64> {
59- let base = (stop as f64 / start as f64).powf(1.0 / num as f64);
60- let mut prod = start as f64;
61- let mut previous = start;
62- let mut out = Vec::new();
63- for _ in 0..num - 1 {
64- prod *= base;
65- let present = (prod + 0.5).floor() as i64;
66- out.push(present - previous);
67- previous = present;
68- }
69- out.push(stop - previous);
70- out
71-}
72-
73-/// The master frequency band table.
74-fn f_master(
75- rate: u32,
76- start_freq: usize,
77- stop_freq: usize,
78- freq_scale: i32,
79- alter_scale: i32,
80-) -> Option<Vec<i64>> {
81- let offsets = k0_offsets(rate)?;
82- let (start_min, stop_min) = start_stop_min(rate);
83- let k0 = start_min + offsets[start_freq] as i64;
84- let k2 = if stop_freq < 14 {
85- let mut widths = make_bands(stop_min, 64, 13);
86- widths.sort();
87- stop_min + widths[..stop_freq].iter().sum::<i64>()
88- } else if stop_freq == 14 {
89- 2 * k0
90- } else {
91- 3 * k0
92- };
93- let k2 = k2.min(64);
94- if k2 <= k0 || k2 - k0 > span_limit(rate) {
95- return None;
96- }
97-
98- if freq_scale == 0 {
99- let dk: i64 = if alter_scale != 0 { 2 } else { 1 };
100- let num_bands = 2 * ((k2 - k0 + 2 * (dk - 1)) / (2 * dk));
101- if num_bands <= 0 {
102- return None;
103- }
104- let mut vk = vec![dk; num_bands as usize];
105- let mut k2diff = k2 - k0 - num_bands * dk;
106- let (mut at, incr): (i64, i64) = if k2diff < 0 {
107- (0, 1)
108- } else {
109- (num_bands - 1, -1)
110- };
111- while k2diff != 0 && at >= 0 && at < num_bands {
112- vk[at as usize] -= incr;
113- at += incr;
114- k2diff += incr;
115- }
116- let mut table = vec![k0];
117- for d in vk {
118- if d <= 0 {
119- return None;
120- }
121- table.push(table[table.len() - 1] + d);
122- }
123- return Some(table);
124- }
125-
126- let half_bands = 7 - freq_scale;
127- let two_regions = 49 * k2 > 110 * k0;
128- let k1 = if two_regions { 2 * k0 } else { k2 };
129- let num_bands_0 = 2 * (half_bands as f64 * (k1 as f64 / k0 as f64).log2() + 0.5).floor() as i64;
130- if num_bands_0 <= 0 {
131- return None;
132- }
133- let mut vk0 = make_bands(k0, k1, num_bands_0);
134- vk0.sort();
135- let vdk0_max = vk0[vk0.len() - 1];
136- let mut table = vec![k0];
137- for &d in &vk0 {
138- if d <= 0 {
139- return None;
140- }
141- table.push(table[table.len() - 1] + d);
142- }
143- if !two_regions {
144- return Some(table);
145- }
146- let invwarp = if alter_scale != 0 { 1.0 / 1.3 } else { 1.0 };
147- let num_bands_1 =
148- 2 * (half_bands as f64 * invwarp * (k2 as f64 / k1 as f64).log2() + 0.5).floor() as i64;
149- if num_bands_1 <= 0 {
150- return None;
151- }
152- let mut vk1 = make_bands(k1, k2, num_bands_1);
153- vk1.sort();
154- if vdk0_max > vk1[0] {
155- let change = (vdk0_max - vk1[0]).min((vk1[vk1.len() - 1] - vk1[0]) >> 1);
156- let last = vk1.len() - 1;
157- vk1[0] += change;
158- vk1[last] -= change;
159- vk1.sort();
160- }
161- for &d in &vk1 {
162- if d <= 0 {
163- return None;
164- }
165- table.push(table[table.len() - 1] + d);
166- }
167- Some(table)
168-}
169-
170-/// The derived band tables for one SBR header, or `None` if the reference
171-/// decoder would have refused this combination.
172-#[derive(Debug, Clone, PartialEq, Eq)]
173-pub struct BandTables {
174- pub n_master: usize,
175- pub n_high: usize,
176- pub n_low: usize,
177- pub n_q: usize,
178- pub f_high: Vec<i64>,
179- pub f_low: Vec<i64>,
180- pub f_noise: Vec<i64>,
181- pub kx: i64,
182- pub k2: i64,
183- /// Master table borders (`k0 = f_master[0]`), needed by the patch builder.
184- pub f_master: Vec<i64>,
185- /// SBR (output) sample rate, the patch builder's `goalSb` input.
186- pub rate: u32,
187-}
188-
189-/// `rate` is the SBR rate: twice the AAC-LC core's.
190-pub fn freq_tables(
191- rate: u32,
192- start_freq: usize,
193- stop_freq: usize,
194- freq_scale: i32,
195- alter_scale: i32,
196- xover_band: usize,
197- noise_bands: i32,
198-) -> Option<BandTables> {
199- let master = f_master(rate, start_freq, stop_freq, freq_scale, alter_scale)?;
200- let n_master = master.len() - 1;
201- if xover_band > n_master {
202- return None;
203- }
204- let n_high = n_master - xover_band;
205- if n_high < 1 {
206- return None;
207- }
208- let n_low = (n_high + 1) >> 1;
209- let f_high = master[xover_band..].to_vec();
210- let mut f_low = vec![f_high[0]];
211- if n_high & 1 != 0 {
212- for k in 1..=n_low {
213- f_low.push(f_high[2 * k - 1]);
214- }
215- } else {
216- for k in 1..=n_low {
217- f_low.push(f_high[2 * k]);
218- }
219- }
220- let kx = f_high[0];
221- let k2 = master[master.len() - 1];
222- let n_q = (1i64.max((noise_bands as f64 * (k2 as f64 / kx as f64).log2() + 0.5).floor() as i64))
223- as usize;
224- if n_q > 5 {
225- return None;
226- }
227- let mut f_noise = vec![f_low[0]];
228- let mut temp = 0i64;
229- for k in 1..=n_q {
230- temp += (n_low as i64 - temp) / (n_q as i64 + 1 - k as i64);
231- f_noise.push(f_low[temp as usize]);
232- }
233- Some(BandTables {
234- n_master,
235- n_high,
236- n_low,
237- n_q,
238- f_high,
239- f_low,
240- f_noise,
241- kx,
242- k2,
243- f_master: master.clone(),
244- rate,
245- })
246-}
247-
248-#[cfg(test)]
249-mod tests {
250- use super::*;
251-
252- /// `(sbr_rate, start_freq, stop_freq, freq_scale, alter_scale, noise_bands,
253- /// xover_band, expected)`, `expected` being `(n_master, n_high, n_low, n_q,
254- /// f_high, f_low, f_noise)`. 500 configurations sampled from the same
255- /// `freq_tables()` Python function the project ledger records as checked
256- /// against a reference decoder over 6387 configurations; regenerate with
257- /// `scripts/aac-tables/sbrtables.py`'s `freq_tables` if that function ever
258- /// changes.
259- #[allow(clippy::type_complexity)]
260- static VECTORS: &[(
261- u32,
262- usize,
263- usize,
264- i32,
265- i32,
266- i32,
267- usize,
268- Option<(usize, usize, usize, usize, &[i64], &[i64], &[i64])>,
269- )] = &[
270- (
271- 24000,
272- 13,
273- 2,
274- 1,
275- 0,
276- 2,
277- 0,
278- Some((4, 4, 2, 1, &[27, 29, 31, 33, 36], &[27, 31, 36], &[27, 36])),
279- ),
280- (
281- 24000,
282- 11,
283- 1,
284- 1,
285- 1,
286- 2,
287- 2,
288- Some((6, 4, 2, 1, &[26, 28, 30, 32, 34], &[26, 30, 34], &[26, 34])),
289- ),
290- (
291- 32000,
292- 13,
293- 5,
294- 2,
295- 0,
296- 1,
297- 5,
298- Some((6, 1, 1, 1, &[39, 42], &[39, 42], &[39, 42])),
299- ),
300- (
301- 32000,
302- 2,
303- 2,
304- 2,
305- 0,
306- 2,
307- 6,
308- Some((
309- 14,
310- 8,
311- 4,
312- 2,
313- &[20, 22, 24, 26, 28, 30, 32, 34, 36],
314- &[20, 24, 28, 32, 36],
315- &[20, 28, 36],
316- )),
317- ),
318- (
319- 22050,
320- 13,
321- 2,
322- 2,
323- 1,
324- 1,
325- 5,
326- Some((6, 1, 1, 1, &[35, 38], &[35, 38], &[35, 38])),
327- ),
328- (16000, 14, 0, 2, 1, 2, 6, None),
329- (
330- 64000,
331- 9,
332- 9,
333- 3,
334- 1,
335- 1,
336- 1,
337- Some((
338- 12,
339- 11,
340- 6,
341- 1,
342- &[17, 19, 21, 23, 25, 27, 29, 32, 35, 38, 41, 45],
343- &[17, 19, 23, 27, 32, 38, 45],
344- &[17, 45],
345- )),
346- ),
347- (44100, 15, 1, 1, 0, 0, 5, None),
348- (
349- 16000,
350- 8,
351- 12,
352- 2,
353- 1,
354- 1,
355- 6,
356- Some((
357- 12,
358- 6,
359- 3,
360- 1,
361- &[36, 39, 42, 45, 48, 55, 62],
362- &[36, 42, 48, 62],
363- &[36, 62],
364- )),
365- ),
366- (
367- 44100,
368- 3,
369- 3,
370- 3,
371- 1,
372- 0,
373- 4,
374- Some((
375- 10,
376- 6,
377- 3,
378- 1,
379- &[16, 18, 20, 22, 24, 26, 29],
380- &[16, 20, 24, 29],
381- &[16, 29],
382- )),
383- ),
384- (
385- 24000,
386- 7,
387- 3,
388- 3,
389- 0,
390- 1,
391- 6,
392- Some((8, 2, 1, 1, &[32, 35, 38], &[32, 38], &[32, 38])),
393- ),
394- (
395- 16000,
396- 10,
397- 11,
398- 1,
399- 0,
400- 3,
401- 4,
402- Some((
403- 14,
404- 10,
405- 5,
406- 3,
407- &[33, 35, 37, 39, 41, 43, 46, 49, 52, 56, 60],
408- &[33, 37, 41, 46, 52, 60],
409- &[33, 37, 46, 60],
410- )),
411- ),
412- (
413- 96000,
414- 10,
415- 10,
416- 0,
417- 1,
418- 2,
419- 7,
420- Some((
421- 14,
422- 7,
423- 4,
424- 1,
425- &[30, 32, 34, 36, 38, 40, 42, 44],
426- &[30, 32, 36, 40, 44],
427- &[30, 44],
428- )),
429- ),
430- (48000, 2, 10, 3, 1, 2, 3, None),
431- (
432- 16000,
433- 0,
434- 10,
435- 0,
436- 1,
437- 1,
438- 4,
439- Some((
440- 22,
441- 18,
442- 9,
443- 1,
444- &[
445- 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58,
446- ],
447- &[22, 26, 30, 34, 38, 42, 46, 50, 54, 58],
448- &[22, 58],
449- )),
450- ),
451- (64000, 11, 0, 1, 1, 2, 3, None),
452- (
453- 48000,
454- 15,
455- 14,
456- 1,
457- 1,
458- 3,
459- 1,
460- Some((
461- 12,
462- 11,
463- 6,
464- 3,
465- &[33, 35, 37, 39, 41, 43, 46, 49, 52, 55, 58, 62],
466- &[33, 35, 39, 43, 49, 55, 62],
467- &[33, 39, 49, 62],
468- )),
469- ),
470- (64000, 6, 12, 2, 0, 0, 5, None),
471- (
472- 48000,
473- 1,
474- 4,
475- 0,
476- 1,
477- 0,
478- 7,
479- Some((10, 3, 2, 1, &[23, 25, 27, 29], &[23, 25, 29], &[23, 29])),
480- ),
481- (
482- 24000,
483- 9,
484- 14,
485- 3,
486- 1,
487- 1,
488- 0,
489- Some((
490- 8,
491- 8,
492- 4,
493- 1,
494- &[21, 23, 25, 27, 29, 32, 35, 38, 42],
495- &[21, 25, 29, 35, 42],
496- &[21, 42],
497- )),
498- ),
499- (
500- 24000,
501- 4,
502- 6,
503- 3,
504- 1,
505- 0,
506- 0,
507- Some((
508- 10,
509- 10,
510- 5,
511- 1,
512- &[16, 17, 19, 21, 23, 25, 27, 29, 32, 38, 44],
513- &[16, 19, 23, 27, 32, 44],
514- &[16, 44],
515- )),
516- ),
517- (96000, 15, 8, 3, 1, 0, 4, None),
518- (
519- 64000,
520- 1,
521- 14,
522- 0,
523- 0,
524- 1,
525- 2,
526- Some((
527- 8,
528- 6,
529- 3,
530- 1,
531- &[10, 11, 12, 13, 14, 15, 16],
532- &[10, 12, 14, 16],
533- &[10, 16],
534- )),
535- ),
536- (44100, 4, 10, 0, 0, 0, 2, None),
537- (88200, 0, 9, 3, 0, 2, 5, None),
538- (
539- 32000,
540- 3,
541- 15,
542- 2,
543- 0,
544- 2,
545- 2,
546- Some((
547- 16,
548- 14,
549- 7,
550- 3,
551- &[17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45],
552- &[17, 19, 22, 26, 30, 34, 39, 45],
553- &[17, 22, 30, 45],
554- )),
555- ),
556- (44100, 15, 3, 3, 0, 1, 3, None),
557- (96000, 1, 5, 1, 0, 1, 6, None),
558- (96000, 6, 8, 1, 1, 3, 2, None),
559- (
560- 48000,
561- 14,
562- 9,
563- 1,
564- 1,
565- 3,
566- 3,
567- Some((
568- 8,
569- 5,
570- 3,
571- 1,
572- &[33, 35, 37, 39, 42, 45],
573- &[33, 35, 39, 45],
574- &[33, 45],
575- )),
576- ),
577- (
578- 64000,
579- 2,
580- 8,
581- 3,
582- 0,
583- 2,
584- 5,
585- Some((
586- 18,
587- 13,
588- 7,
589- 3,
590- &[14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41],
591- &[14, 15, 18, 22, 26, 30, 35, 41],
592- &[14, 18, 26, 41],
593- )),
594- ),
595- (
596- 44100,
597- 4,
598- 8,
599- 3,
600- 1,
601- 1,
602- 7,
603- Some((
604- 12,
605- 5,
606- 3,
607- 1,
608- &[24, 26, 29, 33, 38, 43],
609- &[24, 26, 33, 43],
610- &[24, 43],
611- )),
612- ),
613- (96000, 13, 6, 2, 1, 1, 7, None),
614- (32000, 1, 2, 1, 0, 1, 5, None),
615- (
616- 96000,
617- 4,
618- 2,
619- 0,
620- 0,
621- 3,
622- 3,
623- Some((
624- 8,
625- 5,
626- 3,
627- 2,
628- &[12, 13, 14, 15, 16, 17],
629- &[12, 13, 15, 17],
630- &[12, 13, 17],
631- )),
632- ),
633- (
634- 48000,
635- 12,
636- 8,
637- 2,
638- 1,
639- 1,
640- 5,
641- Some((8, 3, 2, 1, &[32, 35, 38, 41], &[32, 35, 41], &[32, 41])),
642- ),
643- (
644- 22050,
645- 14,
646- 9,
647- 1,
648- 1,
649- 3,
650- 5,
651- Some((
652- 10,
653- 5,
654- 3,
655- 1,
656- &[38, 40, 43, 46, 49, 52],
657- &[38, 40, 46, 52],
658- &[38, 52],
659- )),
660- ),
661- (32000, 0, 15, 2, 0, 2, 7, None),
662- (
663- 88200,
664- 11,
665- 5,
666- 1,
667- 1,
668- 1,
669- 2,
670- Some((6, 4, 2, 1, &[20, 21, 22, 24, 26], &[20, 22, 26], &[20, 26])),
671- ),
672- (
673- 22050,
674- 4,
675- 15,
676- 0,
677- 1,
678- 2,
679- 7,
680- Some((
681- 16,
682- 9,
683- 5,
684- 1,
685- &[30, 32, 34, 36, 38, 40, 42, 44, 46, 48],
686- &[30, 32, 36, 40, 44, 48],
687- &[30, 48],
688- )),
689- ),
690- (
691- 44100,
692- 13,
693- 12,
694- 2,
695- 0,
696- 3,
697- 3,
698- Some((
699- 12,
700- 9,
701- 5,
702- 3,
703- &[31, 33, 35, 38, 41, 44, 47, 50, 54, 59],
704- &[31, 33, 38, 44, 50, 59],
705- &[31, 33, 44, 59],
706- )),
707- ),
708- (64000, 2, 3, 1, 1, 1, 6, None),
709- (
710- 32000,
711- 6,
712- 1,
713- 3,
714- 1,
715- 3,
716- 6,
717- Some((8, 2, 1, 1, &[29, 31, 34], &[29, 34], &[29, 34])),
718- ),
719- (
720- 88200,
721- 13,
722- 11,
723- 1,
724- 0,
725- 1,
726- 7,
727- Some((
728- 14,
729- 7,
730- 4,
731- 1,
732- &[34, 36, 38, 40, 42, 45, 48, 51],
733- &[34, 36, 40, 45, 51],
734- &[34, 51],
735- )),
736- ),
737- (44100, 4, 10, 0, 0, 2, 5, None),
738- (
739- 32000,
740- 13,
741- 5,
742- 1,
743- 1,
744- 3,
745- 5,
746- Some((8, 3, 2, 1, &[36, 38, 40, 42], &[36, 38, 42], &[36, 42])),
747- ),
748- (
749- 24000,
750- 5,
751- 14,
752- 0,
753- 0,
754- 0,
755- 7,
756- Some((
757- 16,
758- 9,
759- 5,
760- 1,
761- &[24, 25, 26, 27, 28, 29, 30, 31, 32, 34],
762- &[24, 25, 27, 29, 31, 34],
763- &[24, 34],
764- )),
765- ),
766- (22050, 14, 3, 2, 0, 3, 6, None),
767- (
768- 96000,
769- 6,
770- 7,
771- 3,
772- 0,
773- 1,
774- 6,
775- Some((
776- 12,
777- 6,
778- 3,
779- 1,
780- &[18, 20, 22, 24, 26, 28, 31],
781- &[18, 22, 26, 31],
782- &[18, 31],
783- )),
784- ),
785- (
786- 22050,
787- 12,
788- 3,
789- 1,
790- 0,
791- 1,
792- 7,
793- Some((8, 1, 1, 1, &[37, 40], &[37, 40], &[37, 40])),
794- ),
795- (
796- 32000,
797- 2,
798- 7,
799- 0,
800- 0,
801- 0,
802- 5,
803- Some((
804- 32,
805- 27,
806- 14,
807- 1,
808- &[
809- 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
810- 39, 40, 41, 42, 43, 44, 45, 46,
811- ],
812- &[19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
813- &[19, 46],
814- )),
815- ),
816- (96000, 15, 3, 2, 1, 1, 0, None),
817- (
818- 96000,
819- 4,
820- 8,
821- 3,
822- 1,
823- 2,
824- 1,
825- Some((
826- 14,
827- 13,
828- 7,
829- 4,
830- &[10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 25, 28, 31, 35],
831- &[10, 11, 13, 15, 18, 22, 28, 35],
832- &[10, 11, 15, 22, 35],
833- )),
834- ),
835- (
836- 96000,
837- 4,
838- 9,
839- 3,
840- 0,
841- 0,
842- 1,
843- Some((
844- 16,
845- 15,
846- 8,
847- 1,
848- &[
849- 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 29, 32, 35, 39,
850- ],
851- &[10, 11, 13, 15, 18, 22, 26, 32, 39],
852- &[10, 39],
853- )),
854- ),
855- (
856- 22050,
857- 15,
858- 13,
859- 0,
860- 0,
861- 2,
862- 0,
863- Some((
864- 34,
865- 34,
866- 17,
867- 2,
868- &[
869- 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
870- 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
871- ],
872- &[
873- 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
874- ],
875- &[30, 46, 64],
876- )),
877- ),
878- (96000, 13, 0, 0, 0, 0, 1, None),
879- (
880- 64000,
881- 7,
882- 3,
883- 2,
884- 0,
885- 1,
886- 7,
887- Some((8, 1, 1, 1, &[24, 26], &[24, 26], &[24, 26])),
888- ),
889- (
890- 64000,
891- 0,
892- 7,
893- 0,
894- 1,
895- 0,
896- 0,
897- Some((
898- 16,
899- 16,
900- 8,
901- 1,
902- &[
903- 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37,
904- ],
905- &[6, 9, 13, 17, 21, 25, 29, 33, 37],
906- &[6, 37],
907- )),
908- ),
909- (64000, 1, 7, 2, 1, 0, 2, None),
910- (
911- 24000,
912- 6,
913- 8,
914- 1,
915- 1,
916- 1,
917- 5,
918- Some((
919- 16,
920- 11,
921- 6,
922- 1,
923- &[23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 49],
924- &[23, 24, 28, 32, 36, 42, 49],
925- &[23, 49],
926- )),
927- ),
928- (
929- 16000,
930- 15,
931- 1,
932- 2,
933- 0,
934- 2,
935- 2,
936- Some((6, 4, 2, 1, &[36, 39, 42, 45, 49], &[36, 42, 49], &[36, 49])),
937- ),
938- (
939- 22050,
940- 7,
941- 9,
942- 1,
943- 0,
944- 1,
945- 0,
946- Some((
947- 18,
948- 18,
949- 9,
950- 1,
951- &[
952- 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49, 52,
953- ],
954- &[19, 21, 23, 26, 30, 34, 38, 42, 46, 52],
955- &[19, 52],
956- )),
957- ),
958- (
959- 32000,
960- 7,
961- 5,
962- 3,
963- 1,
964- 3,
965- 4,
966- Some((
967- 10,
968- 6,
969- 3,
970- 2,
971- &[26, 28, 30, 33, 36, 39, 42],
972- &[26, 30, 36, 42],
973- &[26, 30, 42],
974- )),
975- ),
976- (96000, 15, 11, 2, 0, 1, 6, None),
977- (48000, 10, 11, 0, 1, 0, 0, None),
978- (
979- 32000,
980- 6,
981- 1,
982- 2,
983- 1,
984- 2,
985- 5,
986- Some((
987- 10,
988- 5,
989- 3,
990- 1,
991- &[24, 26, 28, 30, 32, 34],
992- &[24, 26, 30, 34],
993- &[24, 34],
994- )),
995- ),
996- (88200, 6, 3, 1, 0, 1, 6, None),
997- (
998- 88200,
999- 9,
1000- 7,
1001- 0,
1002- 1,
1003- 0,
1004- 6,
1005- Some((10, 4, 2, 1, &[25, 27, 29, 31, 33], &[25, 29, 33], &[25, 33])),
1006- ),
1007- (96000, 14, 2, 2, 0, 0, 1, None),
1008- (32000, 6, 11, 2, 1, 1, 3, None),
1009- (
1010- 16000,
1011- 2,
1012- 0,
1013- 2,
1014- 1,
1015- 3,
1016- 3,
1017- Some((
1018- 14,
1019- 11,
1020- 6,
1021- 4,
1022- &[21, 23, 25, 27, 29, 31, 33, 36, 39, 42, 45, 48],
1023- &[21, 23, 27, 31, 36, 42, 48],
1024- &[21, 23, 27, 36, 48],
1025- )),
1026- ),
1027- (
1028- 44100,
1029- 10,
1030- 5,
1031- 0,
1032- 1,
1033- 0,
1034- 2,
1035- Some((
1036- 8,
1037- 6,
1038- 3,
1039- 1,
1040- &[22, 24, 26, 28, 30, 32, 34],
1041- &[22, 26, 30, 34],
1042- &[22, 34],
1043- )),
1044- ),
1045- (88200, 14, 5, 1, 1, 2, 6, None),
1046- (64000, 8, 11, 2, 1, 0, 4, None),
1047- (
1048- 32000,
1049- 15,
1050- 8,
1051- 2,
1052- 0,
1053- 0,
1054- 3,
1055- Some((6, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
1056- ),
1057- (
1058- 32000,
1059- 11,
1060- 0,
1061- 2,
1062- 0,
1063- 0,
1064- 2,
1065- Some((4, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
1066- ),
1067- (88200, 7, 7, 1, 1, 1, 1, None),
1068- (
1069- 48000,
1070- 9,
1071- 0,
1072- 0,
1073- 0,
1074- 0,
1075- 0,
1076- Some((4, 4, 2, 1, &[17, 18, 19, 20, 21], &[17, 19, 21], &[17, 21])),
1077- ),
1078- (48000, 12, 13, 0, 0, 0, 5, None),
1079- (
1080- 96000,
1081- 15,
1082- 12,
1083- 1,
1084- 0,
1085- 0,
1086- 7,
1087- Some((10, 3, 2, 1, &[47, 50, 53, 57], &[47, 50, 57], &[47, 57])),
1088- ),
1089- (96000, 14, 0, 3, 1, 2, 0, None),
1090- (
1091- 64000,
1092- 6,
1093- 14,
1094- 3,
1095- 1,
1096- 0,
1097- 1,
1098- Some((
1099- 8,
1100- 7,
1101- 4,
1102- 1,
1103- &[14, 15, 16, 18, 20, 22, 24, 26],
1104- &[14, 15, 18, 22, 26],
1105- &[14, 26],
1106- )),
1107- ),
1108- (64000, 1, 2, 3, 0, 3, 7, None),
1109- (
1110- 48000,
1111- 8,
1112- 8,
1113- 2,
1114- 0,
1115- 1,
1116- 7,
1117- Some((
1118- 14,
1119- 7,
1120- 4,
1121- 1,
1122- &[26, 28, 30, 32, 34, 36, 38, 41],
1123- &[26, 28, 32, 36, 41],
1124- &[26, 41],
1125- )),
1126- ),
1127- (48000, 7, 1, 3, 0, 1, 6, None),
1128- (
1129- 32000,
1130- 2,
1131- 15,
1132- 0,
1133- 1,
1134- 0,
1135- 0,
1136- Some((
1137- 14,
1138- 14,
1139- 7,
1140- 1,
1141- &[14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
1142- &[14, 18, 22, 26, 30, 34, 38, 42],
1143- &[14, 42],
1144- )),
1145- ),
1146- (64000, 4, 5, 1, 0, 1, 0, None),
1147- (
1148- 32000,
1149- 2,
1150- 5,
1151- 1,
1152- 0,
1153- 1,
1154- 1,
1155- Some((
1156- 20,
1157- 19,
1158- 10,
1159- 1,
1160- &[
1161- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 29, 30, 32, 34, 36, 38, 40, 42,
1162- ],
1163- &[15, 16, 18, 20, 22, 24, 28, 30, 34, 38, 42],
1164- &[15, 42],
1165- )),
1166- ),
1167- (64000, 11, 4, 2, 0, 3, 6, None),
1168- (
1169- 16000,
1170- 4,
1171- 13,
1172- 2,
1173- 0,
1174- 3,
1175- 5,
1176- Some((
1177- 16,
1178- 11,
1179- 6,
1180- 4,
1181- &[28, 30, 32, 34, 37, 40, 43, 47, 51, 55, 59, 64],
1182- &[28, 30, 34, 40, 47, 55, 64],
1183- &[28, 30, 34, 47, 64],
1184- )),
1185- ),
1186- (
1187- 64000,
1188- 15,
1189- 14,
1190- 0,
1191- 0,
1192- 1,
1193- 3,
1194- Some((
1195- 30,
1196- 27,
1197- 14,
1198- 1,
1199- &[
1200- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
1201- 53, 54, 55, 56, 57, 58, 59, 60,
1202- ],
1203- &[33, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60],
1204- &[33, 60],
1205- )),
1206- ),
1207- (
1208- 22050,
1209- 8,
1210- 15,
1211- 0,
1212- 0,
1213- 0,
1214- 3,
1215- Some((
1216- 40,
1217- 37,
1218- 19,
1219- 1,
1220- &[
1221- 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
1222- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
1223- ],
1224- &[
1225- 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
1226- ],
1227- &[23, 60],
1228- )),
1229- ),
1230- (44100, 1, 4, 1, 0, 3, 1, None),
1231- (
1232- 16000,
1233- 2,
1234- 2,
1235- 2,
1236- 0,
1237- 2,
1238- 4,
1239- Some((
1240- 14,
1241- 10,
1242- 5,
1243- 2,
1244- &[23, 25, 27, 29, 31, 33, 36, 39, 42, 46, 50],
1245- &[23, 27, 31, 36, 42, 50],
1246- &[23, 31, 50],
1247- )),
1248- ),
1249- (
1250- 44100,
1251- 10,
1252- 4,
1253- 3,
1254- 0,
1255- 3,
1256- 1,
1257- Some((
1258- 6,
1259- 5,
1260- 3,
1261- 2,
1262- &[20, 22, 24, 26, 28, 31],
1263- &[20, 22, 26, 31],
1264- &[20, 22, 31],
1265- )),
1266- ),
1267- (
1268- 22050,
1269- 8,
1270- 12,
1271- 0,
1272- 0,
1273- 3,
1274- 7,
1275- Some((
1276- 40,
1277- 33,
1278- 17,
1279- 4,
1280- &[
1281- 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
1282- 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61,
1283- ],
1284- &[
1285- 27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 61,
1286- ],
1287- &[27, 34, 42, 50, 61],
1288- )),
1289- ),
1290- (
1291- 24000,
1292- 9,
1293- 5,
1294- 1,
1295- 0,
1296- 2,
1297- 2,
1298- Some((
1299- 12,
1300- 10,
1301- 5,
1302- 2,
1303- &[23, 24, 25, 27, 29, 31, 33, 35, 37, 39, 42],
1304- &[23, 25, 29, 33, 37, 42],
1305- &[23, 29, 42],
1306- )),
1307- ),
1308- (
1309- 24000,
1310- 8,
1311- 10,
1312- 3,
1313- 0,
1314- 0,
1315- 1,
1316- Some((
1317- 12,
1318- 11,
1319- 6,
1320- 1,
1321- &[22, 24, 26, 28, 31, 34, 37, 40, 43, 47, 51, 55],
1322- &[22, 24, 28, 34, 40, 47, 55],
1323- &[22, 55],
1324- )),
1325- ),
1326- (
1327- 48000,
1328- 13,
1329- 7,
1330- 0,
1331- 0,
1332- 1,
1333- 5,
1334- Some((
1335- 14,
1336- 9,
1337- 5,
1338- 1,
1339- &[29, 30, 31, 32, 33, 34, 35, 36, 37, 38],
1340- &[29, 30, 32, 34, 36, 38],
1341- &[29, 38],
1342- )),
1343- ),
1344- (64000, 13, 5, 2, 1, 3, 7, None),
1345- (24000, 0, 13, 2, 0, 2, 7, None),
1346- (
1347- 64000,
1348- 2,
1349- 14,
1350- 3,
1351- 0,
1352- 1,
1353- 4,
1354- Some((8, 4, 2, 1, &[13, 14, 15, 16, 18], &[13, 15, 18], &[13, 18])),
1355- ),
1356- (
1357- 88200,
1358- 14,
1359- 10,
1360- 2,
1361- 1,
1362- 0,
1363- 3,
1364- Some((
1365- 8,
1366- 5,
1367- 3,
1368- 1,
1369- &[33, 35, 37, 40, 43, 46],
1370- &[33, 35, 40, 46],
1371- &[33, 46],
1372- )),
1373- ),
1374- (88200, 5, 12, 2, 1, 1, 4, None),
1375- (64000, 3, 13, 0, 0, 0, 2, None),
1376- (
1377- 16000,
1378- 4,
1379- 10,
1380- 2,
1381- 1,
1382- 3,
1383- 7,
1384- Some((
1385- 14,
1386- 7,
1387- 4,
1388- 3,
1389- &[32, 34, 37, 40, 44, 48, 53, 58],
1390- &[32, 34, 40, 48, 58],
1391- &[32, 34, 40, 58],
1392- )),
1393- ),
1394- (
1395- 24000,
1396- 2,
1397- 9,
1398- 1,
1399- 1,
1400- 0,
1401- 5,
1402- Some((
1403- 20,
1404- 15,
1405- 8,
1406- 1,
1407- &[
1408- 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 35, 38, 41, 44, 48, 52,
1409- ],
1410- &[19, 20, 22, 24, 28, 32, 38, 44, 52],
1411- &[19, 52],
1412- )),
1413- ),
1414- (
1415- 24000,
1416- 12,
1417- 8,
1418- 2,
1419- 1,
1420- 2,
1421- 7,
1422- Some((10, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
1423- ),
1424- (
1425- 32000,
1426- 6,
1427- 2,
1428- 0,
1429- 1,
1430- 0,
1431- 4,
1432- Some((
1433- 10,
1434- 6,
1435- 3,
1436- 1,
1437- &[24, 26, 28, 30, 32, 34, 36],
1438- &[24, 28, 32, 36],
1439- &[24, 36],
1440- )),
1441- ),
1442- (96000, 12, 4, 0, 1, 2, 2, None),
1443- (88200, 9, 12, 3, 1, 0, 3, None),
1444- (
1445- 44100,
1446- 2,
1447- 3,
1448- 0,
1449- 1,
1450- 1,
1451- 2,
1452- Some((
1453- 10,
1454- 8,
1455- 4,
1456- 1,
1457- &[13, 15, 17, 19, 21, 23, 25, 27, 29],
1458- &[13, 17, 21, 25, 29],
1459- &[13, 29],
1460- )),
1461- ),
1462- (
1463- 24000,
1464- 4,
1465- 2,
1466- 2,
1467- 0,
1468- 0,
1469- 4,
1470- Some((
1471- 12,
1472- 8,
1473- 4,
1474- 1,
1475- &[20, 22, 24, 26, 28, 30, 32, 34, 36],
1476- &[20, 24, 28, 32, 36],
1477- &[20, 36],
1478- )),
1479- ),
1480- (44100, 14, 1, 2, 1, 3, 7, None),
1481- (
1482- 16000,
1483- 14,
1484- 13,
1485- 0,
1486- 0,
1487- 3,
1488- 5,
1489- Some((
1490- 34,
1491- 29,
1492- 15,
1493- 3,
1494- &[
1495- 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
1496- 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
1497- ],
1498- &[
1499- 35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
1500- ],
1501- &[35, 44, 54, 64],
1502- )),
1503- ),
1504- (
1505- 24000,
1506- 5,
1507- 4,
1508- 1,
1509- 0,
1510- 1,
1511- 4,
1512- Some((
1513- 14,
1514- 10,
1515- 5,
1516- 1,
1517- &[21, 22, 23, 24, 26, 28, 30, 32, 34, 37, 40],
1518- &[21, 23, 26, 30, 34, 40],
1519- &[21, 40],
1520- )),
1521- ),
1522- (
1523- 32000,
1524- 12,
1525- 2,
1526- 1,
1527- 0,
1528- 3,
1529- 2,
1530- Some((6, 4, 2, 1, &[28, 30, 32, 34, 36], &[28, 32, 36], &[28, 36])),
1531- ),
1532- (
1533- 96000,
1534- 4,
1535- 1,
1536- 3,
1537- 1,
1538- 3,
1539- 1,
1540- Some((
1541- 6,
1542- 5,
1543- 3,
1544- 2,
1545- &[10, 11, 12, 13, 14, 15],
1546- &[10, 11, 13, 15],
1547- &[10, 11, 15],
1548- )),
1549- ),
1550- (
1551- 64000,
1552- 5,
1553- 14,
1554- 0,
1555- 0,
1556- 1,
1557- 4,
1558- Some((
1559- 12,
1560- 8,
1561- 4,
1562- 1,
1563- &[16, 17, 18, 19, 20, 21, 22, 23, 24],
1564- &[16, 18, 20, 22, 24],
1565- &[16, 24],
1566- )),
1567- ),
1568- (
1569- 24000,
1570- 13,
1571- 8,
1572- 2,
1573- 0,
1574- 1,
1575- 0,
1576- Some((
1577- 8,
1578- 8,
1579- 4,
1580- 1,
1581- &[27, 29, 31, 33, 36, 39, 42, 45, 49],
1582- &[27, 31, 36, 42, 49],
1583- &[27, 49],
1584- )),
1585- ),
1586- (
1587- 96000,
1588- 6,
1589- 2,
1590- 2,
1591- 1,
1592- 0,
1593- 3,
1594- Some((6, 3, 2, 1, &[14, 15, 16, 17], &[14, 15, 17], &[14, 17])),
1595- ),
1596- (
1597- 88200,
1598- 7,
1599- 6,
1600- 3,
1601- 0,
1602- 3,
1603- 4,
1604- Some((
1605- 10,
1606- 6,
1607- 3,
1608- 3,
1609- &[16, 18, 20, 22, 24, 26, 29],
1610- &[16, 20, 24, 29],
1611- &[16, 20, 24, 29],
1612- )),
1613- ),
1614- (88200, 2, 14, 1, 0, 0, 5, None),
1615- (
1616- 96000,
1617- 6,
1618- 3,
1619- 3,
1620- 0,
1621- 3,
1622- 1,
1623- Some((
1624- 6,
1625- 5,
1626- 3,
1627- 2,
1628- &[12, 13, 14, 15, 17, 19],
1629- &[12, 13, 15, 19],
1630- &[12, 13, 19],
1631- )),
1632- ),
1633- (32000, 0, 3, 1, 1, 2, 6, None),
1634- (
1635- 48000,
1636- 14,
1637- 5,
1638- 1,
1639- 0,
1640- 2,
1641- 0,
1642- Some((2, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
1643- ),
1644- (64000, 3, 8, 1, 1, 3, 5, None),
1645- (
1646- 22050,
1647- 13,
1648- 0,
1649- 3,
1650- 0,
1651- 2,
1652- 0,
1653- Some((4, 4, 2, 1, &[26, 28, 30, 32, 35], &[26, 30, 35], &[26, 35])),
1654- ),
1655- (
1656- 44100,
1657- 0,
1658- 8,
1659- 0,
1660- 1,
1661- 2,
1662- 1,
1663- Some((
1664- 18,
1665- 17,
1666- 9,
1667- 5,
1668- &[
1669- 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43,
1670- ],
1671- &[9, 11, 15, 19, 23, 27, 31, 35, 39, 43],
1672- &[9, 11, 19, 27, 35, 43],
1673- )),
1674- ),
1675- (
1676- 48000,
1677- 9,
1678- 14,
1679- 3,
1680- 1,
1681- 2,
1682- 7,
1683- Some((8, 1, 1, 1, &[31, 34], &[31, 34], &[31, 34])),
1684- ),
1685- (88200, 13, 6, 1, 1, 0, 7, None),
1686- (88200, 2, 3, 3, 1, 3, 6, None),
1687- (
1688- 64000,
1689- 0,
1690- 0,
1691- 0,
1692- 0,
1693- 0,
1694- 1,
1695- Some((
1696- 14,
1697- 13,
1698- 7,
1699- 1,
1700- &[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
1701- &[7, 8, 10, 12, 14, 16, 18, 20],
1702- &[7, 20],
1703- )),
1704- ),
1705- (44100, 0, 5, 1, 0, 1, 4, None),
1706- (48000, 0, 13, 2, 1, 2, 3, None),
1707- (
1708- 44100,
1709- 14,
1710- 6,
1711- 1,
1712- 1,
1713- 3,
1714- 2,
1715- Some((4, 2, 1, 1, &[32, 34, 37], &[32, 37], &[32, 37])),
1716- ),
1717- (96000, 2, 10, 0, 0, 1, 0, None),
1718- (88200, 3, 11, 3, 1, 1, 3, None),
1719- (
1720- 64000,
1721- 13,
1722- 11,
1723- 0,
1724- 1,
1725- 2,
1726- 3,
1727- Some((
1728- 16,
1729- 13,
1730- 7,
1731- 2,
1732- &[28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54],
1733- &[28, 30, 34, 38, 42, 46, 50, 54],
1734- &[28, 38, 54],
1735- )),
1736- ),
1737- (64000, 14, 0, 3, 1, 1, 1, None),
1738- (
1739- 24000,
1740- 11,
1741- 13,
1742- 2,
1743- 0,
1744- 1,
1745- 0,
1746- Some((
1747- 14,
1748- 14,
1749- 7,
1750- 1,
1751- &[23, 24, 26, 28, 30, 32, 34, 37, 40, 43, 46, 50, 54, 59, 64],
1752- &[23, 26, 30, 34, 40, 46, 54, 64],
1753- &[23, 64],
1754- )),
1755- ),
1756- (
1757- 32000,
1758- 11,
1759- 8,
1760- 0,
1761- 1,
1762- 1,
1763- 1,
1764- Some((
1765- 14,
1766- 13,
1767- 7,
1768- 1,
1769- &[24, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49],
1770- &[24, 25, 29, 33, 37, 41, 45, 49],
1771- &[24, 49],
1772- )),
1773- ),
1774- (
1775- 96000,
1776- 11,
1777- 6,
1778- 0,
1779- 0,
1780- 2,
1781- 2,
1782- Some((
1783- 8,
1784- 6,
1785- 3,
1786- 1,
1787- &[20, 21, 22, 23, 24, 25, 27],
1788- &[20, 22, 24, 27],
1789- &[20, 27],
1790- )),
1791- ),
1792- (44100, 0, 14, 2, 1, 1, 5, None),
1793- (
1794- 32000,
1795- 6,
1796- 2,
1797- 3,
1798- 0,
1799- 2,
1800- 2,
1801- Some((
1802- 8,
1803- 6,
1804- 3,
1805- 2,
1806- &[21, 23, 25, 27, 30, 33, 36],
1807- &[21, 25, 30, 36],
1808- &[21, 25, 36],
1809- )),
1810- ),
1811- (
1812- 32000,
1813- 3,
1814- 3,
1815- 3,
1816- 0,
1817- 3,
1818- 1,
1819- Some((
1820- 10,
1821- 9,
1822- 5,
1823- 4,
1824- &[16, 17, 19, 21, 23, 25, 27, 30, 34, 38],
1825- &[16, 17, 21, 25, 30, 38],
1826- &[16, 17, 21, 25, 38],
1827- )),
1828- ),
1829- (
1830- 44100,
1831- 14,
1832- 12,
1833- 0,
1834- 1,
1835- 1,
1836- 6,
1837- Some((
1838- 16,
1839- 10,
1840- 5,
1841- 1,
1842- &[39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59],
1843- &[39, 43, 47, 51, 55, 59],
1844- &[39, 59],
1845- )),
1846- ),
1847- (
1848- 24000,
1849- 11,
1850- 8,
1851- 0,
1852- 1,
1853- 1,
1854- 6,
1855- Some((
1856- 14,
1857- 8,
1858- 4,
1859- 1,
1860- &[33, 35, 37, 39, 41, 43, 45, 47, 49],
1861- &[33, 37, 41, 45, 49],
1862- &[33, 49],
1863- )),
1864- ),
1865- (
1866- 22050,
1867- 1,
1868- 9,
1869- 2,
1870- 0,
1871- 0,
1872- 3,
1873- Some((
1874- 20,
1875- 17,
1876- 9,
1877- 1,
1878- &[
1879- 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 52,
1880- ],
1881- &[16, 17, 19, 22, 26, 30, 34, 39, 45, 52],
1882- &[16, 52],
1883- )),
1884- ),
1885- (
1886- 16000,
1887- 3,
1888- 8,
1889- 0,
1890- 1,
1891- 2,
1892- 2,
1893- Some((
1894- 18,
1895- 16,
1896- 8,
1897- 3,
1898- &[
1899- 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 56,
1900- ],
1901- &[23, 27, 31, 35, 39, 43, 47, 51, 56],
1902- &[23, 31, 43, 56],
1903- )),
1904- ),
1905- (44100, 4, 1, 1, 0, 0, 3, None),
1906- (
1907- 64000,
1908- 10,
1909- 1,
1910- 1,
1911- 0,
1912- 2,
1913- 1,
1914- Some((4, 3, 2, 1, &[18, 19, 20, 22], &[18, 19, 22], &[18, 22])),
1915- ),
1916- (
1917- 24000,
1918- 1,
1919- 3,
1920- 0,
1921- 0,
1922- 0,
1923- 2,
1924- Some((
1925- 24,
1926- 22,
1927- 11,
1928- 1,
1929- &[
1930- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
1931- 35, 36, 38,
1932- ],
1933- &[15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 38],
1934- &[15, 38],
1935- )),
1936- ),
1937- (24000, 11, 1, 3, 1, 2, 5, None),
1938- (
1939- 24000,
1940- 5,
1941- 7,
1942- 1,
1943- 0,
1944- 2,
1945- 7,
1946- Some((
1947- 18,
1948- 11,
1949- 6,
1950- 2,
1951- &[24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
1952- &[24, 26, 30, 34, 38, 42, 46],
1953- &[24, 34, 46],
1954- )),
1955- ),
1956- (
1957- 88200,
1958- 14,
1959- 10,
1960- 0,
1961- 1,
1962- 3,
1963- 4,
1964- Some((
1965- 10,
1966- 6,
1967- 3,
1968- 1,
1969- &[34, 36, 38, 40, 42, 44, 46],
1970- &[34, 38, 42, 46],
1971- &[34, 46],
1972- )),
1973- ),
1974- (64000, 13, 12, 3, 1, 1, 6, None),
1975- (
1976- 96000,
1977- 11,
1978- 10,
1979- 2,
1980- 1,
1981- 0,
1982- 5,
1983- Some((
1984- 12,
1985- 7,
1986- 4,
1987- 1,
1988- &[25, 27, 29, 31, 33, 36, 40, 44],
1989- &[25, 27, 31, 36, 44],
1990- &[25, 44],
1991- )),
1992- ),
1993- (
1994- 44100,
1995- 3,
1996- 6,
1997- 0,
1998- 0,
1999- 3,
2000- 6,
crates/ec-aac/src/sbr_bands/mod.rsadded+251 -0
@@ -0,0 +1,251 @@
1+//! SBR frequency band tables (ISO/IEC 14496-3 §4.6.18.3.2.1): `f_master`,
2+//! `f_high`, `f_low`, `f_noise` from a header's `bs_start_freq`/`bs_stop_freq`/
3+//! `bs_freq_scale`/`bs_alter_scale`/`bs_xover_band`/`bs_noise_bands`.
4+//!
5+//! This is a direct port of `scripts/aac-tables/sbrtables.py`'s `freq_tables`/
6+//! `f_master`/`make_bands`, which was checked against a reference decoder over
7+//! 6387 header configurations (recorded in the project ledger). The port itself
8+//! is re-checked here against 500 configurations run through that same Python
9+//! function, embedded as literal test vectors so the check needs no Python at
10+//! test time -- only the numbers it once printed.
11+#![allow(dead_code)]
12+
13+/// `k0` offset by SBR sample rate and `bs_start_freq`, ten rates the reference
14+/// decoder was probed at (`--stage k0`).
15+fn k0_offsets(rate: u32) -> Option<[i32; 16]> {
16+ Some(match rate {
17+ 16000 => [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7],
18+ 22050 => [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13],
19+ 24000 => [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
20+ 32000 => [-6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
21+ 44100 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
22+ 48000 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
23+ 64000 => [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
24+ 88200 => [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
25+ 96000 => [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
26+ _ => return None,
27+ })
28+}
29+
30+/// The QMF band a 3, 4 or 5 kHz border falls in: `(start_min, stop_min)`.
31+fn start_stop_min(rate: u32) -> (i64, i64) {
32+ let temp: i64 = if rate < 32000 {
33+ 3000
34+ } else if rate < 64000 {
35+ 4000
36+ } else {
37+ 5000
38+ };
39+ let rate = rate as i64;
40+ (
41+ ((temp << 7) + (rate >> 1)) / rate,
42+ ((temp << 8) + (rate >> 1)) / rate,
43+ )
44+}
45+
46+/// The widest `k2 - k0` reconstructed at this rate.
47+fn span_limit(rate: u32) -> i64 {
48+ if rate < 32000 {
49+ 48
50+ } else if rate < 64000 {
51+ 35
52+ } else {
53+ 32
54+ }
55+}
56+
57+/// `num` band widths geometrically spaced from `start` to `stop`.
58+fn make_bands(start: i64, stop: i64, num: i64) -> Vec<i64> {
59+ let base = (stop as f64 / start as f64).powf(1.0 / num as f64);
60+ let mut prod = start as f64;
61+ let mut previous = start;
62+ let mut out = Vec::new();
63+ for _ in 0..num - 1 {
64+ prod *= base;
65+ let present = (prod + 0.5).floor() as i64;
66+ out.push(present - previous);
67+ previous = present;
68+ }
69+ out.push(stop - previous);
70+ out
71+}
72+
73+/// The master frequency band table.
74+fn f_master(
75+ rate: u32,
76+ start_freq: usize,
77+ stop_freq: usize,
78+ freq_scale: i32,
79+ alter_scale: i32,
80+) -> Option<Vec<i64>> {
81+ let offsets = k0_offsets(rate)?;
82+ let (start_min, stop_min) = start_stop_min(rate);
83+ let k0 = start_min + offsets[start_freq] as i64;
84+ let k2 = if stop_freq < 14 {
85+ let mut widths = make_bands(stop_min, 64, 13);
86+ widths.sort();
87+ stop_min + widths[..stop_freq].iter().sum::<i64>()
88+ } else if stop_freq == 14 {
89+ 2 * k0
90+ } else {
91+ 3 * k0
92+ };
93+ let k2 = k2.min(64);
94+ if k2 <= k0 || k2 - k0 > span_limit(rate) {
95+ return None;
96+ }
97+
98+ if freq_scale == 0 {
99+ let dk: i64 = if alter_scale != 0 { 2 } else { 1 };
100+ let num_bands = 2 * ((k2 - k0 + 2 * (dk - 1)) / (2 * dk));
101+ if num_bands <= 0 {
102+ return None;
103+ }
104+ let mut vk = vec![dk; num_bands as usize];
105+ let mut k2diff = k2 - k0 - num_bands * dk;
106+ let (mut at, incr): (i64, i64) = if k2diff < 0 {
107+ (0, 1)
108+ } else {
109+ (num_bands - 1, -1)
110+ };
111+ while k2diff != 0 && at >= 0 && at < num_bands {
112+ vk[at as usize] -= incr;
113+ at += incr;
114+ k2diff += incr;
115+ }
116+ let mut table = vec![k0];
117+ for d in vk {
118+ if d <= 0 {
119+ return None;
120+ }
121+ table.push(table[table.len() - 1] + d);
122+ }
123+ return Some(table);
124+ }
125+
126+ let half_bands = 7 - freq_scale;
127+ let two_regions = 49 * k2 > 110 * k0;
128+ let k1 = if two_regions { 2 * k0 } else { k2 };
129+ let num_bands_0 = 2 * (half_bands as f64 * (k1 as f64 / k0 as f64).log2() + 0.5).floor() as i64;
130+ if num_bands_0 <= 0 {
131+ return None;
132+ }
133+ let mut vk0 = make_bands(k0, k1, num_bands_0);
134+ vk0.sort();
135+ let vdk0_max = vk0[vk0.len() - 1];
136+ let mut table = vec![k0];
137+ for &d in &vk0 {
138+ if d <= 0 {
139+ return None;
140+ }
141+ table.push(table[table.len() - 1] + d);
142+ }
143+ if !two_regions {
144+ return Some(table);
145+ }
146+ let invwarp = if alter_scale != 0 { 1.0 / 1.3 } else { 1.0 };
147+ let num_bands_1 =
148+ 2 * (half_bands as f64 * invwarp * (k2 as f64 / k1 as f64).log2() + 0.5).floor() as i64;
149+ if num_bands_1 <= 0 {
150+ return None;
151+ }
152+ let mut vk1 = make_bands(k1, k2, num_bands_1);
153+ vk1.sort();
154+ if vdk0_max > vk1[0] {
155+ let change = (vdk0_max - vk1[0]).min((vk1[vk1.len() - 1] - vk1[0]) >> 1);
156+ let last = vk1.len() - 1;
157+ vk1[0] += change;
158+ vk1[last] -= change;
159+ vk1.sort();
160+ }
161+ for &d in &vk1 {
162+ if d <= 0 {
163+ return None;
164+ }
165+ table.push(table[table.len() - 1] + d);
166+ }
167+ Some(table)
168+}
169+
170+/// The derived band tables for one SBR header, or `None` if the reference
171+/// decoder would have refused this combination.
172+#[derive(Debug, Clone, PartialEq, Eq)]
173+pub struct BandTables {
174+ pub n_master: usize,
175+ pub n_high: usize,
176+ pub n_low: usize,
177+ pub n_q: usize,
178+ pub f_high: Vec<i64>,
179+ pub f_low: Vec<i64>,
180+ pub f_noise: Vec<i64>,
181+ pub kx: i64,
182+ pub k2: i64,
183+ /// Master table borders (`k0 = f_master[0]`), needed by the patch builder.
184+ pub f_master: Vec<i64>,
185+ /// SBR (output) sample rate, the patch builder's `goalSb` input.
186+ pub rate: u32,
187+}
188+
189+/// `rate` is the SBR rate: twice the AAC-LC core's.
190+pub fn freq_tables(
191+ rate: u32,
192+ start_freq: usize,
193+ stop_freq: usize,
194+ freq_scale: i32,
195+ alter_scale: i32,
196+ xover_band: usize,
197+ noise_bands: i32,
198+) -> Option<BandTables> {
199+ let master = f_master(rate, start_freq, stop_freq, freq_scale, alter_scale)?;
200+ let n_master = master.len() - 1;
201+ if xover_band > n_master {
202+ return None;
203+ }
204+ let n_high = n_master - xover_band;
205+ if n_high < 1 {
206+ return None;
207+ }
208+ let n_low = (n_high + 1) >> 1;
209+ let f_high = master[xover_band..].to_vec();
210+ let mut f_low = vec![f_high[0]];
211+ if n_high & 1 != 0 {
212+ for k in 1..=n_low {
213+ f_low.push(f_high[2 * k - 1]);
214+ }
215+ } else {
216+ for k in 1..=n_low {
217+ f_low.push(f_high[2 * k]);
218+ }
219+ }
220+ let kx = f_high[0];
221+ let k2 = master[master.len() - 1];
222+ let n_q = (1i64.max((noise_bands as f64 * (k2 as f64 / kx as f64).log2() + 0.5).floor() as i64))
223+ as usize;
224+ if n_q > 5 {
225+ return None;
226+ }
227+ let mut f_noise = vec![f_low[0]];
228+ let mut temp = 0i64;
229+ for k in 1..=n_q {
230+ temp += (n_low as i64 - temp) / (n_q as i64 + 1 - k as i64);
231+ f_noise.push(f_low[temp as usize]);
232+ }
233+ Some(BandTables {
234+ n_master,
235+ n_high,
236+ n_low,
237+ n_q,
238+ f_high,
239+ f_low,
240+ f_noise,
241+ kx,
242+ k2,
243+ f_master: master.clone(),
244+ rate,
245+ })
246+}
247+
248+#[cfg(test)]
249+mod tests;
250+#[cfg(test)]
251+mod vectors;
crates/ec-aac/src/sbr_bands/tests.rsadded+86 -0
@@ -0,0 +1,86 @@
1+use super::*;
2+use super::vectors::VECTORS;
3+
4+#[test]
5+fn matches_reference_derivation_on_500_configurations() {
6+ let mut mismatches = 0;
7+ for &(
8+ rate,
9+ start_freq,
10+ stop_freq,
11+ freq_scale,
12+ alter_scale,
13+ noise_bands,
14+ xover_band,
15+ expected,
16+ ) in VECTORS.iter().flat_map(|part| part.iter())
17+ {
18+ let got = freq_tables(
19+ rate,
20+ start_freq,
21+ stop_freq,
22+ freq_scale,
23+ alter_scale,
24+ xover_band,
25+ noise_bands,
26+ );
27+ let ok = match (&got, expected) {
28+ (None, None) => true,
29+ (Some(t), Some((n_master, n_high, n_low, n_q, f_high, f_low, f_noise))) => {
30+ t.n_master == n_master
31+ && t.n_high == n_high
32+ && t.n_low == n_low
33+ && t.n_q == n_q
34+ && t.f_high == f_high
35+ && t.f_low == f_low
36+ && t.f_noise == f_noise
37+ }
38+ _ => false,
39+ };
40+ if !ok {
41+ mismatches += 1;
42+ if mismatches <= 10 {
43+ eprintln!(
44+ "mismatch rate={rate} start={start_freq} stop={stop_freq} scale={freq_scale} \
45+ alter={alter_scale} noise={noise_bands} xover={xover_band}: got {got:?} want {expected:?}"
46+ );
47+ }
48+ }
49+ }
50+ assert_eq!(
51+ mismatches, 0,
52+ "{mismatches}/500 configurations disagreed with the reference derivation"
53+ );
54+}
55+
56+#[test]
57+fn bands_are_monotonic_when_present() {
58+ for &(
59+ rate,
60+ start_freq,
61+ stop_freq,
62+ freq_scale,
63+ alter_scale,
64+ noise_bands,
65+ xover_band,
66+ expected,
67+ ) in VECTORS.iter().flat_map(|part| part.iter())
68+ {
69+ if expected.is_none() {
70+ continue;
71+ }
72+ let t = freq_tables(
73+ rate,
74+ start_freq,
75+ stop_freq,
76+ freq_scale,
77+ alter_scale,
78+ xover_band,
79+ noise_bands,
80+ )
81+ .expect("vector says Some");
82+ assert!(t.f_high.windows(2).all(|w| w[0] < w[1]));
83+ assert!(t.f_low.windows(2).all(|w| w[0] < w[1]));
84+ assert!(t.f_noise.windows(2).all(|w| w[0] < w[1]));
85+ }
86+}
crates/ec-aac/src/sbr_bands/vectors/mod.rsadded+25 -0
@@ -0,0 +1,25 @@
1+//! Reference vectors for the `freq_tables` tests: 500 configurations sampled from the
2+//! same `freq_tables()` Python function the project ledger records as checked against a
3+//! reference decoder over 6387 configurations; regenerate with
4+//! `scripts/aac-tables/sbrtables.py`'s `freq_tables` if that function ever changes.
5+
6+mod part0;
7+mod part1;
8+
9+/// `(sbr_rate, start_freq, stop_freq, freq_scale, alter_scale, noise_bands,
10+/// xover_band, expected)`, `expected` being `(n_master, n_high, n_low, n_q,
11+/// f_high, f_low, f_noise)`.
12+#[allow(clippy::type_complexity)]
13+pub(super) type Vector = (
14+ u32,
15+ usize,
16+ usize,
17+ i32,
18+ i32,
19+ i32,
20+ usize,
21+ Option<(usize, usize, usize, usize, &'static [i64], &'static [i64], &'static [i64])>,
22+);
23+
24+/// All reference vectors, in two parts.
25+pub(super) static VECTORS: &[&[Vector]] = &[part0::PART, part1::PART];
crates/ec-aac/src/sbr_bands/vectors/part0.rsadded+4305 -0

Diff too large; view file

@@ -0,0 +1,4305 @@
1+//! Reference vectors for the `freq_tables` tests, first half of the 500 (test-only data).
2+
3+use super::Vector;
4+
5+pub(super) static PART: &[Vector] = &[
6+ (
7+ 24000,
8+ 13,
9+ 2,
10+ 1,
11+ 0,
12+ 2,
13+ 0,
14+ Some((4, 4, 2, 1, &[27, 29, 31, 33, 36], &[27, 31, 36], &[27, 36])),
15+ ),
16+ (
17+ 24000,
18+ 11,
19+ 1,
20+ 1,
21+ 1,
22+ 2,
23+ 2,
24+ Some((6, 4, 2, 1, &[26, 28, 30, 32, 34], &[26, 30, 34], &[26, 34])),
25+ ),
26+ (
27+ 32000,
28+ 13,
29+ 5,
30+ 2,
31+ 0,
32+ 1,
33+ 5,
34+ Some((6, 1, 1, 1, &[39, 42], &[39, 42], &[39, 42])),
35+ ),
36+ (
37+ 32000,
38+ 2,
39+ 2,
40+ 2,
41+ 0,
42+ 2,
43+ 6,
44+ Some((
45+ 14,
46+ 8,
47+ 4,
48+ 2,
49+ &[20, 22, 24, 26, 28, 30, 32, 34, 36],
50+ &[20, 24, 28, 32, 36],
51+ &[20, 28, 36],
52+ )),
53+ ),
54+ (
55+ 22050,
56+ 13,
57+ 2,
58+ 2,
59+ 1,
60+ 1,
61+ 5,
62+ Some((6, 1, 1, 1, &[35, 38], &[35, 38], &[35, 38])),
63+ ),
64+ (16000, 14, 0, 2, 1, 2, 6, None),
65+ (
66+ 64000,
67+ 9,
68+ 9,
69+ 3,
70+ 1,
71+ 1,
72+ 1,
73+ Some((
74+ 12,
75+ 11,
76+ 6,
77+ 1,
78+ &[17, 19, 21, 23, 25, 27, 29, 32, 35, 38, 41, 45],
79+ &[17, 19, 23, 27, 32, 38, 45],
80+ &[17, 45],
81+ )),
82+ ),
83+ (44100, 15, 1, 1, 0, 0, 5, None),
84+ (
85+ 16000,
86+ 8,
87+ 12,
88+ 2,
89+ 1,
90+ 1,
91+ 6,
92+ Some((
93+ 12,
94+ 6,
95+ 3,
96+ 1,
97+ &[36, 39, 42, 45, 48, 55, 62],
98+ &[36, 42, 48, 62],
99+ &[36, 62],
100+ )),
101+ ),
102+ (
103+ 44100,
104+ 3,
105+ 3,
106+ 3,
107+ 1,
108+ 0,
109+ 4,
110+ Some((
111+ 10,
112+ 6,
113+ 3,
114+ 1,
115+ &[16, 18, 20, 22, 24, 26, 29],
116+ &[16, 20, 24, 29],
117+ &[16, 29],
118+ )),
119+ ),
120+ (
121+ 24000,
122+ 7,
123+ 3,
124+ 3,
125+ 0,
126+ 1,
127+ 6,
128+ Some((8, 2, 1, 1, &[32, 35, 38], &[32, 38], &[32, 38])),
129+ ),
130+ (
131+ 16000,
132+ 10,
133+ 11,
134+ 1,
135+ 0,
136+ 3,
137+ 4,
138+ Some((
139+ 14,
140+ 10,
141+ 5,
142+ 3,
143+ &[33, 35, 37, 39, 41, 43, 46, 49, 52, 56, 60],
144+ &[33, 37, 41, 46, 52, 60],
145+ &[33, 37, 46, 60],
146+ )),
147+ ),
148+ (
149+ 96000,
150+ 10,
151+ 10,
152+ 0,
153+ 1,
154+ 2,
155+ 7,
156+ Some((
157+ 14,
158+ 7,
159+ 4,
160+ 1,
161+ &[30, 32, 34, 36, 38, 40, 42, 44],
162+ &[30, 32, 36, 40, 44],
163+ &[30, 44],
164+ )),
165+ ),
166+ (48000, 2, 10, 3, 1, 2, 3, None),
167+ (
168+ 16000,
169+ 0,
170+ 10,
171+ 0,
172+ 1,
173+ 1,
174+ 4,
175+ Some((
176+ 22,
177+ 18,
178+ 9,
179+ 1,
180+ &[
181+ 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58,
182+ ],
183+ &[22, 26, 30, 34, 38, 42, 46, 50, 54, 58],
184+ &[22, 58],
185+ )),
186+ ),
187+ (64000, 11, 0, 1, 1, 2, 3, None),
188+ (
189+ 48000,
190+ 15,
191+ 14,
192+ 1,
193+ 1,
194+ 3,
195+ 1,
196+ Some((
197+ 12,
198+ 11,
199+ 6,
200+ 3,
201+ &[33, 35, 37, 39, 41, 43, 46, 49, 52, 55, 58, 62],
202+ &[33, 35, 39, 43, 49, 55, 62],
203+ &[33, 39, 49, 62],
204+ )),
205+ ),
206+ (64000, 6, 12, 2, 0, 0, 5, None),
207+ (
208+ 48000,
209+ 1,
210+ 4,
211+ 0,
212+ 1,
213+ 0,
214+ 7,
215+ Some((10, 3, 2, 1, &[23, 25, 27, 29], &[23, 25, 29], &[23, 29])),
216+ ),
217+ (
218+ 24000,
219+ 9,
220+ 14,
221+ 3,
222+ 1,
223+ 1,
224+ 0,
225+ Some((
226+ 8,
227+ 8,
228+ 4,
229+ 1,
230+ &[21, 23, 25, 27, 29, 32, 35, 38, 42],
231+ &[21, 25, 29, 35, 42],
232+ &[21, 42],
233+ )),
234+ ),
235+ (
236+ 24000,
237+ 4,
238+ 6,
239+ 3,
240+ 1,
241+ 0,
242+ 0,
243+ Some((
244+ 10,
245+ 10,
246+ 5,
247+ 1,
248+ &[16, 17, 19, 21, 23, 25, 27, 29, 32, 38, 44],
249+ &[16, 19, 23, 27, 32, 44],
250+ &[16, 44],
251+ )),
252+ ),
253+ (96000, 15, 8, 3, 1, 0, 4, None),
254+ (
255+ 64000,
256+ 1,
257+ 14,
258+ 0,
259+ 0,
260+ 1,
261+ 2,
262+ Some((
263+ 8,
264+ 6,
265+ 3,
266+ 1,
267+ &[10, 11, 12, 13, 14, 15, 16],
268+ &[10, 12, 14, 16],
269+ &[10, 16],
270+ )),
271+ ),
272+ (44100, 4, 10, 0, 0, 0, 2, None),
273+ (88200, 0, 9, 3, 0, 2, 5, None),
274+ (
275+ 32000,
276+ 3,
277+ 15,
278+ 2,
279+ 0,
280+ 2,
281+ 2,
282+ Some((
283+ 16,
284+ 14,
285+ 7,
286+ 3,
287+ &[17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45],
288+ &[17, 19, 22, 26, 30, 34, 39, 45],
289+ &[17, 22, 30, 45],
290+ )),
291+ ),
292+ (44100, 15, 3, 3, 0, 1, 3, None),
293+ (96000, 1, 5, 1, 0, 1, 6, None),
294+ (96000, 6, 8, 1, 1, 3, 2, None),
295+ (
296+ 48000,
297+ 14,
298+ 9,
299+ 1,
300+ 1,
301+ 3,
302+ 3,
303+ Some((
304+ 8,
305+ 5,
306+ 3,
307+ 1,
308+ &[33, 35, 37, 39, 42, 45],
309+ &[33, 35, 39, 45],
310+ &[33, 45],
311+ )),
312+ ),
313+ (
314+ 64000,
315+ 2,
316+ 8,
317+ 3,
318+ 0,
319+ 2,
320+ 5,
321+ Some((
322+ 18,
323+ 13,
324+ 7,
325+ 3,
326+ &[14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41],
327+ &[14, 15, 18, 22, 26, 30, 35, 41],
328+ &[14, 18, 26, 41],
329+ )),
330+ ),
331+ (
332+ 44100,
333+ 4,
334+ 8,
335+ 3,
336+ 1,
337+ 1,
338+ 7,
339+ Some((
340+ 12,
341+ 5,
342+ 3,
343+ 1,
344+ &[24, 26, 29, 33, 38, 43],
345+ &[24, 26, 33, 43],
346+ &[24, 43],
347+ )),
348+ ),
349+ (96000, 13, 6, 2, 1, 1, 7, None),
350+ (32000, 1, 2, 1, 0, 1, 5, None),
351+ (
352+ 96000,
353+ 4,
354+ 2,
355+ 0,
356+ 0,
357+ 3,
358+ 3,
359+ Some((
360+ 8,
361+ 5,
362+ 3,
363+ 2,
364+ &[12, 13, 14, 15, 16, 17],
365+ &[12, 13, 15, 17],
366+ &[12, 13, 17],
367+ )),
368+ ),
369+ (
370+ 48000,
371+ 12,
372+ 8,
373+ 2,
374+ 1,
375+ 1,
376+ 5,
377+ Some((8, 3, 2, 1, &[32, 35, 38, 41], &[32, 35, 41], &[32, 41])),
378+ ),
379+ (
380+ 22050,
381+ 14,
382+ 9,
383+ 1,
384+ 1,
385+ 3,
386+ 5,
387+ Some((
388+ 10,
389+ 5,
390+ 3,
391+ 1,
392+ &[38, 40, 43, 46, 49, 52],
393+ &[38, 40, 46, 52],
394+ &[38, 52],
395+ )),
396+ ),
397+ (32000, 0, 15, 2, 0, 2, 7, None),
398+ (
399+ 88200,
400+ 11,
401+ 5,
402+ 1,
403+ 1,
404+ 1,
405+ 2,
406+ Some((6, 4, 2, 1, &[20, 21, 22, 24, 26], &[20, 22, 26], &[20, 26])),
407+ ),
408+ (
409+ 22050,
410+ 4,
411+ 15,
412+ 0,
413+ 1,
414+ 2,
415+ 7,
416+ Some((
417+ 16,
418+ 9,
419+ 5,
420+ 1,
421+ &[30, 32, 34, 36, 38, 40, 42, 44, 46, 48],
422+ &[30, 32, 36, 40, 44, 48],
423+ &[30, 48],
424+ )),
425+ ),
426+ (
427+ 44100,
428+ 13,
429+ 12,
430+ 2,
431+ 0,
432+ 3,
433+ 3,
434+ Some((
435+ 12,
436+ 9,
437+ 5,
438+ 3,
439+ &[31, 33, 35, 38, 41, 44, 47, 50, 54, 59],
440+ &[31, 33, 38, 44, 50, 59],
441+ &[31, 33, 44, 59],
442+ )),
443+ ),
444+ (64000, 2, 3, 1, 1, 1, 6, None),
445+ (
446+ 32000,
447+ 6,
448+ 1,
449+ 3,
450+ 1,
451+ 3,
452+ 6,
453+ Some((8, 2, 1, 1, &[29, 31, 34], &[29, 34], &[29, 34])),
454+ ),
455+ (
456+ 88200,
457+ 13,
458+ 11,
459+ 1,
460+ 0,
461+ 1,
462+ 7,
463+ Some((
464+ 14,
465+ 7,
466+ 4,
467+ 1,
468+ &[34, 36, 38, 40, 42, 45, 48, 51],
469+ &[34, 36, 40, 45, 51],
470+ &[34, 51],
471+ )),
472+ ),
473+ (44100, 4, 10, 0, 0, 2, 5, None),
474+ (
475+ 32000,
476+ 13,
477+ 5,
478+ 1,
479+ 1,
480+ 3,
481+ 5,
482+ Some((8, 3, 2, 1, &[36, 38, 40, 42], &[36, 38, 42], &[36, 42])),
483+ ),
484+ (
485+ 24000,
486+ 5,
487+ 14,
488+ 0,
489+ 0,
490+ 0,
491+ 7,
492+ Some((
493+ 16,
494+ 9,
495+ 5,
496+ 1,
497+ &[24, 25, 26, 27, 28, 29, 30, 31, 32, 34],
498+ &[24, 25, 27, 29, 31, 34],
499+ &[24, 34],
500+ )),
501+ ),
502+ (22050, 14, 3, 2, 0, 3, 6, None),
503+ (
504+ 96000,
505+ 6,
506+ 7,
507+ 3,
508+ 0,
509+ 1,
510+ 6,
511+ Some((
512+ 12,
513+ 6,
514+ 3,
515+ 1,
516+ &[18, 20, 22, 24, 26, 28, 31],
517+ &[18, 22, 26, 31],
518+ &[18, 31],
519+ )),
520+ ),
521+ (
522+ 22050,
523+ 12,
524+ 3,
525+ 1,
526+ 0,
527+ 1,
528+ 7,
529+ Some((8, 1, 1, 1, &[37, 40], &[37, 40], &[37, 40])),
530+ ),
531+ (
532+ 32000,
533+ 2,
534+ 7,
535+ 0,
536+ 0,
537+ 0,
538+ 5,
539+ Some((
540+ 32,
541+ 27,
542+ 14,
543+ 1,
544+ &[
545+ 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
546+ 39, 40, 41, 42, 43, 44, 45, 46,
547+ ],
548+ &[19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
549+ &[19, 46],
550+ )),
551+ ),
552+ (96000, 15, 3, 2, 1, 1, 0, None),
553+ (
554+ 96000,
555+ 4,
556+ 8,
557+ 3,
558+ 1,
559+ 2,
560+ 1,
561+ Some((
562+ 14,
563+ 13,
564+ 7,
565+ 4,
566+ &[10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 25, 28, 31, 35],
567+ &[10, 11, 13, 15, 18, 22, 28, 35],
568+ &[10, 11, 15, 22, 35],
569+ )),
570+ ),
571+ (
572+ 96000,
573+ 4,
574+ 9,
575+ 3,
576+ 0,
577+ 0,
578+ 1,
579+ Some((
580+ 16,
581+ 15,
582+ 8,
583+ 1,
584+ &[
585+ 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 29, 32, 35, 39,
586+ ],
587+ &[10, 11, 13, 15, 18, 22, 26, 32, 39],
588+ &[10, 39],
589+ )),
590+ ),
591+ (
592+ 22050,
593+ 15,
594+ 13,
595+ 0,
596+ 0,
597+ 2,
598+ 0,
599+ Some((
600+ 34,
601+ 34,
602+ 17,
603+ 2,
604+ &[
605+ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
606+ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
607+ ],
608+ &[
609+ 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
610+ ],
611+ &[30, 46, 64],
612+ )),
613+ ),
614+ (96000, 13, 0, 0, 0, 0, 1, None),
615+ (
616+ 64000,
617+ 7,
618+ 3,
619+ 2,
620+ 0,
621+ 1,
622+ 7,
623+ Some((8, 1, 1, 1, &[24, 26], &[24, 26], &[24, 26])),
624+ ),
625+ (
626+ 64000,
627+ 0,
628+ 7,
629+ 0,
630+ 1,
631+ 0,
632+ 0,
633+ Some((
634+ 16,
635+ 16,
636+ 8,
637+ 1,
638+ &[
639+ 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37,
640+ ],
641+ &[6, 9, 13, 17, 21, 25, 29, 33, 37],
642+ &[6, 37],
643+ )),
644+ ),
645+ (64000, 1, 7, 2, 1, 0, 2, None),
646+ (
647+ 24000,
648+ 6,
649+ 8,
650+ 1,
651+ 1,
652+ 1,
653+ 5,
654+ Some((
655+ 16,
656+ 11,
657+ 6,
658+ 1,
659+ &[23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 49],
660+ &[23, 24, 28, 32, 36, 42, 49],
661+ &[23, 49],
662+ )),
663+ ),
664+ (
665+ 16000,
666+ 15,
667+ 1,
668+ 2,
669+ 0,
670+ 2,
671+ 2,
672+ Some((6, 4, 2, 1, &[36, 39, 42, 45, 49], &[36, 42, 49], &[36, 49])),
673+ ),
674+ (
675+ 22050,
676+ 7,
677+ 9,
678+ 1,
679+ 0,
680+ 1,
681+ 0,
682+ Some((
683+ 18,
684+ 18,
685+ 9,
686+ 1,
687+ &[
688+ 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49, 52,
689+ ],
690+ &[19, 21, 23, 26, 30, 34, 38, 42, 46, 52],
691+ &[19, 52],
692+ )),
693+ ),
694+ (
695+ 32000,
696+ 7,
697+ 5,
698+ 3,
699+ 1,
700+ 3,
701+ 4,
702+ Some((
703+ 10,
704+ 6,
705+ 3,
706+ 2,
707+ &[26, 28, 30, 33, 36, 39, 42],
708+ &[26, 30, 36, 42],
709+ &[26, 30, 42],
710+ )),
711+ ),
712+ (96000, 15, 11, 2, 0, 1, 6, None),
713+ (48000, 10, 11, 0, 1, 0, 0, None),
714+ (
715+ 32000,
716+ 6,
717+ 1,
718+ 2,
719+ 1,
720+ 2,
721+ 5,
722+ Some((
723+ 10,
724+ 5,
725+ 3,
726+ 1,
727+ &[24, 26, 28, 30, 32, 34],
728+ &[24, 26, 30, 34],
729+ &[24, 34],
730+ )),
731+ ),
732+ (88200, 6, 3, 1, 0, 1, 6, None),
733+ (
734+ 88200,
735+ 9,
736+ 7,
737+ 0,
738+ 1,
739+ 0,
740+ 6,
741+ Some((10, 4, 2, 1, &[25, 27, 29, 31, 33], &[25, 29, 33], &[25, 33])),
742+ ),
743+ (96000, 14, 2, 2, 0, 0, 1, None),
744+ (32000, 6, 11, 2, 1, 1, 3, None),
745+ (
746+ 16000,
747+ 2,
748+ 0,
749+ 2,
750+ 1,
751+ 3,
752+ 3,
753+ Some((
754+ 14,
755+ 11,
756+ 6,
757+ 4,
758+ &[21, 23, 25, 27, 29, 31, 33, 36, 39, 42, 45, 48],
759+ &[21, 23, 27, 31, 36, 42, 48],
760+ &[21, 23, 27, 36, 48],
761+ )),
762+ ),
763+ (
764+ 44100,
765+ 10,
766+ 5,
767+ 0,
768+ 1,
769+ 0,
770+ 2,
771+ Some((
772+ 8,
773+ 6,
774+ 3,
775+ 1,
776+ &[22, 24, 26, 28, 30, 32, 34],
777+ &[22, 26, 30, 34],
778+ &[22, 34],
779+ )),
780+ ),
781+ (88200, 14, 5, 1, 1, 2, 6, None),
782+ (64000, 8, 11, 2, 1, 0, 4, None),
783+ (
784+ 32000,
785+ 15,
786+ 8,
787+ 2,
788+ 0,
789+ 0,
790+ 3,
791+ Some((6, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
792+ ),
793+ (
794+ 32000,
795+ 11,
796+ 0,
797+ 2,
798+ 0,
799+ 0,
800+ 2,
801+ Some((4, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
802+ ),
803+ (88200, 7, 7, 1, 1, 1, 1, None),
804+ (
805+ 48000,
806+ 9,
807+ 0,
808+ 0,
809+ 0,
810+ 0,
811+ 0,
812+ Some((4, 4, 2, 1, &[17, 18, 19, 20, 21], &[17, 19, 21], &[17, 21])),
813+ ),
814+ (48000, 12, 13, 0, 0, 0, 5, None),
815+ (
816+ 96000,
817+ 15,
818+ 12,
819+ 1,
820+ 0,
821+ 0,
822+ 7,
823+ Some((10, 3, 2, 1, &[47, 50, 53, 57], &[47, 50, 57], &[47, 57])),
824+ ),
825+ (96000, 14, 0, 3, 1, 2, 0, None),
826+ (
827+ 64000,
828+ 6,
829+ 14,
830+ 3,
831+ 1,
832+ 0,
833+ 1,
834+ Some((
835+ 8,
836+ 7,
837+ 4,
838+ 1,
839+ &[14, 15, 16, 18, 20, 22, 24, 26],
840+ &[14, 15, 18, 22, 26],
841+ &[14, 26],
842+ )),
843+ ),
844+ (64000, 1, 2, 3, 0, 3, 7, None),
845+ (
846+ 48000,
847+ 8,
848+ 8,
849+ 2,
850+ 0,
851+ 1,
852+ 7,
853+ Some((
854+ 14,
855+ 7,
856+ 4,
857+ 1,
858+ &[26, 28, 30, 32, 34, 36, 38, 41],
859+ &[26, 28, 32, 36, 41],
860+ &[26, 41],
861+ )),
862+ ),
863+ (48000, 7, 1, 3, 0, 1, 6, None),
864+ (
865+ 32000,
866+ 2,
867+ 15,
868+ 0,
869+ 1,
870+ 0,
871+ 0,
872+ Some((
873+ 14,
874+ 14,
875+ 7,
876+ 1,
877+ &[14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
878+ &[14, 18, 22, 26, 30, 34, 38, 42],
879+ &[14, 42],
880+ )),
881+ ),
882+ (64000, 4, 5, 1, 0, 1, 0, None),
883+ (
884+ 32000,
885+ 2,
886+ 5,
887+ 1,
888+ 0,
889+ 1,
890+ 1,
891+ Some((
892+ 20,
893+ 19,
894+ 10,
895+ 1,
896+ &[
897+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 29, 30, 32, 34, 36, 38, 40, 42,
898+ ],
899+ &[15, 16, 18, 20, 22, 24, 28, 30, 34, 38, 42],
900+ &[15, 42],
901+ )),
902+ ),
903+ (64000, 11, 4, 2, 0, 3, 6, None),
904+ (
905+ 16000,
906+ 4,
907+ 13,
908+ 2,
909+ 0,
910+ 3,
911+ 5,
912+ Some((
913+ 16,
914+ 11,
915+ 6,
916+ 4,
917+ &[28, 30, 32, 34, 37, 40, 43, 47, 51, 55, 59, 64],
918+ &[28, 30, 34, 40, 47, 55, 64],
919+ &[28, 30, 34, 47, 64],
920+ )),
921+ ),
922+ (
923+ 64000,
924+ 15,
925+ 14,
926+ 0,
927+ 0,
928+ 1,
929+ 3,
930+ Some((
931+ 30,
932+ 27,
933+ 14,
934+ 1,
935+ &[
936+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
937+ 53, 54, 55, 56, 57, 58, 59, 60,
938+ ],
939+ &[33, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60],
940+ &[33, 60],
941+ )),
942+ ),
943+ (
944+ 22050,
945+ 8,
946+ 15,
947+ 0,
948+ 0,
949+ 0,
950+ 3,
951+ Some((
952+ 40,
953+ 37,
954+ 19,
955+ 1,
956+ &[
957+ 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
958+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
959+ ],
960+ &[
961+ 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
962+ ],
963+ &[23, 60],
964+ )),
965+ ),
966+ (44100, 1, 4, 1, 0, 3, 1, None),
967+ (
968+ 16000,
969+ 2,
970+ 2,
971+ 2,
972+ 0,
973+ 2,
974+ 4,
975+ Some((
976+ 14,
977+ 10,
978+ 5,
979+ 2,
980+ &[23, 25, 27, 29, 31, 33, 36, 39, 42, 46, 50],
981+ &[23, 27, 31, 36, 42, 50],
982+ &[23, 31, 50],
983+ )),
984+ ),
985+ (
986+ 44100,
987+ 10,
988+ 4,
989+ 3,
990+ 0,
991+ 3,
992+ 1,
993+ Some((
994+ 6,
995+ 5,
996+ 3,
997+ 2,
998+ &[20, 22, 24, 26, 28, 31],
999+ &[20, 22, 26, 31],
1000+ &[20, 22, 31],
1001+ )),
1002+ ),
1003+ (
1004+ 22050,
1005+ 8,
1006+ 12,
1007+ 0,
1008+ 0,
1009+ 3,
1010+ 7,
1011+ Some((
1012+ 40,
1013+ 33,
1014+ 17,
1015+ 4,
1016+ &[
1017+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
1018+ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61,
1019+ ],
1020+ &[
1021+ 27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 61,
1022+ ],
1023+ &[27, 34, 42, 50, 61],
1024+ )),
1025+ ),
1026+ (
1027+ 24000,
1028+ 9,
1029+ 5,
1030+ 1,
1031+ 0,
1032+ 2,
1033+ 2,
1034+ Some((
1035+ 12,
1036+ 10,
1037+ 5,
1038+ 2,
1039+ &[23, 24, 25, 27, 29, 31, 33, 35, 37, 39, 42],
1040+ &[23, 25, 29, 33, 37, 42],
1041+ &[23, 29, 42],
1042+ )),
1043+ ),
1044+ (
1045+ 24000,
1046+ 8,
1047+ 10,
1048+ 3,
1049+ 0,
1050+ 0,
1051+ 1,
1052+ Some((
1053+ 12,
1054+ 11,
1055+ 6,
1056+ 1,
1057+ &[22, 24, 26, 28, 31, 34, 37, 40, 43, 47, 51, 55],
1058+ &[22, 24, 28, 34, 40, 47, 55],
1059+ &[22, 55],
1060+ )),
1061+ ),
1062+ (
1063+ 48000,
1064+ 13,
1065+ 7,
1066+ 0,
1067+ 0,
1068+ 1,
1069+ 5,
1070+ Some((
1071+ 14,
1072+ 9,
1073+ 5,
1074+ 1,
1075+ &[29, 30, 31, 32, 33, 34, 35, 36, 37, 38],
1076+ &[29, 30, 32, 34, 36, 38],
1077+ &[29, 38],
1078+ )),
1079+ ),
1080+ (64000, 13, 5, 2, 1, 3, 7, None),
1081+ (24000, 0, 13, 2, 0, 2, 7, None),
1082+ (
1083+ 64000,
1084+ 2,
1085+ 14,
1086+ 3,
1087+ 0,
1088+ 1,
1089+ 4,
1090+ Some((8, 4, 2, 1, &[13, 14, 15, 16, 18], &[13, 15, 18], &[13, 18])),
1091+ ),
1092+ (
1093+ 88200,
1094+ 14,
1095+ 10,
1096+ 2,
1097+ 1,
1098+ 0,
1099+ 3,
1100+ Some((
1101+ 8,
1102+ 5,
1103+ 3,
1104+ 1,
1105+ &[33, 35, 37, 40, 43, 46],
1106+ &[33, 35, 40, 46],
1107+ &[33, 46],
1108+ )),
1109+ ),
1110+ (88200, 5, 12, 2, 1, 1, 4, None),
1111+ (64000, 3, 13, 0, 0, 0, 2, None),
1112+ (
1113+ 16000,
1114+ 4,
1115+ 10,
1116+ 2,
1117+ 1,
1118+ 3,
1119+ 7,
1120+ Some((
1121+ 14,
1122+ 7,
1123+ 4,
1124+ 3,
1125+ &[32, 34, 37, 40, 44, 48, 53, 58],
1126+ &[32, 34, 40, 48, 58],
1127+ &[32, 34, 40, 58],
1128+ )),
1129+ ),
1130+ (
1131+ 24000,
1132+ 2,
1133+ 9,
1134+ 1,
1135+ 1,
1136+ 0,
1137+ 5,
1138+ Some((
1139+ 20,
1140+ 15,
1141+ 8,
1142+ 1,
1143+ &[
1144+ 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 35, 38, 41, 44, 48, 52,
1145+ ],
1146+ &[19, 20, 22, 24, 28, 32, 38, 44, 52],
1147+ &[19, 52],
1148+ )),
1149+ ),
1150+ (
1151+ 24000,
1152+ 12,
1153+ 8,
1154+ 2,
1155+ 1,
1156+ 2,
1157+ 7,
1158+ Some((10, 3, 2, 1, &[40, 43, 46, 49], &[40, 43, 49], &[40, 49])),
1159+ ),
1160+ (
1161+ 32000,
1162+ 6,
1163+ 2,
1164+ 0,
1165+ 1,
1166+ 0,
1167+ 4,
1168+ Some((
1169+ 10,
1170+ 6,
1171+ 3,
1172+ 1,
1173+ &[24, 26, 28, 30, 32, 34, 36],
1174+ &[24, 28, 32, 36],
1175+ &[24, 36],
1176+ )),
1177+ ),
1178+ (96000, 12, 4, 0, 1, 2, 2, None),
1179+ (88200, 9, 12, 3, 1, 0, 3, None),
1180+ (
1181+ 44100,
1182+ 2,
1183+ 3,
1184+ 0,
1185+ 1,
1186+ 1,
1187+ 2,
1188+ Some((
1189+ 10,
1190+ 8,
1191+ 4,
1192+ 1,
1193+ &[13, 15, 17, 19, 21, 23, 25, 27, 29],
1194+ &[13, 17, 21, 25, 29],
1195+ &[13, 29],
1196+ )),
1197+ ),
1198+ (
1199+ 24000,
1200+ 4,
1201+ 2,
1202+ 2,
1203+ 0,
1204+ 0,
1205+ 4,
1206+ Some((
1207+ 12,
1208+ 8,
1209+ 4,
1210+ 1,
1211+ &[20, 22, 24, 26, 28, 30, 32, 34, 36],
1212+ &[20, 24, 28, 32, 36],
1213+ &[20, 36],
1214+ )),
1215+ ),
1216+ (44100, 14, 1, 2, 1, 3, 7, None),
1217+ (
1218+ 16000,
1219+ 14,
1220+ 13,
1221+ 0,
1222+ 0,
1223+ 3,
1224+ 5,
1225+ Some((
1226+ 34,
1227+ 29,
1228+ 15,
1229+ 3,
1230+ &[
1231+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
1232+ 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
1233+ ],
1234+ &[
1235+ 35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
1236+ ],
1237+ &[35, 44, 54, 64],
1238+ )),
1239+ ),
1240+ (
1241+ 24000,
1242+ 5,
1243+ 4,
1244+ 1,
1245+ 0,
1246+ 1,
1247+ 4,
1248+ Some((
1249+ 14,
1250+ 10,
1251+ 5,
1252+ 1,
1253+ &[21, 22, 23, 24, 26, 28, 30, 32, 34, 37, 40],
1254+ &[21, 23, 26, 30, 34, 40],
1255+ &[21, 40],
1256+ )),
1257+ ),
1258+ (
1259+ 32000,
1260+ 12,
1261+ 2,
1262+ 1,
1263+ 0,
1264+ 3,
1265+ 2,
1266+ Some((6, 4, 2, 1, &[28, 30, 32, 34, 36], &[28, 32, 36], &[28, 36])),
1267+ ),
1268+ (
1269+ 96000,
1270+ 4,
1271+ 1,
1272+ 3,
1273+ 1,
1274+ 3,
1275+ 1,
1276+ Some((
1277+ 6,
1278+ 5,
1279+ 3,
1280+ 2,
1281+ &[10, 11, 12, 13, 14, 15],
1282+ &[10, 11, 13, 15],
1283+ &[10, 11, 15],
1284+ )),
1285+ ),
1286+ (
1287+ 64000,
1288+ 5,
1289+ 14,
1290+ 0,
1291+ 0,
1292+ 1,
1293+ 4,
1294+ Some((
1295+ 12,
1296+ 8,
1297+ 4,
1298+ 1,
1299+ &[16, 17, 18, 19, 20, 21, 22, 23, 24],
1300+ &[16, 18, 20, 22, 24],
1301+ &[16, 24],
1302+ )),
1303+ ),
1304+ (
1305+ 24000,
1306+ 13,
1307+ 8,
1308+ 2,
1309+ 0,
1310+ 1,
1311+ 0,
1312+ Some((
1313+ 8,
1314+ 8,
1315+ 4,
1316+ 1,
1317+ &[27, 29, 31, 33, 36, 39, 42, 45, 49],
1318+ &[27, 31, 36, 42, 49],
1319+ &[27, 49],
1320+ )),
1321+ ),
1322+ (
1323+ 96000,
1324+ 6,
1325+ 2,
1326+ 2,
1327+ 1,
1328+ 0,
1329+ 3,
1330+ Some((6, 3, 2, 1, &[14, 15, 16, 17], &[14, 15, 17], &[14, 17])),
1331+ ),
1332+ (
1333+ 88200,
1334+ 7,
1335+ 6,
1336+ 3,
1337+ 0,
1338+ 3,
1339+ 4,
1340+ Some((
1341+ 10,
1342+ 6,
1343+ 3,
1344+ 3,
1345+ &[16, 18, 20, 22, 24, 26, 29],
1346+ &[16, 20, 24, 29],
1347+ &[16, 20, 24, 29],
1348+ )),
1349+ ),
1350+ (88200, 2, 14, 1, 0, 0, 5, None),
1351+ (
1352+ 96000,
1353+ 6,
1354+ 3,
1355+ 3,
1356+ 0,
1357+ 3,
1358+ 1,
1359+ Some((
1360+ 6,
1361+ 5,
1362+ 3,
1363+ 2,
1364+ &[12, 13, 14, 15, 17, 19],
1365+ &[12, 13, 15, 19],
1366+ &[12, 13, 19],
1367+ )),
1368+ ),
1369+ (32000, 0, 3, 1, 1, 2, 6, None),
1370+ (
1371+ 48000,
1372+ 14,
1373+ 5,
1374+ 1,
1375+ 0,
1376+ 2,
1377+ 0,
1378+ Some((2, 2, 1, 1, &[27, 29, 32], &[27, 32], &[27, 32])),
1379+ ),
1380+ (64000, 3, 8, 1, 1, 3, 5, None),
1381+ (
1382+ 22050,
1383+ 13,
1384+ 0,
1385+ 3,
1386+ 0,
1387+ 2,
1388+ 0,
1389+ Some((4, 4, 2, 1, &[26, 28, 30, 32, 35], &[26, 30, 35], &[26, 35])),
1390+ ),
1391+ (
1392+ 44100,
1393+ 0,
1394+ 8,
1395+ 0,
1396+ 1,
1397+ 2,
1398+ 1,
1399+ Some((
1400+ 18,
1401+ 17,
1402+ 9,
1403+ 5,
1404+ &[
1405+ 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43,
1406+ ],
1407+ &[9, 11, 15, 19, 23, 27, 31, 35, 39, 43],
1408+ &[9, 11, 19, 27, 35, 43],
1409+ )),
1410+ ),
1411+ (
1412+ 48000,
1413+ 9,
1414+ 14,
1415+ 3,
1416+ 1,
1417+ 2,
1418+ 7,
1419+ Some((8, 1, 1, 1, &[31, 34], &[31, 34], &[31, 34])),
1420+ ),
1421+ (88200, 13, 6, 1, 1, 0, 7, None),
1422+ (88200, 2, 3, 3, 1, 3, 6, None),
1423+ (
1424+ 64000,
1425+ 0,
1426+ 0,
1427+ 0,
1428+ 0,
1429+ 0,
1430+ 1,
1431+ Some((
1432+ 14,
1433+ 13,
1434+ 7,
1435+ 1,
1436+ &[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
1437+ &[7, 8, 10, 12, 14, 16, 18, 20],
1438+ &[7, 20],
1439+ )),
1440+ ),
1441+ (44100, 0, 5, 1, 0, 1, 4, None),
1442+ (48000, 0, 13, 2, 1, 2, 3, None),
1443+ (
1444+ 44100,
1445+ 14,
1446+ 6,
1447+ 1,
1448+ 1,
1449+ 3,
1450+ 2,
1451+ Some((4, 2, 1, 1, &[32, 34, 37], &[32, 37], &[32, 37])),
1452+ ),
1453+ (96000, 2, 10, 0, 0, 1, 0, None),
1454+ (88200, 3, 11, 3, 1, 1, 3, None),
1455+ (
1456+ 64000,
1457+ 13,
1458+ 11,
1459+ 0,
1460+ 1,
1461+ 2,
1462+ 3,
1463+ Some((
1464+ 16,
1465+ 13,
1466+ 7,
1467+ 2,
1468+ &[28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54],
1469+ &[28, 30, 34, 38, 42, 46, 50, 54],
1470+ &[28, 38, 54],
1471+ )),
1472+ ),
1473+ (64000, 14, 0, 3, 1, 1, 1, None),
1474+ (
1475+ 24000,
1476+ 11,
1477+ 13,
1478+ 2,
1479+ 0,
1480+ 1,
1481+ 0,
1482+ Some((
1483+ 14,
1484+ 14,
1485+ 7,
1486+ 1,
1487+ &[23, 24, 26, 28, 30, 32, 34, 37, 40, 43, 46, 50, 54, 59, 64],
1488+ &[23, 26, 30, 34, 40, 46, 54, 64],
1489+ &[23, 64],
1490+ )),
1491+ ),
1492+ (
1493+ 32000,
1494+ 11,
1495+ 8,
1496+ 0,
1497+ 1,
1498+ 1,
1499+ 1,
1500+ Some((
1501+ 14,
1502+ 13,
1503+ 7,
1504+ 1,
1505+ &[24, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49],
1506+ &[24, 25, 29, 33, 37, 41, 45, 49],
1507+ &[24, 49],
1508+ )),
1509+ ),
1510+ (
1511+ 96000,
1512+ 11,
1513+ 6,
1514+ 0,
1515+ 0,
1516+ 2,
1517+ 2,
1518+ Some((
1519+ 8,
1520+ 6,
1521+ 3,
1522+ 1,
1523+ &[20, 21, 22, 23, 24, 25, 27],
1524+ &[20, 22, 24, 27],
1525+ &[20, 27],
1526+ )),
1527+ ),
1528+ (44100, 0, 14, 2, 1, 1, 5, None),
1529+ (
1530+ 32000,
1531+ 6,
1532+ 2,
1533+ 3,
1534+ 0,
1535+ 2,
1536+ 2,
1537+ Some((
1538+ 8,
1539+ 6,
1540+ 3,
1541+ 2,
1542+ &[21, 23, 25, 27, 30, 33, 36],
1543+ &[21, 25, 30, 36],
1544+ &[21, 25, 36],
1545+ )),
1546+ ),
1547+ (
1548+ 32000,
1549+ 3,
1550+ 3,
1551+ 3,
1552+ 0,
1553+ 3,
1554+ 1,
1555+ Some((
1556+ 10,
1557+ 9,
1558+ 5,
1559+ 4,
1560+ &[16, 17, 19, 21, 23, 25, 27, 30, 34, 38],
1561+ &[16, 17, 21, 25, 30, 38],
1562+ &[16, 17, 21, 25, 38],
1563+ )),
1564+ ),
1565+ (
1566+ 44100,
1567+ 14,
1568+ 12,
1569+ 0,
1570+ 1,
1571+ 1,
1572+ 6,
1573+ Some((
1574+ 16,
1575+ 10,
1576+ 5,
1577+ 1,
1578+ &[39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59],
1579+ &[39, 43, 47, 51, 55, 59],
1580+ &[39, 59],
1581+ )),
1582+ ),
1583+ (
1584+ 24000,
1585+ 11,
1586+ 8,
1587+ 0,
1588+ 1,
1589+ 1,
1590+ 6,
1591+ Some((
1592+ 14,
1593+ 8,
1594+ 4,
1595+ 1,
1596+ &[33, 35, 37, 39, 41, 43, 45, 47, 49],
1597+ &[33, 37, 41, 45, 49],
1598+ &[33, 49],
1599+ )),
1600+ ),
1601+ (
1602+ 22050,
1603+ 1,
1604+ 9,
1605+ 2,
1606+ 0,
1607+ 0,
1608+ 3,
1609+ Some((
1610+ 20,
1611+ 17,
1612+ 9,
1613+ 1,
1614+ &[
1615+ 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 52,
1616+ ],
1617+ &[16, 17, 19, 22, 26, 30, 34, 39, 45, 52],
1618+ &[16, 52],
1619+ )),
1620+ ),
1621+ (
1622+ 16000,
1623+ 3,
1624+ 8,
1625+ 0,
1626+ 1,
1627+ 2,
1628+ 2,
1629+ Some((
1630+ 18,
1631+ 16,
1632+ 8,
1633+ 3,
1634+ &[
1635+ 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 56,
1636+ ],
1637+ &[23, 27, 31, 35, 39, 43, 47, 51, 56],
1638+ &[23, 31, 43, 56],
1639+ )),
1640+ ),
1641+ (44100, 4, 1, 1, 0, 0, 3, None),
1642+ (
1643+ 64000,
1644+ 10,
1645+ 1,
1646+ 1,
1647+ 0,
1648+ 2,
1649+ 1,
1650+ Some((4, 3, 2, 1, &[18, 19, 20, 22], &[18, 19, 22], &[18, 22])),
1651+ ),
1652+ (
1653+ 24000,
1654+ 1,
1655+ 3,
1656+ 0,
1657+ 0,
1658+ 0,
1659+ 2,
1660+ Some((
1661+ 24,
1662+ 22,
1663+ 11,
1664+ 1,
1665+ &[
1666+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
1667+ 35, 36, 38,
1668+ ],
1669+ &[15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 38],
1670+ &[15, 38],
1671+ )),
1672+ ),
1673+ (24000, 11, 1, 3, 1, 2, 5, None),
1674+ (
1675+ 24000,
1676+ 5,
1677+ 7,
1678+ 1,
1679+ 0,
1680+ 2,
1681+ 7,
1682+ Some((
1683+ 18,
1684+ 11,
1685+ 6,
1686+ 2,
1687+ &[24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46],
1688+ &[24, 26, 30, 34, 38, 42, 46],
1689+ &[24, 34, 46],
1690+ )),
1691+ ),
1692+ (
1693+ 88200,
1694+ 14,
1695+ 10,
1696+ 0,
1697+ 1,
1698+ 3,
1699+ 4,
1700+ Some((
1701+ 10,
1702+ 6,
1703+ 3,
1704+ 1,
1705+ &[34, 36, 38, 40, 42, 44, 46],
1706+ &[34, 38, 42, 46],
1707+ &[34, 46],
1708+ )),
1709+ ),
1710+ (64000, 13, 12, 3, 1, 1, 6, None),
1711+ (
1712+ 96000,
1713+ 11,
1714+ 10,
1715+ 2,
1716+ 1,
1717+ 0,
1718+ 5,
1719+ Some((
1720+ 12,
1721+ 7,
1722+ 4,
1723+ 1,
1724+ &[25, 27, 29, 31, 33, 36, 40, 44],
1725+ &[25, 27, 31, 36, 44],
1726+ &[25, 44],
1727+ )),
1728+ ),
1729+ (
1730+ 44100,
1731+ 3,
1732+ 6,
1733+ 0,
1734+ 0,
1735+ 3,
1736+ 6,
1737+ Some((
1738+ 24,
1739+ 18,
1740+ 9,
1741+ 3,
1742+ &[
1743+ 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37,
1744+ ],
1745+ &[18, 20, 22, 24, 26, 28, 30, 32, 34, 37],
1746+ &[18, 24, 30, 37],
1747+ )),
1748+ ),
1749+ (88200, 12, 13, 1, 1, 0, 0, None),
1750+ (
1751+ 96000,
1752+ 12,
1753+ 7,
1754+ 1,
1755+ 0,
1756+ 2,
1757+ 2,
1758+ Some((
1759+ 8,
1760+ 6,
1761+ 3,
1762+ 1,
1763+ &[22, 23, 24, 25, 27, 29, 31],
1764+ &[22, 24, 27, 31],
1765+ &[22, 31],
1766+ )),
1767+ ),
1768+ (44100, 3, 4, 1, 1, 2, 5, None),
1769+ (
1770+ 88200,
1771+ 5,
1772+ 7,
1773+ 0,
1774+ 0,
1775+ 1,
1776+ 4,
1777+ Some((
1778+ 22,
1779+ 18,
1780+ 9,
1781+ 1,
1782+ &[
1783+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33,
1784+ ],
1785+ &[14, 16, 18, 20, 22, 24, 26, 28, 30, 33],
1786+ &[14, 33],
1787+ )),
1788+ ),
1789+ (32000, 0, 11, 1, 0, 1, 3, None),
1790+ (
1791+ 48000,
1792+ 4,
1793+ 8,
1794+ 2,
1795+ 0,
1796+ 0,
1797+ 6,
1798+ Some((
1799+ 18,
1800+ 12,
1801+ 6,
1802+ 1,
1803+ &[18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 41],
1804+ &[18, 20, 24, 28, 32, 36, 41],
1805+ &[18, 41],
1806+ )),
1807+ ),
1808+ (
1809+ 88200,
1810+ 14,
1811+ 10,
1812+ 3,
1813+ 0,
1814+ 3,
1815+ 5,
1816+ Some((6, 1, 1, 1, &[42, 46], &[42, 46], &[42, 46])),
1817+ ),
1818+ (
1819+ 16000,
1820+ 10,
1821+ 2,
1822+ 1,
1823+ 1,
1824+ 0,
1825+ 1,
1826+ Some((
1827+ 12,
1828+ 11,
1829+ 6,
1830+ 1,
1831+ &[27, 28, 30, 32, 34, 36, 38, 40, 42, 44, 47, 50],
1832+ &[27, 28, 32, 36, 40, 44, 50],
1833+ &[27, 50],
1834+ )),
1835+ ),
1836+ (
1837+ 32000,
1838+ 10,
1839+ 8,
1840+ 0,
1841+ 0,
1842+ 2,
1843+ 0,
1844+ Some((
1845+ 26,
1846+ 26,
1847+ 13,
1848+ 2,
1849+ &[
1850+ 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
1851+ 42, 43, 44, 45, 46, 47, 49,
1852+ ],
1853+ &[22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49],
1854+ &[22, 34, 49],
1855+ )),
1856+ ),
1857+ (64000, 6, 15, 1, 0, 0, 0, None),
1858+ (
1859+ 44100,
1860+ 1,
1861+ 8,
1862+ 0,
1863+ 1,
1864+ 1,
1865+ 3,
1866+ Some((
1867+ 16,
1868+ 13,
1869+ 7,
1870+ 1,
1871+ &[16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 43],
1872+ &[16, 18, 22, 26, 30, 34, 38, 43],
1873+ &[16, 43],
1874+ )),
1875+ ),
1876+ (
1877+ 96000,
1878+ 12,
1879+ 11,
1880+ 3,
1881+ 1,
1882+ 2,
1883+ 4,
1884+ Some((
1885+ 10,
1886+ 6,
1887+ 3,
1888+ 2,
1889+ &[28, 31, 34, 37, 40, 45, 50],
1890+ &[28, 34, 40, 50],
1891+ &[28, 34, 50],
1892+ )),
1893+ ),
1894+ (96000, 3, 0, 3, 0, 2, 0, None),
1895+ (
1896+ 48000,
1897+ 12,
1898+ 4,
1899+ 3,
1900+ 1,
1901+ 3,
1902+ 0,
1903+ Some((4, 4, 2, 1, &[22, 23, 25, 27, 29], &[22, 25, 29], &[22, 29])),
1904+ ),
1905+ (96000, 3, 11, 2, 1, 2, 2, None),
1906+ (
1907+ 44100,
1908+ 2,
1909+ 5,
1910+ 0,
1911+ 1,
1912+ 3,
1913+ 3,
1914+ Some((
1915+ 12,
1916+ 9,
1917+ 5,
1918+ 3,
1919+ &[16, 18, 20, 22, 24, 26, 28, 30, 32, 34],
1920+ &[16, 18, 22, 26, 30, 34],
1921+ &[16, 18, 26, 34],
1922+ )),
1923+ ),
1924+ (44100, 11, 1, 1, 0, 3, 4, None),
1925+ (88200, 6, 1, 2, 1, 0, 6, None),
1926+ (
1927+ 16000,
1928+ 2,
1929+ 5,
1930+ 2,
1931+ 1,
1932+ 2,
1933+ 3,
1934+ Some((
1935+ 14,
1936+ 11,
1937+ 6,
1938+ 3,
1939+ &[21, 23, 25, 27, 29, 31, 33, 36, 40, 44, 48, 53],
1940+ &[21, 23, 27, 31, 36, 44, 53],
1941+ &[21, 27, 36, 53],
1942+ )),
1943+ ),
1944+ (
1945+ 64000,
1946+ 5,
1947+ 1,
1948+ 3,
1949+ 1,
1950+ 0,
1951+ 3,
1952+ Some((6, 3, 2, 1, &[16, 18, 20, 22], &[16, 18, 22], &[16, 22])),
1953+ ),
1954+ (
1955+ 24000,
1956+ 2,
1957+ 0,
1958+ 0,
1959+ 1,
1960+ 3,
1961+ 5,
1962+ Some((
1963+ 10,
1964+ 5,
1965+ 3,
1966+ 2,
1967+ &[22, 24, 26, 28, 30, 32],
1968+ &[22, 24, 28, 32],
1969+ &[22, 24, 32],
1970+ )),
1971+ ),
1972+ (
1973+ 64000,
1974+ 8,
1975+ 8,
1976+ 2,
1977+ 0,
1978+ 2,
1979+ 3,
1980+ Some((
1981+ 14,
1982+ 11,
1983+ 6,
1984+ 2,
1985+ &[18, 19, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41],
1986+ &[18, 19, 22, 26, 30, 35, 41],
1987+ &[18, 26, 41],
1988+ )),
1989+ ),
1990+ (
1991+ 16000,
1992+ 12,
1993+ 12,
1994+ 0,
1995+ 0,
1996+ 2,
1997+ 7,
1998+ Some((
1999+ 34,
2000+ 27,
crates/ec-aac/src/sbr_bands/vectors/part1.rsadded+1695 -0
@@ -0,0 +1,1695 @@
1+//! Reference vectors for the `freq_tables` tests, second half of the 500 (test-only data).
2+
3+use super::Vector;
4+
5+pub(super) static PART: &[Vector] = &[
6+ (
7+ 16000,
8+ 5,
9+ 5,
10+ 1,
11+ 1,
12+ 2,
13+ 2,
14+ Some((
15+ 16,
16+ 14,
17+ 7,
18+ 2,
19+ &[23, 24, 25, 27, 29, 31, 33, 35, 37, 39, 42, 44, 47, 50, 53],
20+ &[23, 25, 29, 33, 37, 42, 47, 53],
21+ &[23, 33, 53],
22+ )),
23+ ),
24+ (
25+ 16000,
26+ 10,
27+ 7,
28+ 2,
29+ 1,
30+ 2,
31+ 4,
32+ Some((
33+ 10,
34+ 6,
35+ 3,
36+ 1,
37+ &[35, 38, 41, 44, 47, 51, 55],
38+ &[35, 41, 47, 55],
39+ &[35, 55],
40+ )),
41+ ),
42+ (48000, 2, 12, 2, 1, 0, 4, None),
43+ (88200, 0, 6, 1, 0, 1, 0, None),
44+ (
45+ 22050,
46+ 3,
47+ 4,
48+ 1,
49+ 0,
50+ 1,
51+ 7,
52+ Some((
53+ 18,
54+ 11,
55+ 6,
56+ 1,
57+ &[22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
58+ &[22, 23, 26, 30, 34, 38, 42],
59+ &[22, 42],
60+ )),
61+ ),
62+ (
63+ 64000,
64+ 3,
65+ 2,
66+ 0,
67+ 0,
68+ 2,
69+ 7,
70+ Some((
71+ 14,
72+ 7,
73+ 4,
74+ 1,
75+ &[17, 18, 19, 20, 21, 22, 23, 24],
76+ &[17, 18, 20, 22, 24],
77+ &[17, 24],
78+ )),
79+ ),
80+ (
81+ 16000,
82+ 4,
83+ 2,
84+ 0,
85+ 1,
86+ 1,
87+ 5,
88+ Some((
89+ 16,
90+ 11,
91+ 6,
92+ 1,
93+ &[28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50],
94+ &[28, 30, 34, 38, 42, 46, 50],
95+ &[28, 50],
96+ )),
97+ ),
98+ (
99+ 64000,
100+ 6,
101+ 2,
102+ 3,
103+ 0,
104+ 2,
105+ 2,
106+ Some((
107+ 8,
108+ 6,
109+ 3,
110+ 1,
111+ &[15, 16, 17, 18, 20, 22, 24],
112+ &[15, 17, 20, 24],
113+ &[15, 24],
114+ )),
115+ ),
116+ (
117+ 32000,
118+ 11,
119+ 4,
120+ 1,
121+ 1,
122+ 2,
123+ 6,
124+ Some((10, 4, 2, 1, &[32, 34, 36, 38, 40], &[32, 36, 40], &[32, 40])),
125+ ),
126+ (88200, 2, 5, 2, 0, 2, 3, None),
127+ (64000, 1, 7, 2, 1, 1, 2, None),
128+ (
129+ 24000,
130+ 4,
131+ 5,
132+ 3,
133+ 0,
134+ 2,
135+ 2,
136+ Some((
137+ 12,
138+ 10,
139+ 5,
140+ 2,
141+ &[19, 21, 23, 25, 27, 29, 32, 34, 36, 39, 42],
142+ &[19, 23, 27, 32, 36, 42],
143+ &[19, 27, 42],
144+ )),
145+ ),
146+ (
147+ 24000,
148+ 10,
149+ 5,
150+ 3,
151+ 0,
152+ 1,
153+ 4,
154+ Some((8, 4, 2, 1, &[30, 33, 36, 39, 42], &[30, 36, 42], &[30, 42])),
155+ ),
156+ (
157+ 16000,
158+ 6,
159+ 1,
160+ 3,
161+ 0,
162+ 0,
163+ 4,
164+ Some((
165+ 10,
166+ 6,
167+ 3,
168+ 1,
169+ &[30, 33, 36, 39, 42, 45, 49],
170+ &[30, 36, 42, 49],
171+ &[30, 49],
172+ )),
173+ ),
174+ (88200, 8, 15, 1, 0, 2, 3, None),
175+ (
176+ 24000,
177+ 2,
178+ 3,
179+ 1,
180+ 0,
181+ 2,
182+ 7,
183+ Some((
184+ 18,
185+ 11,
186+ 6,
187+ 2,
188+ &[21, 22, 23, 24, 26, 28, 29, 30, 32, 34, 36, 38],
189+ &[21, 22, 24, 28, 30, 34, 38],
190+ &[21, 28, 38],
191+ )),
192+ ),
193+ (48000, 1, 15, 1, 1, 1, 0, None),
194+ (48000, 6, 11, 0, 1, 2, 5, None),
195+ (
196+ 48000,
197+ 0,
198+ 0,
199+ 0,
200+ 0,
201+ 0,
202+ 5,
203+ Some((
204+ 14,
205+ 9,
206+ 5,
207+ 1,
208+ &[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
209+ &[12, 13, 15, 17, 19, 21],
210+ &[12, 21],
211+ )),
212+ ),
213+ (64000, 12, 0, 3, 0, 1, 5, None),
214+ (88200, 4, 12, 0, 0, 0, 5, None),
215+ (22050, 8, 0, 3, 0, 3, 6, None),
216+ (24000, 0, 12, 0, 1, 2, 4, None),
217+ (
218+ 16000,
219+ 4,
220+ 15,
221+ 0,
222+ 0,
223+ 0,
224+ 5,
225+ Some((
226+ 40,
227+ 35,
228+ 18,
229+ 1,
230+ &[
231+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
232+ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
233+ ],
234+ &[
235+ 25, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
236+ ],
237+ &[25, 60],
238+ )),
239+ ),
240+ (
241+ 96000,
242+ 14,
243+ 10,
244+ 2,
245+ 1,
246+ 2,
247+ 1,
248+ Some((
249+ 8,
250+ 7,
251+ 4,
252+ 1,
253+ &[28, 30, 32, 34, 36, 38, 41, 44],
254+ &[28, 30, 34, 38, 44],
255+ &[28, 44],
256+ )),
257+ ),
258+ (44100, 15, 10, 3, 0, 0, 6, None),
259+ (
260+ 22050,
261+ 4,
262+ 15,
263+ 0,
264+ 0,
265+ 0,
266+ 3,
267+ Some((
268+ 32,
269+ 29,
270+ 15,
271+ 1,
272+ &[
273+ 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
274+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
275+ ],
276+ &[
277+ 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48,
278+ ],
279+ &[19, 48],
280+ )),
281+ ),
282+ (
283+ 48000,
284+ 3,
285+ 8,
286+ 2,
287+ 1,
288+ 3,
289+ 3,
290+ Some((
291+ 16,
292+ 13,
293+ 7,
294+ 5,
295+ &[14, 15, 16, 17, 18, 19, 20, 22, 24, 27, 30, 33, 37, 41],
296+ &[14, 15, 17, 19, 22, 27, 33, 41],
297+ &[14, 15, 17, 19, 27, 41],
298+ )),
299+ ),
300+ (48000, 14, 13, 2, 1, 0, 6, None),
301+ (
302+ 96000,
303+ 14,
304+ 14,
305+ 0,
306+ 1,
307+ 1,
308+ 5,
309+ Some((
310+ 14,
311+ 9,
312+ 5,
313+ 1,
314+ &[36, 38, 40, 42, 44, 46, 48, 50, 52, 54],
315+ &[36, 38, 42, 46, 50, 54],
316+ &[36, 54],
317+ )),
318+ ),
319+ (
320+ 24000,
321+ 13,
322+ 12,
323+ 1,
324+ 0,
325+ 2,
326+ 0,
327+ Some((
328+ 14,
329+ 14,
330+ 7,
331+ 2,
332+ &[27, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48, 51, 54, 57, 61],
333+ &[27, 30, 34, 38, 42, 48, 54, 61],
334+ &[27, 38, 61],
335+ )),
336+ ),
337+ (
338+ 22050,
339+ 10,
340+ 4,
341+ 1,
342+ 1,
343+ 3,
344+ 5,
345+ Some((
346+ 12,
347+ 7,
348+ 4,
349+ 2,
350+ &[28, 30, 32, 34, 36, 38, 40, 42],
351+ &[28, 30, 34, 38, 42],
352+ &[28, 34, 42],
353+ )),
354+ ),
355+ (
356+ 16000,
357+ 5,
358+ 9,
359+ 3,
360+ 1,
361+ 3,
362+ 6,
363+ Some((
364+ 10,
365+ 4,
366+ 2,
367+ 2,
368+ &[35, 38, 42, 49, 57],
369+ &[35, 42, 57],
370+ &[35, 42, 57],
371+ )),
372+ ),
373+ (
374+ 16000,
375+ 12,
376+ 8,
377+ 0,
378+ 0,
379+ 3,
380+ 1,
381+ Some((
382+ 28,
383+ 27,
384+ 14,
385+ 3,
386+ &[
387+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
388+ 49, 50, 51, 52, 53, 54, 55, 56,
389+ ],
390+ &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56],
391+ &[29, 36, 46, 56],
392+ )),
393+ ),
394+ (
395+ 88200,
396+ 2,
397+ 8,
398+ 0,
399+ 0,
400+ 0,
401+ 3,
402+ Some((
403+ 30,
404+ 27,
405+ 14,
406+ 1,
407+ &[
408+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
409+ 30, 31, 32, 33, 34, 35, 36, 37,
410+ ],
411+ &[10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37],
412+ &[10, 37],
413+ )),
414+ ),
415+ (
416+ 16000,
417+ 14,
418+ 5,
419+ 1,
420+ 1,
421+ 1,
422+ 7,
423+ Some((10, 3, 2, 1, &[44, 47, 50, 53], &[44, 47, 53], &[44, 53])),
424+ ),
425+ (
426+ 96000,
427+ 11,
428+ 6,
429+ 0,
430+ 0,
431+ 1,
432+ 0,
433+ Some((
434+ 8,
435+ 8,
436+ 4,
437+ 1,
438+ &[18, 19, 20, 21, 22, 23, 24, 25, 27],
439+ &[18, 20, 22, 24, 27],
440+ &[18, 27],
441+ )),
442+ ),
443+ (
444+ 24000,
445+ 15,
446+ 12,
447+ 3,
448+ 1,
449+ 3,
450+ 5,
451+ Some((8, 3, 2, 1, &[48, 52, 56, 61], &[48, 52, 61], &[48, 61])),
452+ ),
453+ (
454+ 44100,
455+ 6,
456+ 6,
457+ 1,
458+ 1,
459+ 0,
460+ 6,
461+ Some((
462+ 14,
463+ 8,
464+ 4,
465+ 1,
466+ &[21, 22, 23, 24, 26, 28, 30, 33, 37],
467+ &[21, 23, 26, 30, 37],
468+ &[21, 37],
469+ )),
470+ ),
471+ (
472+ 64000,
473+ 7,
474+ 8,
475+ 2,
476+ 1,
477+ 2,
478+ 5,
479+ Some((
480+ 14,
481+ 9,
482+ 5,
483+ 2,
484+ &[19, 20, 22, 24, 26, 28, 31, 34, 37, 41],
485+ &[19, 20, 24, 28, 34, 41],
486+ &[19, 24, 41],
487+ )),
488+ ),
489+ (
490+ 48000,
491+ 13,
492+ 12,
493+ 3,
494+ 0,
495+ 3,
496+ 6,
497+ Some((
498+ 10,
499+ 4,
500+ 2,
501+ 2,
502+ &[40, 44, 48, 53, 59],
503+ &[40, 48, 59],
504+ &[40, 48, 59],
505+ )),
506+ ),
507+ (
508+ 64000,
509+ 12,
510+ 7,
511+ 2,
512+ 0,
513+ 0,
514+ 1,
515+ Some((
516+ 8,
517+ 7,
518+ 4,
519+ 1,
520+ &[22, 24, 26, 28, 30, 32, 34, 37],
521+ &[22, 24, 28, 32, 37],
522+ &[22, 37],
523+ )),
524+ ),
525+ (
526+ 16000,
527+ 2,
528+ 10,
529+ 1,
530+ 1,
531+ 3,
532+ 2,
533+ Some((
534+ 18,
535+ 16,
536+ 8,
537+ 5,
538+ &[
539+ 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 49, 53, 58,
540+ ],
541+ &[20, 22, 24, 28, 32, 36, 42, 49, 58],
542+ &[20, 22, 24, 32, 42, 58],
543+ )),
544+ ),
545+ (
546+ 48000,
547+ 6,
548+ 14,
549+ 1,
550+ 1,
551+ 1,
552+ 6,
553+ Some((
554+ 12,
555+ 6,
556+ 3,
557+ 1,
558+ &[20, 21, 22, 23, 24, 26, 28],
559+ &[20, 22, 24, 28],
560+ &[20, 28],
561+ )),
562+ ),
563+ (
564+ 16000,
565+ 7,
566+ 3,
567+ 2,
568+ 0,
569+ 3,
570+ 0,
571+ Some((
572+ 12,
573+ 12,
574+ 6,
575+ 3,
576+ &[23, 24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 51],
577+ &[23, 26, 30, 34, 39, 45, 51],
578+ &[23, 30, 39, 51],
579+ )),
580+ ),
581+ (
582+ 88200,
583+ 11,
584+ 14,
585+ 2,
586+ 1,
587+ 0,
588+ 0,
589+ Some((
590+ 10,
591+ 10,
592+ 5,
593+ 1,
594+ &[18, 19, 20, 21, 23, 25, 27, 29, 31, 33, 36],
595+ &[18, 20, 23, 27, 31, 36],
596+ &[18, 36],
597+ )),
598+ ),
599+ (
600+ 16000,
601+ 13,
602+ 6,
603+ 3,
604+ 0,
605+ 1,
606+ 2,
607+ Some((
608+ 8,
609+ 6,
610+ 3,
611+ 1,
612+ &[34, 37, 40, 43, 46, 50, 54],
613+ &[34, 40, 46, 54],
614+ &[34, 54],
615+ )),
616+ ),
617+ (
618+ 32000,
619+ 5,
620+ 2,
621+ 0,
622+ 1,
623+ 3,
624+ 2,
625+ Some((
626+ 10,
627+ 8,
628+ 4,
629+ 3,
630+ &[20, 22, 24, 26, 28, 30, 32, 34, 36],
631+ &[20, 24, 28, 32, 36],
632+ &[20, 24, 28, 36],
633+ )),
634+ ),
635+ (
636+ 22050,
637+ 8,
638+ 6,
639+ 2,
640+ 0,
641+ 2,
642+ 7,
643+ Some((
644+ 12,
645+ 5,
646+ 3,
647+ 1,
648+ &[32, 34, 37, 40, 43, 46],
649+ &[32, 34, 40, 46],
650+ &[32, 46],
651+ )),
652+ ),
653+ (
654+ 32000,
655+ 8,
656+ 5,
657+ 0,
658+ 1,
659+ 0,
660+ 7,
661+ Some((
662+ 12,
663+ 5,
664+ 3,
665+ 1,
666+ &[32, 34, 36, 38, 40, 42],
667+ &[32, 34, 38, 42],
668+ &[32, 42],
669+ )),
670+ ),
671+ (
672+ 48000,
673+ 3,
674+ 1,
675+ 0,
676+ 0,
677+ 3,
678+ 7,
679+ Some((
680+ 12,
681+ 5,
682+ 3,
683+ 1,
684+ &[18, 19, 20, 21, 22, 23],
685+ &[18, 19, 21, 23],
686+ &[18, 23],
687+ )),
688+ ),
689+ (
690+ 22050,
691+ 0,
692+ 7,
693+ 3,
694+ 0,
695+ 2,
696+ 1,
697+ Some((
698+ 16,
699+ 15,
700+ 8,
701+ 4,
702+ &[
703+ 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 31, 34, 37, 40, 44, 48,
704+ ],
705+ &[13, 14, 16, 20, 24, 28, 34, 40, 48],
706+ &[13, 16, 24, 34, 48],
707+ )),
708+ ),
709+ (
710+ 32000,
711+ 10,
712+ 9,
713+ 0,
714+ 0,
715+ 3,
716+ 7,
717+ Some((
718+ 30,
719+ 23,
720+ 12,
721+ 3,
722+ &[
723+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
724+ 49, 50, 51, 52,
725+ ],
726+ &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52],
727+ &[29, 36, 44, 52],
728+ )),
729+ ),
730+ (
731+ 32000,
732+ 3,
733+ 0,
734+ 2,
735+ 0,
736+ 3,
737+ 1,
738+ Some((
739+ 10,
740+ 9,
741+ 5,
742+ 3,
743+ &[16, 17, 18, 19, 21, 23, 25, 27, 29, 32],
744+ &[16, 17, 19, 23, 27, 32],
745+ &[16, 17, 23, 32],
746+ )),
747+ ),
748+ (
749+ 48000,
750+ 3,
751+ 3,
752+ 0,
753+ 1,
754+ 2,
755+ 7,
756+ Some((8, 1, 1, 1, &[25, 27], &[25, 27], &[25, 27])),
757+ ),
758+ (
759+ 22050,
760+ 13,
761+ 2,
762+ 2,
763+ 0,
764+ 0,
765+ 2,
766+ Some((6, 4, 2, 1, &[29, 31, 33, 35, 38], &[29, 33, 38], &[29, 38])),
767+ ),
768+ (
769+ 96000,
770+ 2,
771+ 6,
772+ 0,
773+ 0,
774+ 0,
775+ 3,
776+ Some((
777+ 20,
778+ 17,
779+ 9,
780+ 1,
781+ &[
782+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
783+ ],
784+ &[10, 11, 13, 15, 17, 19, 21, 23, 25, 27],
785+ &[10, 27],
786+ )),
787+ ),
788+ (
789+ 64000,
790+ 14,
791+ 9,
792+ 1,
793+ 0,
794+ 3,
795+ 3,
796+ Some((
797+ 10,
798+ 7,
799+ 4,
800+ 2,
801+ &[30, 32, 34, 36, 38, 40, 42, 45],
802+ &[30, 32, 36, 40, 45],
803+ &[30, 36, 45],
804+ )),
805+ ),
806+ (
807+ 16000,
808+ 13,
809+ 14,
810+ 0,
811+ 1,
812+ 1,
813+ 6,
814+ Some((
815+ 14,
816+ 8,
817+ 4,
818+ 1,
819+ &[41, 43, 45, 47, 49, 51, 53, 55, 58],
820+ &[41, 45, 49, 53, 58],
821+ &[41, 58],
822+ )),
823+ ),
824+ (
825+ 96000,
826+ 9,
827+ 5,
828+ 3,
829+ 1,
830+ 2,
831+ 5,
832+ Some((6, 1, 1, 1, &[22, 24], &[22, 24], &[22, 24])),
833+ ),
834+ (
835+ 16000,
836+ 5,
837+ 15,
838+ 1,
839+ 0,
840+ 2,
841+ 7,
842+ Some((
843+ 20,
844+ 13,
845+ 7,
846+ 2,
847+ &[31, 33, 35, 37, 39, 42, 44, 46, 48, 51, 54, 57, 60, 63],
848+ &[31, 33, 37, 42, 46, 51, 57, 63],
849+ &[31, 42, 63],
850+ )),
851+ ),
852+ (
853+ 24000,
854+ 12,
855+ 4,
856+ 2,
857+ 0,
858+ 1,
859+ 3,
860+ Some((6, 3, 2, 1, &[31, 34, 37, 40], &[31, 34, 40], &[31, 40])),
861+ ),
862+ (
863+ 32000,
864+ 14,
865+ 10,
866+ 3,
867+ 0,
868+ 3,
869+ 2,
870+ Some((
871+ 8,
872+ 6,
873+ 3,
874+ 2,
875+ &[34, 37, 40, 43, 47, 51, 55],
876+ &[34, 40, 47, 55],
877+ &[34, 40, 55],
878+ )),
879+ ),
880+ (
881+ 32000,
882+ 11,
883+ 2,
884+ 3,
885+ 0,
886+ 3,
887+ 2,
888+ Some((6, 4, 2, 1, &[27, 29, 31, 33, 36], &[27, 31, 36], &[27, 36])),
889+ ),
890+ (
891+ 32000,
892+ 10,
893+ 1,
894+ 2,
895+ 0,
896+ 1,
897+ 4,
898+ Some((6, 2, 1, 1, &[29, 31, 34], &[29, 34], &[29, 34])),
899+ ),
900+ (
901+ 16000,
902+ 5,
903+ 15,
904+ 1,
905+ 1,
906+ 1,
907+ 3,
908+ Some((
909+ 18,
910+ 15,
911+ 8,
912+ 1,
913+ &[
914+ 24, 25, 27, 29, 31, 33, 35, 37, 39, 42, 45, 48, 51, 55, 59, 63,
915+ ],
916+ &[24, 25, 29, 33, 37, 42, 48, 55, 63],
917+ &[24, 63],
918+ )),
919+ ),
920+ (
921+ 22050,
922+ 10,
923+ 3,
924+ 1,
925+ 0,
926+ 1,
927+ 7,
928+ Some((10, 3, 2, 1, &[33, 35, 37, 40], &[33, 35, 40], &[33, 40])),
929+ ),
930+ (
931+ 22050,
932+ 10,
933+ 4,
934+ 0,
935+ 1,
936+ 2,
937+ 2,
938+ Some((
939+ 10,
940+ 8,
941+ 4,
942+ 1,
943+ &[26, 28, 30, 32, 34, 36, 38, 40, 42],
944+ &[26, 30, 34, 38, 42],
945+ &[26, 42],
946+ )),
947+ ),
948+ (
949+ 24000,
950+ 0,
951+ 4,
952+ 2,
953+ 0,
954+ 0,
955+ 5,
956+ Some((
957+ 18,
958+ 13,
959+ 7,
960+ 1,
961+ &[16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 37, 40],
962+ &[16, 17, 19, 22, 26, 30, 34, 40],
963+ &[16, 40],
964+ )),
965+ ),
966+ (
967+ 24000,
968+ 7,
969+ 1,
970+ 2,
971+ 1,
972+ 0,
973+ 0,
974+ Some((
975+ 8,
976+ 8,
977+ 4,
978+ 1,
979+ &[19, 20, 21, 23, 25, 27, 29, 31, 34],
980+ &[19, 21, 25, 29, 34],
981+ &[19, 34],
982+ )),
983+ ),
984+ (
985+ 16000,
986+ 11,
987+ 15,
988+ 1,
989+ 1,
990+ 1,
991+ 6,
992+ Some((
993+ 14,
994+ 8,
995+ 4,
996+ 1,
997+ &[38, 40, 42, 45, 48, 51, 54, 59, 64],
998+ &[38, 42, 48, 54, 64],
999+ &[38, 64],
1000+ )),
1001+ ),
1002+ (
1003+ 44100,
1004+ 1,
1005+ 1,
1006+ 0,
1007+ 1,
1008+ 0,
1009+ 5,
1010+ Some((8, 3, 2, 1, &[19, 21, 23, 25], &[19, 21, 25], &[19, 25])),
1011+ ),
1012+ (
1013+ 64000,
1014+ 15,
1015+ 10,
1016+ 3,
1017+ 1,
1018+ 2,
1019+ 1,
1020+ Some((
1021+ 6,
1022+ 5,
1023+ 3,
1024+ 1,
1025+ &[32, 35, 38, 41, 45, 49],
1026+ &[32, 35, 41, 49],
1027+ &[32, 49],
1028+ )),
1029+ ),
1030+ (
1031+ 88200,
1032+ 10,
1033+ 14,
1034+ 3,
1035+ 0,
1036+ 0,
1037+ 4,
1038+ Some((8, 4, 2, 1, &[23, 25, 27, 29, 32], &[23, 27, 32], &[23, 32])),
1039+ ),
1040+ (
1041+ 32000,
1042+ 10,
1043+ 7,
1044+ 3,
1045+ 0,
1046+ 3,
1047+ 6,
1048+ Some((8, 2, 1, 1, &[38, 42, 46], &[38, 46], &[38, 46])),
1049+ ),
1050+ (
1051+ 22050,
1052+ 12,
1053+ 4,
1054+ 0,
1055+ 1,
1056+ 1,
1057+ 2,
1058+ Some((
1059+ 10,
1060+ 8,
1061+ 4,
1062+ 1,
1063+ &[26, 28, 30, 32, 34, 36, 38, 40, 42],
1064+ &[26, 30, 34, 38, 42],
1065+ &[26, 42],
1066+ )),
1067+ ),
1068+ (
1069+ 22050,
1070+ 4,
1071+ 11,
1072+ 1,
1073+ 0,
1074+ 1,
1075+ 2,
1076+ Some((
1077+ 22,
1078+ 20,
1079+ 10,
1080+ 2,
1081+ &[
1082+ 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48, 51, 54,
1083+ 58,
1084+ ],
1085+ &[18, 20, 22, 24, 28, 32, 36, 40, 45, 51, 58],
1086+ &[18, 32, 58],
1087+ )),
1088+ ),
1089+ (
1090+ 24000,
1091+ 1,
1092+ 1,
1093+ 2,
1094+ 0,
1095+ 2,
1096+ 6,
1097+ Some((
1098+ 14,
1099+ 8,
1100+ 4,
1101+ 2,
1102+ &[19, 20, 22, 24, 26, 28, 30, 32, 34],
1103+ &[19, 22, 26, 30, 34],
1104+ &[19, 26, 34],
1105+ )),
1106+ ),
1107+ (
1108+ 32000,
1109+ 4,
1110+ 2,
1111+ 1,
1112+ 1,
1113+ 1,
1114+ 7,
1115+ Some((
1116+ 14,
1117+ 7,
1118+ 4,
1119+ 1,
1120+ &[23, 24, 26, 28, 30, 32, 34, 36],
1121+ &[23, 24, 28, 32, 36],
1122+ &[23, 36],
1123+ )),
1124+ ),
1125+ (
1126+ 22050,
1127+ 9,
1128+ 13,
1129+ 2,
1130+ 0,
1131+ 3,
1132+ 2,
1133+ Some((
1134+ 16,
1135+ 14,
1136+ 7,
1137+ 4,
1138+ &[24, 26, 28, 30, 32, 34, 36, 39, 42, 45, 48, 52, 56, 60, 64],
1139+ &[24, 28, 32, 36, 42, 48, 56, 64],
1140+ &[24, 28, 36, 48, 64],
1141+ )),
1142+ ),
1143+ (
1144+ 44100,
1145+ 11,
1146+ 9,
1147+ 2,
1148+ 1,
1149+ 2,
1150+ 1,
1151+ Some((
1152+ 12,
1153+ 11,
1154+ 6,
1155+ 2,
1156+ &[22, 23, 25, 27, 29, 31, 33, 35, 38, 41, 44, 47],
1157+ &[22, 23, 27, 31, 35, 41, 47],
1158+ &[22, 31, 47],
1159+ )),
1160+ ),
1161+ (
1162+ 96000,
1163+ 7,
1164+ 10,
1165+ 2,
1166+ 0,
1167+ 1,
1168+ 7,
1169+ Some((
1170+ 18,
1171+ 11,
1172+ 6,
1173+ 1,
1174+ &[19, 20, 22, 24, 26, 28, 30, 32, 35, 38, 41, 44],
1175+ &[19, 20, 24, 28, 32, 38, 44],
1176+ &[19, 44],
1177+ )),
1178+ ),
1179+ (
1180+ 24000,
1181+ 12,
1182+ 8,
1183+ 0,
1184+ 1,
1185+ 3,
1186+ 4,
1187+ Some((
1188+ 12,
1189+ 8,
1190+ 4,
1191+ 2,
1192+ &[33, 35, 37, 39, 41, 43, 45, 47, 49],
1193+ &[33, 37, 41, 45, 49],
1194+ &[33, 41, 49],
1195+ )),
1196+ ),
1197+ (
1198+ 22050,
1199+ 7,
1200+ 7,
1201+ 1,
1202+ 1,
1203+ 1,
1204+ 6,
1205+ Some((
1206+ 16,
1207+ 10,
1208+ 5,
1209+ 1,
1210+ &[26, 28, 30, 32, 34, 36, 38, 40, 42, 45, 48],
1211+ &[26, 30, 34, 38, 42, 48],
1212+ &[26, 48],
1213+ )),
1214+ ),
1215+ (
1216+ 48000,
1217+ 13,
1218+ 10,
1219+ 0,
1220+ 0,
1221+ 3,
1222+ 5,
1223+ Some((
1224+ 24,
1225+ 19,
1226+ 10,
1227+ 2,
1228+ &[
1229+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49,
1230+ ],
1231+ &[29, 30, 32, 34, 36, 38, 40, 42, 44, 46, 49],
1232+ &[29, 38, 49],
1233+ )),
1234+ ),
1235+ (
1236+ 32000,
1237+ 15,
1238+ 15,
1239+ 0,
1240+ 0,
1241+ 1,
1242+ 5,
1243+ Some((
1244+ 32,
1245+ 27,
1246+ 14,
1247+ 1,
1248+ &[
1249+ 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
1250+ 57, 58, 59, 60, 61, 62, 63, 64,
1251+ ],
1252+ &[37, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64],
1253+ &[37, 64],
1254+ )),
1255+ ),
1256+ (
1257+ 96000,
1258+ 11,
1259+ 10,
1260+ 1,
1261+ 0,
1262+ 3,
1263+ 1,
1264+ Some((
1265+ 16,
1266+ 15,
1267+ 8,
1268+ 4,
1269+ &[
1270+ 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44,
1271+ ],
1272+ &[19, 20, 22, 24, 28, 32, 36, 40, 44],
1273+ &[19, 22, 28, 36, 44],
1274+ )),
1275+ ),
1276+ (
1277+ 22050,
1278+ 12,
1279+ 12,
1280+ 0,
1281+ 0,
1282+ 0,
1283+ 2,
1284+ Some((
1285+ 36,
1286+ 34,
1287+ 17,
1288+ 1,
1289+ &[
1290+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
1291+ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61,
1292+ ],
1293+ &[
1294+ 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 61,
1295+ ],
1296+ &[26, 61],
1297+ )),
1298+ ),
1299+ (
1300+ 22050,
1301+ 9,
1302+ 14,
1303+ 2,
1304+ 1,
1305+ 0,
1306+ 6,
1307+ Some((10, 4, 2, 1, &[32, 34, 36, 39, 42], &[32, 36, 42], &[32, 42])),
1308+ ),
1309+ (
1310+ 96000,
1311+ 2,
1312+ 4,
1313+ 0,
1314+ 1,
1315+ 0,
1316+ 7,
1317+ Some((8, 1, 1, 1, &[19, 21], &[19, 21], &[19, 21])),
1318+ ),
1319+ (
1320+ 24000,
1321+ 4,
1322+ 3,
1323+ 0,
1324+ 1,
1325+ 0,
1326+ 4,
1327+ Some((
1328+ 12,
1329+ 8,
1330+ 4,
1331+ 1,
1332+ &[22, 24, 26, 28, 30, 32, 34, 36, 38],
1333+ &[22, 26, 30, 34, 38],
1334+ &[22, 38],
1335+ )),
1336+ ),
1337+ (
1338+ 48000,
1339+ 10,
1340+ 9,
1341+ 3,
1342+ 0,
1343+ 2,
1344+ 0,
1345+ Some((
1346+ 10,
1347+ 10,
1348+ 5,
1349+ 3,
1350+ &[18, 19, 21, 23, 25, 27, 30, 33, 36, 40, 45],
1351+ &[18, 21, 25, 30, 36, 45],
1352+ &[18, 21, 30, 45],
1353+ )),
1354+ ),
1355+ (
1356+ 16000,
1357+ 11,
1358+ 2,
1359+ 2,
1360+ 1,
1361+ 3,
1362+ 7,
1363+ Some((8, 1, 1, 1, &[46, 50], &[46, 50], &[46, 50])),
1364+ ),
1365+ (
1366+ 64000,
1367+ 11,
1368+ 8,
1369+ 3,
1370+ 1,
1371+ 0,
1372+ 7,
1373+ Some((8, 1, 1, 1, &[37, 41], &[37, 41], &[37, 41])),
1374+ ),
1375+ (
1376+ 22050,
1377+ 1,
1378+ 12,
1379+ 2,
1380+ 0,
1381+ 1,
1382+ 3,
1383+ Some((
1384+ 22,
1385+ 19,
1386+ 10,
1387+ 2,
1388+ &[
1389+ 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 37, 40, 43, 46, 49, 53, 57, 61,
1390+ ],
1391+ &[16, 17, 19, 22, 26, 30, 34, 40, 46, 53, 61],
1392+ &[16, 30, 61],
1393+ )),
1394+ ),
1395+ (
1396+ 32000,
1397+ 5,
1398+ 5,
1399+ 1,
1400+ 0,
1401+ 2,
1402+ 5,
1403+ Some((
1404+ 16,
1405+ 11,
1406+ 6,
1407+ 2,
1408+ &[22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42],
1409+ &[22, 23, 26, 30, 34, 38, 42],
1410+ &[22, 30, 42],
1411+ )),
1412+ ),
1413+ (
1414+ 48000,
1415+ 9,
1416+ 2,
1417+ 3,
1418+ 1,
1419+ 2,
1420+ 1,
1421+ Some((4, 3, 2, 1, &[19, 21, 23, 25], &[19, 21, 25], &[19, 25])),
1422+ ),
1423+ (
1424+ 16000,
1425+ 13,
1426+ 5,
1427+ 1,
1428+ 0,
1429+ 0,
1430+ 2,
1431+ Some((
1432+ 10,
1433+ 8,
1434+ 4,
1435+ 1,
1436+ &[33, 35, 37, 39, 41, 44, 47, 50, 53],
1437+ &[33, 37, 41, 47, 53],
1438+ &[33, 53],
1439+ )),
1440+ ),
1441+ (
1442+ 88200,
1443+ 9,
1444+ 14,
1445+ 1,
1446+ 1,
1447+ 2,
1448+ 7,
1449+ Some((
1450+ 12,
1451+ 5,
1452+ 3,
1453+ 1,
1454+ &[21, 22, 23, 24, 26, 28],
1455+ &[21, 22, 24, 28],
1456+ &[21, 28],
1457+ )),
1458+ ),
1459+ (
1460+ 88200,
1461+ 10,
1462+ 2,
1463+ 1,
1464+ 0,
1465+ 3,
1466+ 1,
1467+ Some((2, 1, 1, 1, &[17, 19], &[17, 19], &[17, 19])),
1468+ ),
1469+ (
1470+ 44100,
1471+ 15,
1472+ 15,
1473+ 3,
1474+ 0,
1475+ 3,
1476+ 1,
1477+ Some((
1478+ 8,
1479+ 7,
1480+ 4,
1481+ 3,
1482+ &[35, 38, 41, 45, 49, 54, 59, 64],
1483+ &[35, 38, 45, 54, 64],
1484+ &[35, 38, 45, 64],
1485+ )),
1486+ ),
1487+ (
1488+ 22050,
1489+ 5,
1490+ 7,
1491+ 2,
1492+ 1,
1493+ 0,
1494+ 6,
1495+ Some((
1496+ 14,
1497+ 8,
1498+ 4,
1499+ 1,
1500+ &[26, 28, 30, 32, 34, 37, 40, 44, 48],
1501+ &[26, 30, 34, 40, 48],
1502+ &[26, 48],
1503+ )),
1504+ ),
1505+ (
1506+ 48000,
1507+ 15,
1508+ 15,
1509+ 1,
1510+ 0,
1511+ 3,
1512+ 7,
1513+ Some((
1514+ 12,
1515+ 5,
1516+ 3,
1517+ 1,
1518+ &[47, 50, 53, 56, 60, 64],
1519+ &[47, 50, 56, 64],
1520+ &[47, 64],
1521+ )),
1522+ ),
1523+ (
1524+ 64000,
1525+ 12,
1526+ 6,
1527+ 2,
1528+ 1,
1529+ 1,
1530+ 0,
1531+ Some((
1532+ 6,
1533+ 6,
1534+ 3,
1535+ 1,
1536+ &[21, 23, 25, 27, 29, 31, 34],
1537+ &[21, 25, 29, 34],
1538+ &[21, 34],
1539+ )),
1540+ ),
1541+ (
1542+ 32000,
1543+ 7,
1544+ 2,
1545+ 2,
1546+ 0,
1547+ 2,
1548+ 4,
1549+ Some((
1550+ 10,
1551+ 6,
1552+ 3,
1553+ 1,
1554+ &[24, 26, 28, 30, 32, 34, 36],
1555+ &[24, 28, 32, 36],
1556+ &[24, 36],
1557+ )),
1558+ ),
1559+ (
1560+ 44100,
1561+ 6,
1562+ 1,
1563+ 2,
1564+ 0,
1565+ 3,
1566+ 1,
1567+ Some((
1568+ 8,
1569+ 7,
1570+ 4,
1571+ 2,
1572+ &[16, 17, 18, 19, 20, 21, 23, 25],
1573+ &[16, 17, 19, 21, 25],
1574+ &[16, 19, 25],
1575+ )),
1576+ ),
1577+ (
1578+ 32000,
1579+ 9,
1580+ 1,
1581+ 2,
1582+ 1,
1583+ 2,
1584+ 0,
1585+ Some((
1586+ 6,
1587+ 6,
1588+ 3,
1589+ 1,
1590+ &[21, 23, 25, 27, 29, 31, 34],
1591+ &[21, 25, 29, 34],
1592+ &[21, 34],
1593+ )),
1594+ ),
1595+ (
1596+ 64000,
1597+ 9,
1598+ 9,
1599+ 2,
1600+ 1,
1601+ 1,
1602+ 7,
1603+ Some((
1604+ 14,
1605+ 7,
1606+ 4,
1607+ 1,
1608+ &[26, 28, 30, 32, 35, 38, 41, 45],
1609+ &[26, 28, 32, 38, 45],
1610+ &[26, 45],
1611+ )),
1612+ ),
1613+ (
1614+ 16000,
1615+ 14,
1616+ 0,
1617+ 1,
1618+ 0,
1619+ 0,
1620+ 1,
1621+ Some((
1622+ 8,
1623+ 7,
1624+ 4,
1625+ 1,
1626+ &[32, 34, 36, 38, 40, 42, 45, 48],
1627+ &[32, 34, 38, 42, 48],
1628+ &[32, 48],
1629+ )),
1630+ ),
1631+ (
1632+ 44100,
1633+ 5,
1634+ 9,
1635+ 3,
1636+ 0,
1637+ 0,
1638+ 1,
1639+ Some((
1640+ 14,
1641+ 13,
1642+ 7,
1643+ 1,
1644+ &[15, 16, 18, 20, 22, 24, 26, 28, 30, 33, 36, 39, 43, 47],
1645+ &[15, 16, 20, 24, 28, 33, 39, 47],
1646+ &[15, 47],
1647+ )),
1648+ ),
1649+ (
1650+ 44100,
1651+ 11,
1652+ 11,
1653+ 2,
1654+ 1,
1655+ 1,
1656+ 2,
1657+ Some((
1658+ 12,
1659+ 10,
1660+ 5,
1661+ 1,
1662+ &[24, 26, 28, 30, 32, 34, 36, 39, 42, 48, 55],
1663+ &[24, 28, 32, 36, 42, 55],
1664+ &[24, 55],
1665+ )),
1666+ ),
1667+ (
1668+ 88200,
1669+ 0,
1670+ 15,
1671+ 0,
1672+ 1,
1673+ 1,
1674+ 2,
1675+ Some((6, 4, 2, 1, &[7, 9, 11, 13, 15], &[7, 11, 15], &[7, 15])),
1676+ ),
1677+ (
1678+ 44100,
1679+ 5,
1680+ 9,
1681+ 1,
1682+ 0,
1683+ 1,
1684+ 6,
1685+ Some((
1686+ 20,
1687+ 14,
1688+ 7,
1689+ 1,
1690+ &[20, 21, 22, 23, 24, 26, 28, 30, 32, 34, 36, 38, 41, 44, 47],
1691+ &[20, 22, 24, 28, 32, 36, 41, 47],
1692+ &[20, 47],
1693+ )),
1694+ ),
1695+];
crates/ec-aac/src/sbr_chain.rsmodified+270 -37
@@ -6,6 +6,8 @@
6 6
7 use crate::sbr_env::{self, AdjustState};7 use crate::sbr_env::{self, AdjustState};
8 use crate::sbr_hf::{self, ChirpState, HfHistory};8 use crate::sbr_hf::{self, ChirpState, HfHistory};
9+use crate::ps_data::PsCommon;
10+use crate::ps_dsp::{IN_SLOTS, PsEngine, QMF_BANDS};
9 use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};11 use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};
10 use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};12 use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
11 use ec_core::BitReader;13 use ec_core::BitReader;
@@ -132,7 +134,7 @@ pub fn hold_call_count() -> usize {
132 }134 }
133 135
134 fn sideinfo_enabled() -> bool {136 fn sideinfo_enabled() -> bool {
135- std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok()137+ crate::knobs::sbr_sideinfo_debug()
136 }138 }
137 139
138 /// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named140 /// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named
@@ -196,6 +198,9 @@ struct ChannelState {
196 /// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32).198 /// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32).
197 const HF_ADJ: usize = 6;199 const HF_ADJ: usize = 6;
198 200
201+/// Samples a bypass plane lags its raw analysis by: `HF_ADJ` slots at the doubled rate.
202+const BYPASS_DELAY: usize = HF_ADJ * SYNTHESIS_BANDS;
203+
199 impl ChannelState {204 impl ChannelState {
200 fn new(n_q: usize, _seed: u32) -> ChannelState {205 fn new(n_q: usize, _seed: u32) -> ChannelState {
201 ChannelState {206 ChannelState {
@@ -226,13 +231,22 @@ struct Element {
226 last_data: Option<SbrData>,231 last_data: Option<SbrData>,
227 /// Header of the previous applied frame: a change is the spec's reset.232 /// Header of the previous applied frame: a change is the spec's reset.
228 last_header: Option<crate::sbr_payload::SbrHeader>,233 last_header: Option<crate::sbr_payload::SbrHeader>,
234+ /// Parametric Stereo reconstruction state (hybrid filter, decorrelator,
235+ /// mixing history), used when the element carries PS.
236+ ps_engine: PsEngine,
229 }237 }
230 238
239+/// QMF slots per SBR frame: the PS path runs only for the 32-slot frames
240+/// that AAC-LC's 1024-sample frames produce.
241+const PS_SLOTS: usize = 32;
242+
231 /// Every configured SBR element in a stream, keyed by243 /// Every configured SBR element in a stream, keyed by
232 /// `element_instance_tag` (assumed stable frame to frame, as every244 /// `element_instance_tag` (assumed stable frame to frame, as every
233 /// encoder in practice emits it).245 /// encoder in practice emits it).
234 pub struct SbrChain {246 pub struct SbrChain {
235 rate: u32,247 rate: u32,
248+ /// PS is signalled by the config (explicit HE-AACv2).
249+ ps_config: bool,
236 // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance250 // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance
237 // tags are independent namespaces per §4.4 (an encoder may legally251 // tags are independent namespaces per §4.4 (an encoder may legally
238 // reuse tag 0 for both an SCE and a CPE in the same access unit), so252 // reuse tag 0 for both an SCE and a CPE in the same access unit), so
@@ -240,43 +254,139 @@ pub struct SbrChain {
240 // together whenever that happened -- exactly the case in a 5.1254 // together whenever that happened -- exactly the case in a 5.1
241 // stream (SCE + two CPEs).255 // stream (SCE + two CPEs).
242 elements: HashMap<(u8, bool), Element>,256 elements: HashMap<(u8, bool), Element>,
257+ /// Doubling state of each LFE element, keyed by its instance tag. The LFE
258+ /// carries no SBR payload, but its plane still reaches the doubled rate.
259+ bypass: HashMap<u8, (ChannelState, Vec<f32>)>,
243 }260 }
244 261
245 impl SbrChain {262 impl SbrChain {
246 pub fn new(rate: u32) -> SbrChain {263 pub fn new(rate: u32) -> SbrChain {
247 SbrChain {264 SbrChain {
248 rate,265 rate,
266+ ps_config: false,
249 elements: HashMap::new(),267 elements: HashMap::new(),
268+ bypass: HashMap::new(),
269+ }
270+ }
271+
272+ /// Marks PS as signalled by the config: the element's output is stereo.
273+ pub fn set_ps_config(&mut self, on: bool) {
274+ self.ps_config = on;
275+ for elem in self.elements.values_mut() {
276+ elem.parser.set_ps_config(on);
250 }277 }
251 }278 }
252 279
253 /// Parses one FIL element's `sbr_extension_data` (the reader280 /// Parses one FIL element's `sbr_extension_data` (the reader
254 /// positioned right past `bs_extension_type`) for element `tag`.281 /// positioned right past `bs_extension_type`) for element `tag`.
255 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {282 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {
256- let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| Element {283+ let (rate, ps_config) = (self.rate, self.ps_config);
257- parser: SbrParser::new(self.rate),284+ let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| {
258- channels: Vec::new(),285+ let mut parser = SbrParser::new(rate);
259- last_data: None,286+ parser.set_ps_config(ps_config);
260- last_header: None,287+ Element {
288+ parser,
289+ channels: Vec::new(),
290+ last_data: None,
291+ last_header: None,
292+ ps_engine: PsEngine::new(),
293+ }
261 });294 });
262 let data = elem.parser.parse(r, is_cpe).ok()?;295 let data = elem.parser.parse(r, is_cpe).ok()?;
263 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);296 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);
264- while elem.channels.len() < data.channels.len() {297+ // PS needs a second synthesis state: the right output channel.
298+ let need = data.channels.len().max(if data.ps.is_some() { 2 } else { 1 });
299+ while elem.channels.len() < need {
265 let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9);300 let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9);
266 elem.channels.push(ChannelState::new(n_q, seed));301 elem.channels.push(ChannelState::new(n_q, seed));
267 }302 }
268 Some(data)303 Some(data)
269 }304 }
270 305
306+ /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR
307+ /// payload, so its core plane (one frame of `FRAME_LEN` samples) would
308+ /// otherwise stay at half length and misalign everything after it. It runs
309+ /// through the same 32-band analysis and 64-band synthesis as the SBR
310+ /// planes, with the high bands left empty, which is what ffmpeg's output
311+ /// does for the LFE channel.
312+ pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec<f32>) {
313+ let (state, delay) = self
314+ .bypass
315+ .entry(tag)
316+ .or_insert_with(|| (ChannelState::new(1, 0), vec![0.0; BYPASS_DELAY]));
317+ let num_slots = plane.len() / ANALYSIS_BANDS;
318+ let mut out = std::mem::take(delay);
319+ out.reserve(num_slots * SYNTHESIS_BANDS);
320+ for slot in 0..num_slots {
321+ let mut chunk = [0f32; ANALYSIS_BANDS];
322+ chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
323+ // Same scale handling as `apply_data`: the QMF pair is calibrated to the
324+ // un-normalised core PCM domain.
325+ for s in &mut chunk {
326+ *s /= crate::decode::OUTPUT_SCALE;
327+ }
328+ let sub = state.analysis.process_slot(&chunk);
329+ let mut slots = [Complex::<f64>::ZERO; SYNTHESIS_BANDS];
330+ slots[..ANALYSIS_BANDS].copy_from_slice(&sub);
331+ out.extend(synth_slots(&mut state.synthesis, &[slots]));
332+ }
333+ // The reconstructed planes lag their raw analysis by `HF_ADJ` slots;
334+ // hold the bypass output back by the same amount so they line up.
335+ let produced = num_slots * SYNTHESIS_BANDS;
336+ *plane = out[..produced].to_vec();
337+ *delay = out[produced..].to_vec();
338+ }
339+
340+ /// Like [`apply`], for an element whose output lives at `out[start..start + n]`
341+ /// inside a whole access unit. A PS element gets its second output
342+ /// plane inserted right after its first, so the access unit gains a
343+ /// channel.
344+ pub fn apply_planes(
345+ &mut self,
346+ tag: u8,
347+ is_cpe: bool,
348+ data: &SbrData,
349+ out: &mut Vec<Vec<f32>>,
350+ start: usize,
351+ n: usize,
352+ ) -> crate::Result<()> {
353+ let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some());
354+ self.apply(tag, is_cpe, data, &mut out[start..start + n])
355+ }
356+
357+ /// [`apply_planes`] for the last parsed frame, as [`apply_last`].
358+ pub fn apply_last_planes(
359+ &mut self,
360+ tag: u8,
361+ is_cpe: bool,
362+ out: &mut Vec<Vec<f32>>,
363+ start: usize,
364+ n: usize,
365+ ) -> crate::Result<()> {
366+ let has_ps = self
367+ .elements
368+ .get(&(tag, is_cpe))
369+ .and_then(|e| e.last_data.as_ref())
370+ .is_some_and(|d| d.ps.is_some());
371+ let n = expand_for_ps(out, start, n, is_cpe, has_ps);
372+ self.apply_last(tag, is_cpe, &mut out[start..start + n])
373+ }
374+
271 /// Runs the chain over `planes` (element `tag`'s already-decoded core375 /// Runs the chain over `planes` (element `tag`'s already-decoded core
272 /// PCM, one plane per channel), replacing each in place with its376 /// PCM, one plane per channel), replacing each in place with its
273 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a377 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a
274 /// silent no-op: `planes` is left at its core content.378 /// silent no-op: `planes` is left at its core content.
275- pub fn apply(&mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec<f32>]) {379+ pub fn apply(
380+ &mut self,
381+ tag: u8,
382+ is_cpe: bool,
383+ data: &SbrData,
384+ planes: &mut [Vec<f32>],
385+ ) -> crate::Result<()> {
276 if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {386 if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
277 elem.last_data = Some(data.clone());387 elem.last_data = Some(data.clone());
278 }388 }
279- self.apply_data(tag, is_cpe, data, planes, "fresh");389+ self.apply_data(tag, is_cpe, data, planes, "fresh")
280 }390 }
281 391
282 /// Re-runs the chain for `tag` using the last successfully parsed392 /// Re-runs the chain for `tag` using the last successfully parsed
@@ -284,15 +394,20 @@ impl SbrChain {
284 /// fresh payload this frame. A no-op (planes left at core content, same394 /// fresh payload this frame. A no-op (planes left at core content, same
285 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior395 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior
286 /// frame ever parsed successfully for this element.396 /// frame ever parsed successfully for this element.
287- pub fn apply_last(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) {397+ pub fn apply_last(
398+ &mut self,
399+ tag: u8,
400+ is_cpe: bool,
401+ planes: &mut [Vec<f32>],
402+ ) -> crate::Result<()> {
288 let Some(data) = self403 let Some(data) = self
289 .elements404 .elements
290 .get(&(tag, is_cpe))405 .get(&(tag, is_cpe))
291 .and_then(|e| e.last_data.clone())406 .and_then(|e| e.last_data.clone())
292 else {407 else {
293- return;408+ return Ok(());
294 };409 };
295- self.apply_data(tag, is_cpe, &data, planes, "hold");410+ self.apply_data(tag, is_cpe, &data, planes, "hold")
296 }411 }
297 412
298 fn apply_data(413 fn apply_data(
@@ -302,20 +417,20 @@ impl SbrChain {
302 data: &SbrData,417 data: &SbrData,
303 planes: &mut [Vec<f32>],418 planes: &mut [Vec<f32>],
304 source: &'static str,419 source: &'static str,
305- ) {420+ ) -> crate::Result<()> {
306 if source == "hold" {421 if source == "hold" {
307 HOLD_CALLS.fetch_add(1, Ordering::Relaxed);422 HOLD_CALLS.fetch_add(1, Ordering::Relaxed);
308 }423 }
309 let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {424 let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
310- return;425+ return Ok(());
311 };426 };
312 let Some(tables) = elem.parser.tables().cloned() else {427 let Some(tables) = elem.parser.tables().cloned() else {
313- return;428+ return Ok(());
314 };429 };
315 let reset = elem.last_header.as_ref() != elem.parser.header();430 let reset = elem.last_header.as_ref() != elem.parser.header();
316 elem.last_header = elem.parser.header().cloned();431 elem.last_header = elem.parser.header().cloned();
317 let Some(header) = elem.parser.header().cloned() else {432 let Some(header) = elem.parser.header().cloned() else {
318- return;433+ return Ok(());
319 };434 };
320 let coupling = data.coupling;435 let coupling = data.coupling;
321 let sideinfo_on = sideinfo_enabled();436 let sideinfo_on = sideinfo_enabled();
@@ -324,6 +439,15 @@ impl SbrChain {
324 } else {439 } else {
325 0440 0
326 };441 };
442+ // PS: the mono channel is synthesized twice, through its own state and
443+ // through channel 1's (the right output), so both stay in step.
444+ let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some();
445+ let mut ps_planes: Option<(Vec<f32>, Vec<f32>)> = None;
446+ let mut r_synth = if ps_mode && elem.channels.len() >= 2 {
447+ Some(std::mem::take(&mut elem.channels[1].synthesis))
448+ } else {
449+ None
450+ };
327 for (ch, plane) in planes.iter_mut().enumerate() {451 for (ch, plane) in planes.iter_mut().enumerate() {
328 if ch >= data.channels.len() || ch >= elem.channels.len() {452 if ch >= data.channels.len() || ch >= elem.channels.len() {
329 continue;453 continue;
@@ -454,7 +578,7 @@ impl SbrChain {
454 &tables,578 &tables,
455 &sbr_hf::build_patches(&tables),579 &sbr_hf::build_patches(&tables),
456 header.limiter_bands,580 header.limiter_bands,
457- );581+ )?;
458 // Envelope slot i is raw slot i - HF_ADJ: prepend the previous582 // Envelope slot i is raw slot i - HF_ADJ: prepend the previous
459 // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines583 // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines
460 // up with the content it was measured on (§4.6.18.7.6).584 // up with the content it was measured on (§4.6.18.7.6).
@@ -514,26 +638,33 @@ impl SbrChain {
514 638
515 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);639 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
516 let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS);640 let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS);
517- let mut out = Vec::with_capacity(num_slots * SYNTHESIS_BANDS);641+ let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots);
518 for slot in 0..num_slots {642 for slot in 0..num_slots {
519 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];643 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
520 v[0..kx].copy_from_slice(&raw[slot][0..kx]);644 v[0..kx].copy_from_slice(&raw[slot][0..kx]);
521- if std::env::var("EC_AAC_SBR_HF_BYPASS").is_err() {645+ if !crate::knobs::sbr_hf_bypass() {
522 for b in kx..k2 {646 for b in kx..k2 {
523 if b - kx < hf.len() {647 if b - kx < hf.len() {
524 v[b] = hf[b - kx][slot];648 v[b] = hf[b - kx][slot];
525 }649 }
526 }650 }
527 }651 }
528- let mut pcm = state.synthesis.process_slot(&v);652+ vs.push(v);
529- for s in &mut pcm {
530- // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 +
531- // 4.6.18.8.2, literal equations) reads back at half the
532- // core's amplitude; the 2x is the upsampler's gain.
533- *s *= 2.0 * crate::decode::OUTPUT_SCALE;
534- }
535- out.extend_from_slice(&pcm);
536 }653 }
654+ let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) {
655+ (true, Some(ps)) => {
656+ let (left, right) =
657+ render_ps(&mut elem.ps_engine, ps, &vs, &state.low_tail, kx, k2);
658+ let left_pcm = synth_slots(&mut state.synthesis, &left);
659+ let right_pcm = match r_synth.as_mut() {
660+ Some(rs) => synth_slots(rs, &right),
661+ None => left_pcm.clone(),
662+ };
663+ ps_planes = Some((left_pcm, right_pcm));
664+ Vec::new()
665+ }
666+ _ => synth_slots(&mut state.synthesis, &vs),
667+ };
537 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {668 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
538 static N: AtomicUsize = AtomicUsize::new(0);669 static N: AtomicUsize = AtomicUsize::new(0);
539 let n = N.fetch_add(1, Ordering::Relaxed);670 let n = N.fetch_add(1, Ordering::Relaxed);
@@ -548,9 +679,105 @@ impl SbrChain {
548 );679 );
549 }680 }
550 }681 }
551- *plane = out;682+ if ps_planes.is_none() {
683+ *plane = out;
684+ }
685+ }
686+ if let Some(rs) = r_synth {
687+ elem.channels[1].synthesis = rs;
688+ }
689+ if let Some((left, right)) = ps_planes {
690+ planes[0] = left;
691+ planes[1] = right;
692+ }
693+ Ok(())
694+ }
695+}
696+
697+/// Inserts the second output plane a PS element needs, right after its first
698+/// (a copy, which the PS path then overwrites). Returns the element's new
699+/// plane count: 2 when a plane was inserted.
700+fn expand_for_ps(out: &mut Vec<Vec<f32>>, start: usize, n: usize, is_cpe: bool, ps: bool) -> usize {
701+ if ps && !is_cpe && n == 1 && start < out.len() {
702+ let copy = out[start].clone();
703+ out.insert(start + 1, copy);
704+ 2
705+ } else {
706+ n
707+ }
708+}
709+
710+/// Narrows a working-precision QMF sample to the PS engine's single precision.
711+fn narrow32(v: Complex<f64>) -> Complex<f32> {
712+ Complex { re: v.re as f32, im: v.im as f32 }
713+}
714+
715+/// Widens a PS output slab row back to working precision.
716+fn widen(row: &[Complex<f32>; QMF_BANDS]) -> [Complex<f64>; SYNTHESIS_BANDS] {
717+ let mut out = [Complex::ZERO; SYNTHESIS_BANDS];
718+ for (dst, src) in out.iter_mut().zip(row.iter()) {
719+ *dst = Complex { re: f64::from(src.re), im: f64::from(src.im) };
720+ }
721+ out
722+}
723+
724+/// Runs Parametric Stereo over one frame's synthesis input `vs` (32 slots of
725+/// the mono channel's QMF bands). The hybrid filter reads 6 slots past the
726+/// frame, for the low bands it splits: those come from `low_tail`, the raw
727+/// analysis of the same frame, which holds the slots `vs` cannot.
728+type PlaneVec = Vec<[Complex<f64>; SYNTHESIS_BANDS]>;
729+
730+fn render_ps(
731+ engine: &mut PsEngine,
732+ ps: &PsCommon,
733+ vs: &[[Complex<f64>; SYNTHESIS_BANDS]],
734+ low_tail: &[[Complex<f64>; ANALYSIS_BANDS]],
735+ kx: usize,
736+ top: usize,
737+) -> (PlaneVec, PlaneVec) {
738+ if !ps.start {
739+ // No PS header yet: both channels carry the mono signal (FFmpeg's memcpy).
740+ return (vs.to_vec(), vs.to_vec());
741+ }
742+ let mut x = [[Complex::<f32>::new(0.0, 0.0); QMF_BANDS]; IN_SLOTS];
743+ for (j, v) in vs.iter().enumerate().take(IN_SLOTS) {
744+ for (dst, src) in x[j].iter_mut().zip(v.iter()) {
745+ *dst = narrow32(*src);
746+ }
747+ }
748+ // Only bands below the SBR start hold raw analysis; the hybrid filter
749+ // reads lookahead for bands 0..5 only, and those are raw below kx.
750+ let lookahead_bands = kx.min(5);
751+ for (j, row) in low_tail.iter().enumerate() {
752+ let slot = PS_SLOTS + j;
753+ if slot >= IN_SLOTS {
754+ break;
755+ }
756+ for (b, sample) in row.iter().enumerate().take(lookahead_bands) {
757+ x[slot][b] = narrow32(*sample);
758+ }
759+ }
760+ let (left, right) = engine.apply(ps, &x, top);
761+ (
762+ left.iter().map(widen).collect(),
763+ right.iter().map(widen).collect(),
764+ )
765+}
766+
767+/// Runs `slots` through a synthesis bank, at the SBR output scale.
768+fn synth_slots(synth: &mut Synthesis, slots: &[[Complex<f64>; SYNTHESIS_BANDS]]) -> Vec<f32> {
769+ let mut out = Vec::with_capacity(slots.len() * SYNTHESIS_BANDS);
770+ for v in slots {
771+ let mut pcm = synth.process_slot(v);
772+ for s in &mut pcm {
773+ // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 +
774+ // 4.6.18.8.2, literal equations) reads back at half the
775+ // core's amplitude; the 2x is the upsampler's gain.
776+ *s *= 2.0 * crate::decode::OUTPUT_SCALE;
552 }777 }
778+ out.extend_from_slice(&pcm);
553 }779 }
780+ out
554 }781 }
555 782
556 #[cfg(test)]783 #[cfg(test)]
@@ -616,6 +843,7 @@ mod tests {
616 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],843 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
617 last_data: None,844 last_data: None,
618 last_header: None,845 last_header: None,
846+ ps_engine: PsEngine::new(),
619 },847 },
620 );848 );
621 chain849 chain
@@ -628,6 +856,7 @@ mod tests {
628 let data = SbrData {856 let data = SbrData {
629 coupling: false,857 coupling: false,
630 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],858 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
859+ ps: None,
631 };860 };
632 861
633 // A steady tone, not silence: silence round-trips trivially (every862 // A steady tone, not silence: silence round-trips trivially (every
@@ -635,7 +864,7 @@ mod tests {
635 // discontinuity this test exists to catch.864 // discontinuity this test exists to catch.
636 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };865 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };
637 let mut planes = vec![core_au(), core_au()];866 let mut planes = vec![core_au(), core_au()];
638- chain.apply(tag, true, &data, &mut planes);867+ chain.apply(tag, true, &data, &mut planes).unwrap();
639 868
640 let expected_len = 32 * SYNTHESIS_BANDS;869 let expected_len = 32 * SYNTHESIS_BANDS;
641 for (ch, plane) in planes.iter().enumerate() {870 for (ch, plane) in planes.iter().enumerate() {
@@ -651,7 +880,7 @@ mod tests {
651 // generator continuity across the junction, not just each AU in880 // generator continuity across the junction, not just each AU in
652 // isolation.881 // isolation.
653 let mut planes2 = vec![core_au(), core_au()];882 let mut planes2 = vec![core_au(), core_au()];
654- chain.apply(tag, true, &data, &mut planes2);883+ chain.apply(tag, true, &data, &mut planes2).unwrap();
655 for (ch, plane) in planes2.iter().enumerate() {884 for (ch, plane) in planes2.iter().enumerate() {
656 assert_eq!(885 assert_eq!(
657 plane.len(),886 plane.len(),
@@ -716,6 +945,7 @@ mod tests {
716 .collect(),945 .collect(),
717 last_data: None,946 last_data: None,
718 last_header: None,947 last_header: None,
948+ ps_engine: PsEngine::new(),
719 },949 },
720 );950 );
721 chain951 chain
@@ -729,19 +959,21 @@ mod tests {
729 let sce_data = SbrData {959 let sce_data = SbrData {
730 coupling: false,960 coupling: false,
731 channels: vec![one_channel(n_q, n_low)],961 channels: vec![one_channel(n_q, n_low)],
962+ ps: None,
732 };963 };
733 let cpe_data = SbrData {964 let cpe_data = SbrData {
734 coupling: false,965 coupling: false,
735 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],966 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
967+ ps: None,
736 };968 };
737 969
738 let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() };970 let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() };
739 let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() };971 let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() };
740 972
741 let mut sce_planes = vec![sce_tone()];973 let mut sce_planes = vec![sce_tone()];
742- chain.apply(tag, false, &sce_data, &mut sce_planes);974+ chain.apply(tag, false, &sce_data, &mut sce_planes).unwrap();
743 let mut cpe_planes = vec![cpe_tone(), cpe_tone()];975 let mut cpe_planes = vec![cpe_tone(), cpe_tone()];
744- chain.apply(tag, true, &cpe_data, &mut cpe_planes);976+ chain.apply(tag, true, &cpe_data, &mut cpe_planes).unwrap();
745 977
746 // If state aliased, the CPE call above would have run through (and978 // If state aliased, the CPE call above would have run through (and
747 // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead979 // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead
@@ -749,7 +981,7 @@ mod tests {
749 // the SAME output as the first call, proving its state was never981 // the SAME output as the first call, proving its state was never
750 // touched by the CPE call in between.982 // touched by the CPE call in between.
751 let mut sce_planes2 = vec![sce_tone()];983 let mut sce_planes2 = vec![sce_tone()];
752- chain.apply(tag, false, &sce_data, &mut sce_planes2);984+ chain.apply(tag, false, &sce_data, &mut sce_planes2).unwrap();
753 985
754 // A fresh, never-driven SCE-only chain gives the reference: one AU986 // A fresh, never-driven SCE-only chain gives the reference: one AU
755 // through tag/is_cpe=(0,false), nothing else touching its state.987 // through tag/is_cpe=(0,false), nothing else touching its state.
@@ -761,6 +993,7 @@ mod tests {
761 channels: vec![ChannelState::new(n_q, 10)],993 channels: vec![ChannelState::new(n_q, 10)],
762 last_data: None,994 last_data: None,
763 last_header: None,995 last_header: None,
996+ ps_engine: PsEngine::new(),
764 },997 },
765 );998 );
766 reference999 reference
@@ -770,9 +1003,9 @@ mod tests {
770 .parser1003 .parser
771 .set_for_test(header(), t.clone());1004 .set_for_test(header(), t.clone());
772 let mut sce_ref1 = vec![sce_tone()];1005 let mut sce_ref1 = vec![sce_tone()];
773- reference.apply(tag, false, &sce_data, &mut sce_ref1);1006+ reference.apply(tag, false, &sce_data, &mut sce_ref1).unwrap();
774 let mut sce_ref2 = vec![sce_tone()];1007 let mut sce_ref2 = vec![sce_tone()];
775- reference.apply(tag, false, &sce_data, &mut sce_ref2);1008+ reference.apply(tag, false, &sce_data, &mut sce_ref2).unwrap();
776 1009
777 assert_eq!(1010 assert_eq!(
778 sce_planes[0], sce_ref1[0],1011 sce_planes[0], sce_ref1[0],
@@ -821,7 +1054,7 @@ mod tests {
821 let mut synthesis_a = Synthesis::new();1054 let mut synthesis_a = Synthesis::new();
822 let mut per_au_out: Vec<f32> = Vec::new();1055 let mut per_au_out: Vec<f32> = Vec::new();
823 for au in all_samples.chunks(1024) {1056 for au in all_samples.chunks(1024) {
824- for slot in au.chunks_exact(ANALYSIS_BANDS) {1057+ for slot in au.as_chunks::<ANALYSIS_BANDS>().0 {
825 let mut chunk = [0f32; ANALYSIS_BANDS];1058 let mut chunk = [0f32; ANALYSIS_BANDS];
826 chunk.copy_from_slice(slot);1059 chunk.copy_from_slice(slot);
827 let sub = analysis_a.process_slot(&chunk);1060 let sub = analysis_a.process_slot(&chunk);
@@ -836,7 +1069,7 @@ mod tests {
836 let mut analysis_b = Analysis::new();1069 let mut analysis_b = Analysis::new();
837 let mut synthesis_b = Synthesis::new();1070 let mut synthesis_b = Synthesis::new();
838 let mut continuous_out: Vec<f32> = Vec::new();1071 let mut continuous_out: Vec<f32> = Vec::new();
839- for slot in all_samples.chunks_exact(ANALYSIS_BANDS) {1072+ for slot in all_samples.as_chunks::<ANALYSIS_BANDS>().0 {
840 let mut chunk = [0f32; ANALYSIS_BANDS];1073 let mut chunk = [0f32; ANALYSIS_BANDS];
841 chunk.copy_from_slice(slot);1074 chunk.copy_from_slice(slot);
842 let sub = analysis_b.process_slot(&chunk);1075 let sub = analysis_b.process_slot(&chunk);
crates/ec-aac/src/sbr_env.rsmodified+4 -4
@@ -169,7 +169,7 @@ impl Default for AdjustState {
169 }169 }
170 170
171 fn noise_fraction_debug() -> bool {171 fn noise_fraction_debug() -> bool {
172- std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok()172+ crate::knobs::sbr_noise_fraction()
173 }173 }
174 174
175 type NoiseFractionRows = Vec<(usize, f64, f64, f64)>;175 type NoiseFractionRows = Vec<(usize, f64, f64, f64)>;
@@ -227,7 +227,7 @@ pub fn adjust(
227 } else {227 } else {
228 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]228 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]
229 };229 };
230- let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok();230+ let zero_noise = crate::knobs::sbr_noise_zero();
231 let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok();231 let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok();
232 let track_fraction = noise_fraction_debug();232 let track_fraction = noise_fraction_debug();
233 let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 };233 let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 };
@@ -530,7 +530,7 @@ mod tests {
530 // Q_mapped = 1 (q_q = 6): half the target is noise.530 // Q_mapped = 1 (q_q = 6): half the target is noise.
531 let noise_energy = vec![vec![1.0f64; tables.n_q]];531 let noise_energy = vec![vec![1.0f64; tables.n_q]];
532 let hdr = header(1, 3);532 let hdr = header(1, 3);
533- let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);533+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands).unwrap();
534 let mut st = AdjustState::new();534 let mut st = AdjustState::new();
535 adjust(&mut hf, &tables, &hdr, &channel(&tables, None), &env_energy, &noise_energy, &lim, &mut st, true);535 adjust(&mut hf, &tables, &hdr, &channel(&tables, None), &env_energy, &noise_energy, &lim, &mut st, true);
536 for m in 0..k2 - kx {536 for m in 0..k2 - kx {
@@ -552,7 +552,7 @@ mod tests {
552 let env_energy = vec![vec![4.0f64; tables.n_high]];552 let env_energy = vec![vec![4.0f64; tables.n_high]];
553 let noise_energy = vec![vec![0.0f64; tables.n_q]];553 let noise_energy = vec![vec![0.0f64; tables.n_q]];
554 let hdr = header(1, 1);554 let hdr = header(1, 1);
555- let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);555+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands).unwrap();
556 let mut st = AdjustState::new();556 let mut st = AdjustState::new();
557 adjust(&mut hf, &tables, &hdr, &channel(&tables, Some(flags)), &env_energy, &noise_energy, &lim, &mut st, true);557 adjust(&mut hf, &tables, &hdr, &channel(&tables, Some(flags)), &env_energy, &noise_energy, &lim, &mut st, true);
558 let mid = ((tables.f_high[1] + tables.f_high[2]) >> 1) as usize - kx;558 let mid = ((tables.f_high[1] + tables.f_high[2]) >> 1) as usize - kx;
crates/ec-aac/src/sbr_hf.rsmodified+22 -9
@@ -193,14 +193,18 @@ pub fn build_patches(tables: &BandTables) -> Vec<Patch> {
193 /// borders closer than `0.49/limBands` octaves collapse (`bs_limiter_bands`193 /// borders closer than `0.49/limBands` octaves collapse (`bs_limiter_bands`
194 /// 1/2/3 => 1.2/2/3 bands per octave), keeping patch borders over194 /// 1/2/3 => 1.2/2/3 bands per octave), keeping patch borders over
195 /// envelope borders when one of the pair must go. `0` => one band.195 /// envelope borders when one of the pair must go. `0` => one band.
196-pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands: u8) -> Vec<i64> {196+pub fn limiter_band_table(
197+ tables: &BandTables,
198+ patches: &[Patch],
199+ limiter_bands: u8,
200+) -> crate::Result<Vec<i64>> {
197 let kx = tables.kx;201 let kx = tables.kx;
198 let k2 = tables.k2;202 let k2 = tables.k2;
199 if kx >= k2 {203 if kx >= k2 {
200- return vec![kx, k2.max(kx)];204+ return Ok(vec![kx, k2.max(kx)]);
201 }205 }
202 if limiter_bands == 0 {206 if limiter_bands == 0 {
203- return vec![kx, k2];207+ return Ok(vec![kx, k2]);
204 }208 }
205 let warped = match limiter_bands {209 let warped = match limiter_bands {
206 1 => 2f64.powf(0.49 / 1.2),210 1 => 2f64.powf(0.49 / 1.2),
@@ -209,26 +213,35 @@ pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands:
209 };213 };
210 let mut patch_borders: Vec<i64> = vec![kx];214 let mut patch_borders: Vec<i64> = vec![kx];
211 for p in patches {215 for p in patches {
212- patch_borders.push(patch_borders.last().unwrap() + p.width as i64);216+ let last = patch_borders.last().copied().unwrap_or(kx);
217+ patch_borders.push(last.saturating_add(p.width as i64));
213 }218 }
214 let mut table: Vec<i64> = tables.f_low.clone();219 let mut table: Vec<i64> = tables.f_low.clone();
215 table.extend(patch_borders.iter().skip(1).take(patches.len().saturating_sub(1)));220 table.extend(patch_borders.iter().skip(1).take(patches.len().saturating_sub(1)));
216 table.sort_unstable();221 table.sort_unstable();
217 let is_patch = |b: i64| patch_borders.contains(&b);222 let is_patch = |b: i64| patch_borders.contains(&b);
218- let mut out: Vec<i64> = vec![table[0]];223+ let Some((&first, rest)) = table.split_first() else {
219- for &b in &table[1..] {224+ return Err(crate::Error::corrupt("sbr: empty limiter border set"));
220- let last = *out.last().unwrap();225+ };
226+ let mut out: Vec<i64> = vec![first];
227+ for &b in rest {
228+ let last = out
229+ .last()
230+ .copied()
231+ .ok_or_else(|| crate::Error::corrupt("sbr: limiter table lost its first border"))?;
221 if (b as f64) >= (last as f64) * warped {232 if (b as f64) >= (last as f64) * warped {
222 out.push(b);233 out.push(b);
223 } else if b == last || !is_patch(b) {234 } else if b == last || !is_patch(b) {
224 // drop the incoming border235 // drop the incoming border
225 } else if !is_patch(last) {236 } else if !is_patch(last) {
226- *out.last_mut().unwrap() = b;237+ if let Some(slot) = out.last_mut() {
238+ *slot = b;
239+ }
227 } else {240 } else {
228 out.push(b);241 out.push(b);
229 }242 }
230 }243 }
231- out244+ Ok(out)
232 }245 }
233 246
234 /// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163):247 /// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163):
crates/ec-aac/src/sbr_payload.rsmodified+56 -9
@@ -15,6 +15,7 @@
15 //! `sbrtables.py` never needed them for the codebook derivation.15 //! `sbrtables.py` never needed them for the codebook derivation.
16 #![allow(dead_code)]16 #![allow(dead_code)]
17 17
18+use crate::ps_data::PsCommon;
18 use crate::sbr_bands::{BandTables, freq_tables};19 use crate::sbr_bands::{BandTables, freq_tables};
19 use crate::sbr_tables::*;20 use crate::sbr_tables::*;
20 use ec_core::{BitReader, Error, Result};21 use ec_core::{BitReader, Error, Result};
@@ -78,6 +79,10 @@ pub struct SbrData {
78 /// slice's job).79 /// slice's job).
79 pub coupling: bool,80 pub coupling: bool,
80 pub channels: Vec<SbrChannel>,81 pub channels: Vec<SbrChannel>,
82+ /// The element's Parametric Stereo state, present when this element
83+ /// carries PS (signalled in the config, or a PS extension seen earlier).
84+ /// `ps.start` tells whether a PS header has been decoded yet.
85+ pub ps: Option<PsCommon>,
81 }86 }
82 87
83 #[derive(Clone, Debug)]88 #[derive(Clone, Debug)]
@@ -102,10 +107,10 @@ impl Grid {
102 } else {107 } else {
103 let middle = match frame_class {108 let middle = match frame_class {
104 0 => num_env >> 1,109 0 => num_env >> 1,
105- 1 | 3 => num_env - pointer.saturating_sub(1).max(1),110+ 1 | 3 => num_env.saturating_sub(pointer.saturating_sub(1).max(1)),
106 _ => match pointer {111 _ => match pointer {
107 0 => 1,112 0 => 1,
108- 1 => num_env - 1,113+ 1 => num_env.saturating_sub(1),
109 p => p - 1,114 p => p - 1,
110 },115 },
111 };116 };
@@ -149,8 +154,17 @@ pub struct SbrParser {
149 header: Option<SbrHeader>,154 header: Option<SbrHeader>,
150 tables: Option<BandTables>,155 tables: Option<BandTables>,
151 state: [ChannelState; 2],156 state: [ChannelState; 2],
157+ /// Parametric Stereo state, persistent across frames (FFmpeg's
158+ /// `sbr->ps.common`).
159+ ps: PsCommon,
160+ /// PS is in use for this element: signalled in the config, or a PS
161+ /// extension has been read.
162+ ps_enabled: bool,
152 }163 }
153 164
165+/// `bs_extension_id` of Parametric Stereo.
166+const EXTENSION_ID_PS: u32 = 2;
167+
154 fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static [(u8, u32, i32)] {168 fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static [(u8, u32, i32)] {
155 match (balance, amp_res != 0, dt) {169 match (balance, amp_res != 0, dt) {
156 (false, false, false) => &ENV15_F,170 (false, false, false) => &ENV15_F,
@@ -253,9 +267,17 @@ impl SbrParser {
253 header: None,267 header: None,
254 tables: None,268 tables: None,
255 state: Default::default(),269 state: Default::default(),
270+ ps: PsCommon::default(),
271+ ps_enabled: false,
256 }272 }
257 }273 }
258 274
275+ /// Marks PS as signalled by the config (explicit HE-AACv2), so every
276+ /// frame of this element reconstructs stereo.
277+ pub fn set_ps_config(&mut self, on: bool) {
278+ self.ps_enabled |= on;
279+ }
280+
259 /// The header this parser is currently using, if any frame has carried one.281 /// The header this parser is currently using, if any frame has carried one.
260 pub fn header(&self) -> Option<&SbrHeader> {282 pub fn header(&self) -> Option<&SbrHeader> {
261 self.header.as_ref()283 self.header.as_ref()
@@ -518,8 +540,14 @@ impl SbrParser {
518 } else if self.header.is_none() {540 } else if self.header.is_none() {
519 return Err(Error::corrupt("sbr: headerless frame with no prior header"));541 return Err(Error::corrupt("sbr: headerless frame with no prior header"));
520 }542 }
521- let header = self.header.clone().expect("checked above");543+ let header = self
522- let tables = self.tables.clone().expect("set with header");544+ .header
545+ .clone()
546+ .ok_or_else(|| Error::corrupt("sbr: header missing for SBR payload"))?;
547+ let tables = self
548+ .tables
549+ .clone()
550+ .ok_or_else(|| Error::corrupt("sbr: band tables missing for SBR payload"))?;
523 551
524 let data_extra = r.read_bit()?;552 let data_extra = r.read_bit()?;
525 if data_extra {553 if data_extra {
@@ -701,16 +729,35 @@ impl SbrParser {
701 }729 }
702 }730 }
703 731
732+ // sbr_extension_data() extensions, as FFmpeg's `read_sbr_extension`
733+ // loop: a 4-bit size (plus an 8-bit escape at 15), in bits; each
734+ // extension is a 2-bit id. PS is parsed, anything else is skipped.
704 let extended = r.read_bit()?;735 let extended = r.read_bit()?;
705 if extended {736 if extended {
706- let mut size = r.read_bits(4)? as u64;737+ let mut left = u64::from(r.read_bits(4)?);
707- if size == 15 {738+ if left == 15 {
708- size += u64::from(r.read_bits(8)?);739+ left += u64::from(r.read_bits(8)?);
740+ }
741+ left <<= 3;
742+ while left > 7 {
743+ left -= 2;
744+ let ext_id = r.read_bits(2)?;
745+ if ext_id == EXTENSION_ID_PS {
746+ self.ps_enabled = true;
747+ let used = self.ps.read_data(r, left);
748+ left = left.saturating_sub(used);
749+ } else {
750+ r.skip_bits(left)?;
751+ left = 0;
752+ }
753+ }
754+ if left > 0 {
755+ r.skip_bits(left)?;
709 }756 }
710- r.skip_bits(size * 8)?;
711 }757 }
712 758
713- Ok(SbrData { coupling, channels })759+ let ps = self.ps_enabled.then(|| self.ps.clone());
760+ Ok(SbrData { coupling, channels, ps })
714 }761 }
715 }762 }
716 763
crates/ec-aac/src/sbr_qmf.rsmodified+2 -2
@@ -470,8 +470,8 @@ mod tests {
470 assert_eq!(QMF_WINDOW.len(), PROTO_LEN);470 assert_eq!(QMF_WINDOW.len(), PROTO_LEN);
471 let sum: f64 = QMF_WINDOW.iter().sum();471 let sum: f64 = QMF_WINDOW.iter().sum();
472 let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum();472 let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum();
473- assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}");473+ assert!((sum - 81.46300943655164).abs() < 1e-9, "sum={sum}");
474- assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}");474+ assert!((sum_sq - 64.00000000000003).abs() < 1e-9, "sum_sq={sum_sq}");
475 }475 }
476 476
477 477
crates/ec-aac/src/sbr_qmf_window.rsmodified+163 -163
@@ -18,166 +18,166 @@
18 /// the next attempt at the normative bank.18 /// the next attempt at the normative bank.
19 #[allow(dead_code)]19 #[allow(dead_code)]
20 pub const QMF_WINDOW: [f64; 640] = [20 pub const QMF_WINDOW: [f64; 640] = [
21- 0.00000000000000000e+00, -5.52528650469999959e-04, -5.61769257379999957e-04, -4.94751808959999987e-04,21+ 0.0, -0.00055252865047, -0.00056176925738, -0.00049475180896,
22- -4.87522797119999997e-04, -4.89379124979999946e-04, -5.04071434970000047e-04, -5.22656429719999959e-04,22+ -0.00048752279712, -0.00048937912498, -0.00050407143497, -0.00052265642972,
23- -5.46656563370000030e-04, -5.67780256129999956e-04, -5.87093048519999987e-04, -6.13274739379999958e-04,23+ -0.00054665656337, -0.00056778025613, -0.00058709304852, -0.00061327473938,
24- -6.31249353189999992e-04, -6.54033336209999989e-04, -6.77769077639999947e-04, -6.94161462730000039e-04,24+ -0.00063124935319, -0.00065403333621, -0.00067776907764, -0.00069416146273,
25- -7.15773647440000002e-04, -7.25504312220000042e-04, -7.44094185410000010e-04, -7.49059805319999975e-04,25+ -0.00071577364744, -0.00072550431222, -0.00074409418541, -0.00074905980532,
26- -7.68137192699999954e-04, -7.72484859490000044e-04, -7.83433228769999952e-04, -7.77986949269999996e-04,26+ -0.0007681371927, -0.00077248485949, -0.00078343322877, -0.00077798694927,
27- -7.80366470999999963e-04, -7.80144962570000029e-04, -7.75797733100000030e-04, -7.63079357570000034e-04,27+ -0.000780366471, -0.00078014496257, -0.0007757977331, -0.00076307935757,
28- -7.53000142009999985e-04, -7.31935715250000033e-04, -7.21539198759999986e-04, -6.91793753720000050e-04,28+ -0.00075300014201, -0.00073193571525, -0.00072153919876, -0.00069179375372,
29- -6.65041508930000035e-04, -6.34159490250000017e-04, -5.94611893300000041e-04, -5.56457639060000016e-04,29+ -0.00066504150893, -0.00063415949025, -0.0005946118933, -0.00055645763906,
30- -5.14557221080000023e-04, -4.60632548030000006e-04, -4.09512145219999985e-04, -3.50117587559999998e-04,30+ -0.00051455722108, -0.00046063254803, -0.00040951214522, -0.00035011758756,
31- -2.89698117479999975e-04, -2.09833734399999996e-04, -1.44638093489999996e-04, -6.17334407200000046e-05,31+ -0.00028969811748, -0.0002098337344, -0.00014463809349, -6.173344072e-05,
32- 1.34949741799999995e-05, 1.09438312739999999e-04, 2.04301706880000004e-04, 2.94953110410000024e-04,32+ 1.349497418e-05, 0.00010943831274, 0.00020430170688, 0.00029495311041,
33- 4.02654021600000011e-04, 5.10738849519999974e-04, 6.23937613909999957e-04, 7.45802588650000000e-04,33+ 0.0004026540216, 0.00051073884952, 0.00062393761391, 0.00074580258865,
34- 8.60844332620000052e-04, 9.88598830149999995e-04, 1.12501551306999994e-03, 1.25778846474999990e-03,34+ 0.00086084433262, 0.00098859883015, 0.00112501551307, 0.00125778846475,
35- 1.39024948271999991e-03, 1.54432198470999993e-03, 1.68680832531000000e-03, 1.83482654223999998e-03,35+ 0.00139024948272, 0.00154432198471, 0.00168680832531, 0.00183482654224,
36- 1.98411407369000021e-03, 2.14615835557000010e-03, 2.30172547746000005e-03, 2.46256169126000003e-03,36+ 0.00198411407369, 0.00214615835557, 0.00230172547746, 0.00246256169126,
37- 2.62017586901999982e-03, 2.78704643465000007e-03, 2.94694477164999993e-03, 3.11254206525000011e-03,37+ 0.00262017586902, 0.00278704643465, 0.00294694477165, 0.00311254206525,
38- 3.27396134846999996e-03, 3.44188741827999986e-03, 3.60082681231000019e-03, 3.76039229103999981e-03,38+ 0.00327396134847, 0.00344188741828, 0.00360082681231, 0.00376039229104,
39- 3.92074323702999977e-03, 4.08197531935000028e-03, 4.22642692269999988e-03, 4.37307196780999975e-03,39+ 0.00392074323703, 0.00408197531935, 0.0042264269227, 0.00437307196781,
40- 4.52098527825000023e-03, 4.66064606118000036e-03, 4.79325608497999968e-03, 4.91376035744999981e-03,40+ 0.00452098527825, 0.00466064606118, 0.00479325608498, 0.00491376035745,
41- 5.03930226012999985e-03, 5.14073539031999985e-03, 5.24611661323999990e-03, 5.34716811981999964e-03,41+ 0.00503930226013, 0.00514073539032, 0.00524611661324, 0.00534716811982,
42- 5.41967759306999971e-03, 5.48760401507000003e-03, 5.54757145088000028e-03, 5.59380230045000010e-03,42+ 0.00541967759307, 0.00548760401507, 0.00554757145088, 0.00559380230045,
43- 5.62206432097000011e-03, 5.64551969164000036e-03, 5.63891995151000018e-03, 5.62661141931999984e-03,43+ 0.00562206432097, 0.00564551969164, 0.00563891995151, 0.00562661141932,
44- 5.59171286630000004e-03, 5.54043639400000031e-03, 5.47537830770000039e-03, 5.38389758970000010e-03,44+ 0.0055917128663, 0.005540436394, 0.0054753783077, 0.0053838975897,
45- 5.27157587272000013e-03, 5.13822754514000040e-03, 4.98396877629000024e-03, 4.81094690599999982e-03,45+ 0.00527157587272, 0.00513822754514, 0.00498396877629, 0.004810946906,
46- 4.60395301470999975e-03, 4.38018617447000040e-03, 4.12516423269999963e-03, 3.84564081245999988e-03,46+ 0.00460395301471, 0.00438018617447, 0.0041251642327, 0.00384564081246,
47- 3.54012465506999994e-03, 3.20918858098000019e-03, 2.84467578623000001e-03, 2.45085400321000011e-03,47+ 0.00354012465507, 0.00320918858098, 0.00284467578623, 0.00245085400321,
48- 2.02741761850000002e-03, 1.57846825767999992e-03, 1.09023290512000001e-03, 5.83226424800000029e-04,48+ 0.0020274176185, 0.00157846825768, 0.00109023290512, 0.0005832264248,
49- 2.76045190500000009e-05, -5.46428086640000032e-04, -1.15681355226999994e-03, -1.80394725893000003e-03,49+ 2.760451905e-05, -0.00054642808664, -0.00115681355227, -0.00180394725893,
50- -2.48267236448999982e-03, -3.19337783899999996e-03, -3.94011240521999987e-03, -4.72225962399999959e-03,50+ -0.00248267236449, -0.003193377839, -0.00394011240522, -0.004722259624,
51- -5.53372111087999975e-03, -6.37922932685000034e-03, -7.26158168517000019e-03, -8.17982333726000044e-03,51+ -0.00553372111088, -0.00637922932685, -0.00726158168517, -0.00817982333726,
52- -9.13253296085000076e-03, -1.01150215498599996e-02, -1.11315548032100003e-02, -1.21849995950799993e-02,52+ -0.00913253296085, -0.01011502154986, -0.01113155480321, -0.01218499959508,
53- 1.32718220035100004e-02, 1.43904666079200001e-02, 1.55405553342300006e-02, 1.67324712998900005e-02,53+ 0.01327182200351, 0.01439046660792, 0.01554055533423, 0.01673247129989,
54- 1.79433381344300015e-02, 1.91872431369799999e-02, 2.04531793355499994e-02, 2.17467550253499994e-02,54+ 0.01794333813443, 0.01918724313698, 0.02045317933555, 0.02174675502535,
55- 2.30680169286200006e-02, 2.44160992028500008e-02, 2.57875847546699989e-02, 2.71859429632900010e-02,55+ 0.02306801692862, 0.02441609920285, 0.02578758475467, 0.02718594296329,
56- 2.86072173638499995e-02, 3.00502657427899993e-02, 3.15017608738899987e-02, 3.29754081033699978e-02,56+ 0.02860721736385, 0.03005026574279, 0.03150176087389, 0.03297540810337,
57- 3.44620948768599999e-02, 3.59697560554200005e-02, 3.74812850425199975e-02, 3.90053679474499995e-02,57+ 0.03446209487686, 0.03596975605542, 0.03748128504252, 0.03900536794745,
58- 4.05349170558400029e-02, 4.20649094636700027e-02, 4.36097542130400029e-02, 4.51488405641300022e-02,58+ 0.04053491705584, 0.04206490946367, 0.04360975421304, 0.04514884056413,
59- 4.66843027264199975e-02, 4.82165720067199988e-02, 4.97385755601399970e-02, 5.12556155521600026e-02,59+ 0.04668430272642, 0.04821657200672, 0.04973857556014, 0.05125561555216,
60- 5.27630746520700022e-02, 5.42452768358899981e-02, 5.57173648213799971e-02, 5.71616450129900019e-02,60+ 0.05276307465207, 0.05424527683589, 0.05571736482138, 0.05716164501299,
61- 5.85915683626000022e-02, 5.99837480176100002e-02, 6.13455171720699993e-02, 6.26857808117199933e-02,61+ 0.0585915683626, 0.05998374801761, 0.06134551717207, 0.06268578081172,
62- 6.39715898068100031e-02, 6.52247106438000046e-02, 6.64367512210399941e-02, 6.76075985122800011e-02,62+ 0.06397158980681, 0.0652247106438, 0.06643675122104, 0.06760759851228,
63- 6.87043828351199953e-02, 6.97630244712700021e-02, 7.07628710726599941e-02, 7.17002673110199995e-02,63+ 0.06870438283512, 0.06976302447127, 0.07076287107266, 0.07170026731102,
64- 7.25682583308299989e-02, 7.33620255080300043e-02, 7.41003642434199944e-02, 7.47452558119399979e-02,64+ 0.07256825833083, 0.07336202550803, 0.07410036424342, 0.07474525581194,
65- 7.53137336201900043e-02, 7.58008358658399939e-02, 7.61992479339600043e-02, 7.64992170411900041e-02,65+ 0.07531373362019, 0.07580083586584, 0.07619924793396, 0.07649921704119,
66- 7.67093490424499980e-02, 7.68173975696399974e-02, 7.68230011392300044e-02, 7.67204924174599984e-02,66+ 0.07670934904245, 0.07681739756964, 0.07682300113923, 0.07672049241746,
67- 7.65050718319399969e-02, 7.61748321853600030e-02, 7.57305756506100047e-02, 7.51576255287000061e-02,67+ 0.07650507183194, 0.07617483218536, 0.07573057565061, 0.0751576255287,
68- 7.44664394756399950e-02, 7.36406005762000049e-02, 7.26774642729900028e-02, 7.15826364790300013e-02,68+ 0.07446643947564, 0.0736406005762, 0.07267746427299, 0.07158263647903,
69- 7.03533073509299972e-02, 6.89664013195099984e-02, 6.74525021516600015e-02, 6.57690668650799948e-02,69+ 0.07035330735093, 0.06896640131951, 0.06745250215166, 0.06576906686508,
70- 6.39444805963299973e-02, 6.19602779038700008e-02, 5.98166570808999973e-02, 5.75152691986699979e-02,70+ 0.06394448059633, 0.06196027790387, 0.0598166570809, 0.05751526919867,
71- 5.50460034300900014e-02, 5.24093821736600005e-02, 4.95978676344500033e-02, 4.66303305170100019e-02,71+ 0.05504600343009, 0.05240938217366, 0.04959786763445, 0.04663033051701,
72- 4.34768782195799966e-02, 4.01458278412700001e-02, 3.66418116813300027e-02, 3.29583930669100009e-02,72+ 0.04347687821958, 0.04014582784127, 0.03664181168133, 0.03295839306691,
73- 2.90824006012499990e-02, 2.50307561890899984e-02, 2.07997072862199997e-02, 1.63701258222800003e-02,73+ 0.02908240060125, 0.02503075618909, 0.02079970728622, 0.01637012582228,
74- 1.17623832785699999e-02, 6.96368621616999962e-03, 1.97656014503000020e-03, -3.20868968303999981e-03,74+ 0.01176238327857, 0.00696368621617, 0.00197656014503, -0.00320868968304,
75- -8.57117491365999920e-03, -1.41288827355800003e-02, -1.98834129257299992e-02, -2.58227288806400015e-02,75+ -0.00857117491366, -0.01412888273558, -0.01988341292573, -0.02582272888064,
76- -3.19531274533199974e-02, -3.82776572082200034e-02, -4.47806821585600007e-02, -5.14804176793400015e-02,76+ -0.03195312745332, -0.03827765720822, -0.04478068215856, -0.05148041767934,
77- -5.83705326833600033e-02, -6.54409853135899944e-02, -7.26943300812900040e-02, -8.01372934427899974e-02,77+ -0.05837053268336, -0.06544098531359, -0.07269433008129, -0.08013729344279,
78- -8.77547536559299957e-02, -9.55533352891400067e-02, -1.03532953114629997e-01, -1.11682693177299994e-01,78+ -0.08775475365593, -0.09555333528914, -0.10353295311463, -0.1116826931773,
79- -1.20007798467999999e-01, -1.28500285038779999e-01, -1.37155176119340000e-01, -1.45976649118700008e-01,79+ -0.120007798468, -0.12850028503878, -0.13715517611934, -0.1459766491187,
80- -1.54960707106050005e-01, -1.64095885566689997e-01, -1.73380817217060001e-01, -1.82817254851420002e-01,80+ -0.15496070710605, -0.16409588556669, -0.17338081721706, -0.18281725485142,
81- -1.92396674572670012e-01, -2.02125017681030000e-01, -2.11973585380559992e-01, -2.21965269641489993e-01,81+ -0.19239667457267, -0.20212501768103, -0.21197358538056, -0.22196526964149,
82- -2.32069087067909990e-01, -2.42301688459740011e-01, -2.52648030957219993e-01, -2.63105329946029975e-01,82+ -0.23206908706791, -0.24230168845974, -0.25264803095722, -0.26310532994603,
83- -2.73663404056250004e-01, -2.84321418910849999e-01, -2.95071671706459981e-01, -3.05909857519160000e-01,83+ -0.27366340405625, -0.28432141891085, -0.29507167170646, -0.30590985751916,
84- -3.16827891364560021e-01, -3.27811372721049987e-01, -3.38872269386649994e-01, -3.49991412293099990e-01,84+ -0.31682789136456, -0.32781137272105, -0.33887226938665, -0.3499914122931,
85- 3.61158990313549977e-01, 3.72379554630610010e-01, 3.83635001390429997e-01, 3.94921176156749987e-01,85+ 0.36115899031355, 0.37237955463061, 0.38363500139043, 0.39492117615675,
86- 4.06231767676250022e-01, 4.17569689684089973e-01, 4.28911992073729986e-01, 4.40255375436649998e-01,86+ 0.40623176767625, 0.41756968968409, 0.42891199207373, 0.44025537543665,
87- 4.51599653568240000e-01, 4.62930808527570015e-01, 4.74245321461150005e-01, 4.85525309110990011e-01,87+ 0.45159965356824, 0.46293080852757, 0.47424532146115, 0.48552530911099,
88- 4.96770825457070020e-01, 5.07981750004339982e-01, 5.19123497023910030e-01, 5.30224089568550050e-01,88+ 0.49677082545707, 0.50798175000434, 0.51912349702391, 0.53022408956855,
89- 5.41255344873220023e-01, 5.52205125850609990e-01, 5.63078914013700027e-01, 5.73852413169229969e-01,89+ 0.54125534487322, 0.55220512585061, 0.5630789140137, 0.57385241316923,
90- 5.84540323546789975e-01, 5.95112308624960007e-01, 6.05578353891800036e-01, 6.15910993202909984e-01,90+ 0.58454032354679, 0.59511230862496, 0.6055783538918, 0.61591099320291,
91- 6.26124269560550006e-01, 6.36198010772859979e-01, 6.46126969594610023e-01, 6.55901630246709999e-01,91+ 0.62612426956055, 0.63619801077286, 0.64612696959461, 0.65590163024671,
92- 6.65513988016270042e-01, 6.74966319017120009e-01, 6.84235329345979970e-01, 6.93328237670320036e-01,92+ 0.66551398801627, 0.67496631901712, 0.68423532934598, 0.69332823767032,
93- 7.02238871935390030e-01, 7.10941042630950037e-01, 7.19446263495610028e-01, 7.27744890029940028e-01,93+ 0.70223887193539, 0.71094104263095, 0.71944626349561, 0.72774489002994,
94- 7.35821175827690022e-01, 7.43682786364880055e-01, 7.51313745612369965e-01, 7.58708076082419969e-01,94+ 0.73582117582769, 0.74368278636488, 0.75131374561237, 0.75870807608242,
95- 7.65867486509389961e-01, 7.72778088133269980e-01, 7.79428751902159989e-01, 7.85835312039199985e-01,95+ 0.76586748650939, 0.77277808813327, 0.77942875190216, 0.7858353120392,
96- 7.91973584164240019e-01, 7.97846641377000010e-01, 8.03448575185049974e-01, 8.08769500444910028e-01,96+ 0.79197358416424, 0.797846641377, 0.80344857518505, 0.80876950044491,
97- 8.13819127062169967e-01, 8.18577600464679977e-01, 8.23041989054089984e-01, 8.27227534733600001e-01,97+ 0.81381912706217, 0.81857760046468, 0.82304198905409, 0.8272275347336,
98- 8.31103845715200018e-01, 8.34693736184019985e-01, 8.37971733788649975e-01, 8.40954139247219956e-01,98+ 0.8311038457152, 0.83469373618402, 0.83797173378865, 0.84095413924722,
99- 8.43623828120049990e-01, 8.45981846982060026e-01, 8.48031577707630047e-01, 8.49780519842679993e-01,99+ 0.84362382812005, 0.84598184698206, 0.84803157770763, 0.84978051984268,
100- 8.51197152493429976e-01, 8.52304703521470031e-01, 8.53102094970169977e-01, 8.53572057391070005e-01,100+ 0.85119715249343, 0.85230470352147, 0.85310209497017, 0.85357205739107,
101- 8.53738560059369989e-01, 8.53572057391070005e-01, 8.53102094970169977e-01, 8.52304703521470031e-01,101+ 0.85373856005937, 0.85357205739107, 0.85310209497017, 0.85230470352147,
102- 8.51197152493429976e-01, 8.49780519842679993e-01, 8.48031577707630047e-01, 8.45981846982060026e-01,102+ 0.85119715249343, 0.84978051984268, 0.84803157770763, 0.84598184698206,
103- 8.43623828120049990e-01, 8.40954139247219956e-01, 8.37971733788649975e-01, 8.34693736184019985e-01,103+ 0.84362382812005, 0.84095413924722, 0.83797173378865, 0.83469373618402,
104- 8.31103845715200018e-01, 8.27227534733600001e-01, 8.23041989054089984e-01, 8.18577600464679977e-01,104+ 0.8311038457152, 0.8272275347336, 0.82304198905409, 0.81857760046468,
105- 8.13819127062169967e-01, 8.08769500444910028e-01, 8.03448575185049974e-01, 7.97846641377000010e-01,105+ 0.81381912706217, 0.80876950044491, 0.80344857518505, 0.797846641377,
106- 7.91973584164240019e-01, 7.85835312039199985e-01, 7.79428751902159989e-01, 7.72778088133269980e-01,106+ 0.79197358416424, 0.7858353120392, 0.77942875190216, 0.77277808813327,
107- 7.65867486509389961e-01, 7.58708076082419969e-01, 7.51313745612369965e-01, 7.43682786364880055e-01,107+ 0.76586748650939, 0.75870807608242, 0.75131374561237, 0.74368278636488,
108- 7.35821175827690022e-01, 7.27744890029940028e-01, 7.19446263495610028e-01, 7.10941042630950037e-01,108+ 0.73582117582769, 0.72774489002994, 0.71944626349561, 0.71094104263095,
109- 7.02238871935390030e-01, 6.93328237670320036e-01, 6.84235329345979970e-01, 6.74966319017120009e-01,109+ 0.70223887193539, 0.69332823767032, 0.68423532934598, 0.67496631901712,
110- 6.65513988016270042e-01, 6.55901630246709999e-01, 6.46126969594610023e-01, 6.36198010772859979e-01,110+ 0.66551398801627, 0.65590163024671, 0.64612696959461, 0.63619801077286,
111- 6.26124269560550006e-01, 6.15910993202909984e-01, 6.05578353891800036e-01, 5.95112308624960007e-01,111+ 0.62612426956055, 0.61591099320291, 0.6055783538918, 0.59511230862496,
112- 5.84540323546789975e-01, 5.73852413169229969e-01, 5.63078914013700027e-01, 5.52205125850609990e-01,112+ 0.58454032354679, 0.57385241316923, 0.5630789140137, 0.55220512585061,
113- 5.41255344873220023e-01, 5.30224089568550050e-01, 5.19123497023910030e-01, 5.07981750004339982e-01,113+ 0.54125534487322, 0.53022408956855, 0.51912349702391, 0.50798175000434,
114- 4.96770825457070020e-01, 4.85525309110990011e-01, 4.74245321461150005e-01, 4.62930808527570015e-01,114+ 0.49677082545707, 0.48552530911099, 0.47424532146115, 0.46293080852757,
115- 4.51599653568240000e-01, 4.40255375436649998e-01, 4.28911992073729986e-01, 4.17569689684089973e-01,115+ 0.45159965356824, 0.44025537543665, 0.42891199207373, 0.41756968968409,
116- 4.06231767676250022e-01, 3.94921176156749987e-01, 3.83635001390429997e-01, 3.72379554630610010e-01,116+ 0.40623176767625, 0.39492117615675, 0.38363500139043, 0.37237955463061,
117- -3.61158990313549977e-01, -3.49991412293099990e-01, -3.38872269386649994e-01, -3.27811372721049987e-01,117+ -0.36115899031355, -0.3499914122931, -0.33887226938665, -0.32781137272105,
118- -3.16827891364560021e-01, -3.05909857519160000e-01, -2.95071671706459981e-01, -2.84321418910849999e-01,118+ -0.31682789136456, -0.30590985751916, -0.29507167170646, -0.28432141891085,
119- -2.73663404056250004e-01, -2.63105329946029975e-01, -2.52648030957219993e-01, -2.42301688459740011e-01,119+ -0.27366340405625, -0.26310532994603, -0.25264803095722, -0.24230168845974,
120- -2.32069087067909990e-01, -2.21965269641489993e-01, -2.11973585380559992e-01, -2.02125017681030000e-01,120+ -0.23206908706791, -0.22196526964149, -0.21197358538056, -0.20212501768103,
121- -1.92396674572670012e-01, -1.82817254851420002e-01, -1.73380817217060001e-01, -1.64095885566689997e-01,121+ -0.19239667457267, -0.18281725485142, -0.17338081721706, -0.16409588556669,
122- -1.54960707106050005e-01, -1.45976649118700008e-01, -1.37155176119340000e-01, -1.28500285038779999e-01,122+ -0.15496070710605, -0.1459766491187, -0.13715517611934, -0.12850028503878,
123- -1.20007798467999999e-01, -1.11682693177299994e-01, -1.03532953114629997e-01, -9.55533352891400067e-02,123+ -0.120007798468, -0.1116826931773, -0.10353295311463, -0.09555333528914,
124- -8.77547536559299957e-02, -8.01372934427899974e-02, -7.26943300812900040e-02, -6.54409853135899944e-02,124+ -0.08775475365593, -0.08013729344279, -0.07269433008129, -0.06544098531359,
125- -5.83705326833600033e-02, -5.14804176793400015e-02, -4.47806821585600007e-02, -3.82776572082200034e-02,125+ -0.05837053268336, -0.05148041767934, -0.04478068215856, -0.03827765720822,
126- -3.19531274533199974e-02, -2.58227288806400015e-02, -1.98834129257299992e-02, -1.41288827355800003e-02,126+ -0.03195312745332, -0.02582272888064, -0.01988341292573, -0.01412888273558,
127- -8.57117491365999920e-03, -3.20868968303999981e-03, 1.97656014503000020e-03, 6.96368621616999962e-03,127+ -0.00857117491366, -0.00320868968304, 0.00197656014503, 0.00696368621617,
128- 1.17623832785699999e-02, 1.63701258222800003e-02, 2.07997072862199997e-02, 2.50307561890899984e-02,128+ 0.01176238327857, 0.01637012582228, 0.02079970728622, 0.02503075618909,
129- 2.90824006012499990e-02, 3.29583930669100009e-02, 3.66418116813300027e-02, 4.01458278412700001e-02,129+ 0.02908240060125, 0.03295839306691, 0.03664181168133, 0.04014582784127,
130- 4.34768782195799966e-02, 4.66303305170100019e-02, 4.95978676344500033e-02, 5.24093821736600005e-02,130+ 0.04347687821958, 0.04663033051701, 0.04959786763445, 0.05240938217366,
131- 5.50460034300900014e-02, 5.75152691986699979e-02, 5.98166570808999973e-02, 6.19602779038700008e-02,131+ 0.05504600343009, 0.05751526919867, 0.0598166570809, 0.06196027790387,
132- 6.39444805963299973e-02, 6.57690668650799948e-02, 6.74525021516600015e-02, 6.89664013195099984e-02,132+ 0.06394448059633, 0.06576906686508, 0.06745250215166, 0.06896640131951,
133- 7.03533073509299972e-02, 7.15826364790300013e-02, 7.26774642729900028e-02, 7.36406005762000049e-02,133+ 0.07035330735093, 0.07158263647903, 0.07267746427299, 0.0736406005762,
134- 7.44664394756399950e-02, 7.51576255287000061e-02, 7.57305756506100047e-02, 7.61748321853600030e-02,134+ 0.07446643947564, 0.0751576255287, 0.07573057565061, 0.07617483218536,
135- 7.65050718319399969e-02, 7.67204924174599984e-02, 7.68230011392300044e-02, 7.68173975696399974e-02,135+ 0.07650507183194, 0.07672049241746, 0.07682300113923, 0.07681739756964,
136- 7.67093490424499980e-02, 7.64992170411900041e-02, 7.61992479339600043e-02, 7.58008358658399939e-02,136+ 0.07670934904245, 0.07649921704119, 0.07619924793396, 0.07580083586584,
137- 7.53137336201900043e-02, 7.47452558119399979e-02, 7.41003642434199944e-02, 7.33620255080300043e-02,137+ 0.07531373362019, 0.07474525581194, 0.07410036424342, 0.07336202550803,
138- 7.25682583308299989e-02, 7.17002673110199995e-02, 7.07628710726599941e-02, 6.97630244712700021e-02,138+ 0.07256825833083, 0.07170026731102, 0.07076287107266, 0.06976302447127,
139- 6.87043828351199953e-02, 6.76075985122800011e-02, 6.64367512210399941e-02, 6.52247106438000046e-02,139+ 0.06870438283512, 0.06760759851228, 0.06643675122104, 0.0652247106438,
140- 6.39715898068100031e-02, 6.26857808117199933e-02, 6.13455171720699993e-02, 5.99837480176100002e-02,140+ 0.06397158980681, 0.06268578081172, 0.06134551717207, 0.05998374801761,
141- 5.85915683626000022e-02, 5.71616450129900019e-02, 5.57173648213799971e-02, 5.42452768358899981e-02,141+ 0.0585915683626, 0.05716164501299, 0.05571736482138, 0.05424527683589,
142- 5.27630746520700022e-02, 5.12556155521600026e-02, 4.97385755601399970e-02, 4.82165720067199988e-02,142+ 0.05276307465207, 0.05125561555216, 0.04973857556014, 0.04821657200672,
143- 4.66843027264199975e-02, 4.51488405641300022e-02, 4.36097542130400029e-02, 4.20649094636700027e-02,143+ 0.04668430272642, 0.04514884056413, 0.04360975421304, 0.04206490946367,
144- 4.05349170558400029e-02, 3.90053679474499995e-02, 3.74812850425199975e-02, 3.59697560554200005e-02,144+ 0.04053491705584, 0.03900536794745, 0.03748128504252, 0.03596975605542,
145- 3.44620948768599999e-02, 3.29754081033699978e-02, 3.15017608738899987e-02, 3.00502657427899993e-02,145+ 0.03446209487686, 0.03297540810337, 0.03150176087389, 0.03005026574279,
146- 2.86072173638499995e-02, 2.71859429632900010e-02, 2.57875847546699989e-02, 2.44160992028500008e-02,146+ 0.02860721736385, 0.02718594296329, 0.02578758475467, 0.02441609920285,
147- 2.30680169286200006e-02, 2.17467550253499994e-02, 2.04531793355499994e-02, 1.91872431369799999e-02,147+ 0.02306801692862, 0.02174675502535, 0.02045317933555, 0.01918724313698,
148- 1.79433381344300015e-02, 1.67324712998900005e-02, 1.55405553342300006e-02, 1.43904666079200001e-02,148+ 0.01794333813443, 0.01673247129989, 0.01554055533423, 0.01439046660792,
149- -1.32718220035100004e-02, -1.21849995950799993e-02, -1.11315548032100003e-02, -1.01150215498599996e-02,149+ -0.01327182200351, -0.01218499959508, -0.01113155480321, -0.01011502154986,
150- -9.13253296085000076e-03, -8.17982333726000044e-03, -7.26158168517000019e-03, -6.37922932685000034e-03,150+ -0.00913253296085, -0.00817982333726, -0.00726158168517, -0.00637922932685,
151- -5.53372111087999975e-03, -4.72225962399999959e-03, -3.94011240521999987e-03, -3.19337783899999996e-03,151+ -0.00553372111088, -0.004722259624, -0.00394011240522, -0.003193377839,
152- -2.48267236448999982e-03, -1.80394725893000003e-03, -1.15681355226999994e-03, -5.46428086640000032e-04,152+ -0.00248267236449, -0.00180394725893, -0.00115681355227, -0.00054642808664,
153- 2.76045190500000009e-05, 5.83226424800000029e-04, 1.09023290512000001e-03, 1.57846825767999992e-03,153+ 2.760451905e-05, 0.0005832264248, 0.00109023290512, 0.00157846825768,
154- 2.02741761850000002e-03, 2.45085400321000011e-03, 2.84467578623000001e-03, 3.20918858098000019e-03,154+ 0.0020274176185, 0.00245085400321, 0.00284467578623, 0.00320918858098,
155- 3.54012465506999994e-03, 3.84564081245999988e-03, 4.12516423269999963e-03, 4.38018617447000040e-03,155+ 0.00354012465507, 0.00384564081246, 0.0041251642327, 0.00438018617447,
156- 4.60395301470999975e-03, 4.81094690599999982e-03, 4.98396877629000024e-03, 5.13822754514000040e-03,156+ 0.00460395301471, 0.004810946906, 0.00498396877629, 0.00513822754514,
157- 5.27157587272000013e-03, 5.38389758970000010e-03, 5.47537830770000039e-03, 5.54043639400000031e-03,157+ 0.00527157587272, 0.0053838975897, 0.0054753783077, 0.005540436394,
158- 5.59171286630000004e-03, 5.62661141931999984e-03, 5.63891995151000018e-03, 5.64551969164000036e-03,158+ 0.0055917128663, 0.00562661141932, 0.00563891995151, 0.00564551969164,
159- 5.62206432097000011e-03, 5.59380230045000010e-03, 5.54757145088000028e-03, 5.48760401507000003e-03,159+ 0.00562206432097, 0.00559380230045, 0.00554757145088, 0.00548760401507,
160- 5.41967759306999971e-03, 5.34716811981999964e-03, 5.24611661323999990e-03, 5.14073539031999985e-03,160+ 0.00541967759307, 0.00534716811982, 0.00524611661324, 0.00514073539032,
161- 5.03930226012999985e-03, 4.91376035744999981e-03, 4.79325608497999968e-03, 4.66064606118000036e-03,161+ 0.00503930226013, 0.00491376035745, 0.00479325608498, 0.00466064606118,
162- 4.52098527825000023e-03, 4.37307196780999975e-03, 4.22642692269999988e-03, 4.08197531935000028e-03,162+ 0.00452098527825, 0.00437307196781, 0.0042264269227, 0.00408197531935,
163- 3.92074323702999977e-03, 3.76039229103999981e-03, 3.60082681231000019e-03, 3.44188741827999986e-03,163+ 0.00392074323703, 0.00376039229104, 0.00360082681231, 0.00344188741828,
164- 3.27396134846999996e-03, 3.11254206525000011e-03, 2.94694477164999993e-03, 2.78704643465000007e-03,164+ 0.00327396134847, 0.00311254206525, 0.00294694477165, 0.00278704643465,
165- 2.62017586901999982e-03, 2.46256169126000003e-03, 2.30172547746000005e-03, 2.14615835557000010e-03,165+ 0.00262017586902, 0.00246256169126, 0.00230172547746, 0.00214615835557,
166- 1.98411407369000021e-03, 1.83482654223999998e-03, 1.68680832531000000e-03, 1.54432198470999993e-03,166+ 0.00198411407369, 0.00183482654224, 0.00168680832531, 0.00154432198471,
167- 1.39024948271999991e-03, 1.25778846474999990e-03, 1.12501551306999994e-03, 9.88598830149999995e-04,167+ 0.00139024948272, 0.00125778846475, 0.00112501551307, 0.00098859883015,
168- 8.60844332620000052e-04, 7.45802588650000000e-04, 6.23937613909999957e-04, 5.10738849519999974e-04,168+ 0.00086084433262, 0.00074580258865, 0.00062393761391, 0.00051073884952,
169- 4.02654021600000011e-04, 2.94953110410000024e-04, 2.04301706880000004e-04, 1.09438312739999999e-04,169+ 0.0004026540216, 0.00029495311041, 0.00020430170688, 0.00010943831274,
170- 1.34949741799999995e-05, -6.17334407200000046e-05, -1.44638093489999996e-04, -2.09833734399999996e-04,170+ 1.349497418e-05, -6.173344072e-05, -0.00014463809349, -0.0002098337344,
171- -2.89698117479999975e-04, -3.50117587559999998e-04, -4.09512145219999985e-04, -4.60632548030000006e-04,171+ -0.00028969811748, -0.00035011758756, -0.00040951214522, -0.00046063254803,
172- -5.14557221080000023e-04, -5.56457639060000016e-04, -5.94611893300000041e-04, -6.34159490250000017e-04,172+ -0.00051455722108, -0.00055645763906, -0.0005946118933, -0.00063415949025,
173- -6.65041508930000035e-04, -6.91793753720000050e-04, -7.21539198759999986e-04, -7.31935715250000033e-04,173+ -0.00066504150893, -0.00069179375372, -0.00072153919876, -0.00073193571525,
174- -7.53000142009999985e-04, -7.63079357570000034e-04, -7.75797733100000030e-04, -7.80144962570000029e-04,174+ -0.00075300014201, -0.00076307935757, -0.0007757977331, -0.00078014496257,
175- -7.80366470999999963e-04, -7.77986949269999996e-04, -7.83433228769999952e-04, -7.72484859490000044e-04,175+ -0.000780366471, -0.00077798694927, -0.00078343322877, -0.00077248485949,
176- -7.68137192699999954e-04, -7.49059805319999975e-04, -7.44094185410000010e-04, -7.25504312220000042e-04,176+ -0.0007681371927, -0.00074905980532, -0.00074409418541, -0.00072550431222,
177- -7.15773647440000002e-04, -6.94161462730000039e-04, -6.77769077639999947e-04, -6.54033336209999989e-04,177+ -0.00071577364744, -0.00069416146273, -0.00067776907764, -0.00065403333621,
178- -6.31249353189999992e-04, -6.13274739379999958e-04, -5.87093048519999987e-04, -5.67780256129999956e-04,178+ -0.00063124935319, -0.00061327473938, -0.00058709304852, -0.00056778025613,
179- -5.46656563370000030e-04, -5.22656429719999959e-04, -5.04071434970000047e-04, -4.89379124979999946e-04,179+ -0.00054665656337, -0.00052265642972, -0.00050407143497, -0.00048937912498,
180- -4.87522797119999997e-04, -4.94751808959999987e-04, -5.61769257379999957e-04, -5.52528650469999959e-04,180+ -0.00048752279712, -0.00049475180896, -0.00056176925738, -0.00055252865047,
181 ];181 ];
182 182
183 #[cfg(test)]183 #[cfg(test)]
@@ -196,9 +196,9 @@ mod tests {
196 argmax = i;196 argmax = i;
197 }197 }
198 }198 }
199- assert!((sum - 8.14630094365516442e+01).abs() < 1e-9, "sum={sum}");199+ assert!((sum - 81.46300943655164).abs() < 1e-9, "sum={sum}");
200- assert!((sum_sq - 6.40000000000000284e+01).abs() < 1e-9, "sum_sq={sum_sq}");200+ assert!((sum_sq - 64.00000000000003).abs() < 1e-9, "sum_sq={sum_sq}");
201- assert!((max - 8.53738560059369989e-01).abs() < 1e-12, "max={max}");201+ assert!((max - 0.85373856005937).abs() < 1e-12, "max={max}");
202 assert_eq!(argmax, 320);202 assert_eq!(argmax, 320);
203 }203 }
204 }204 }
crates/ec-aac/tests/common/mod.rsadded+18 -0
@@ -0,0 +1,18 @@
1+//! Helpers shared by the ec-aac test binaries that need them: `oracle`,
2+//! `obs_real_content`, `sbr_real_library` and the merged `it` binary.
3+
4+use std::path::{Path, PathBuf};
5+use std::process::Command;
6+
7+pub fn have_ffmpeg() -> bool {
8+ Command::new("ffmpeg")
9+ .arg("-version")
10+ .output()
11+ .map(|o| o.status.success())
12+ .unwrap_or(false)
13+}
14+
15+#[allow(dead_code)] // not used by the sbr_real_library binary
16+pub fn fixtures() -> PathBuf {
17+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
18+}
crates/ec-aac/tests/data/he/he_v1_51.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_51.m4aadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_51.s16added+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_mono.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_mono.m4aadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_mono.s16added+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_stereo.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_stereo.m4aadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v1_stereo.s16added+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v2_stereo.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v2_stereo.m4aadded+0 -0

Binary file changed

crates/ec-aac/tests/data/he/he_v2_stereo.s16added+0 -0

Binary file changed

crates/ec-aac/tests/data/heaac_44100_48k_implicit_2s.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/ps_44100_music.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/ps_44100_sine.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/ps_48000_music.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/data/ps_48000_sine.aacadded+0 -0

Binary file changed

crates/ec-aac/tests/it/common.rsadded+39 -0
@@ -0,0 +1,39 @@
1+//! Helpers shared by the merged `it` test modules.
2+
3+use std::path::{Path, PathBuf};
4+
5+pub fn fixture(name: &str) -> PathBuf {
6+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name)
7+}
8+
9+fn mean(a: &[f32]) -> f64 {
10+ a.iter().map(|v| f64::from(*v)).sum::<f64>() / a.len().max(1) as f64
11+}
12+
13+/// Zero-mean normalised correlation of two equal-length slices.
14+pub fn correlation(a: &[f32], b: &[f32]) -> f64 {
15+ let n = a.len().min(b.len());
16+ if n < 1024 {
17+ return 0.0;
18+ }
19+ let (a, b) = (&a[..n], &b[..n]);
20+ let (ma, mb) = (mean(a), mean(b));
21+ let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64);
22+ for (x, y) in a.iter().zip(b) {
23+ let x = f64::from(*x) - ma;
24+ let y = f64::from(*y) - mb;
25+ num += x * y;
26+ da += x * x;
27+ db += y * y;
28+ }
29+ let den = (da * db).sqrt();
30+ if den == 0.0 { 0.0 } else { num / den }
31+}
32+
33+pub fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
34+ let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
35+ for (i, &v) in samples.iter().enumerate() {
36+ planes[i % channels].push(v);
37+ }
38+ planes
39+}
crates/ec-aac/tests/it/he_parity.rsadded+162 -0
@@ -0,0 +1,162 @@
1+//! HE-AAC v1 (SBR) and v2 (Parametric Stereo) parity against FFmpeg, from stored references.
2+//!
3+//! Fixtures live in `tests/data/he/` and are generated by `scripts/aac-tables/make-he-fixtures.sh`.
4+//! Each stream is written as ADTS (`.aac`) and MP4 (`.m4a`). The reference is FFmpeg's own decode
5+//! of the `.aac`, stored next to it as signed 16-bit little-endian PCM (`.s16`), in FFmpeg's channel
6+//! count and order. Nothing here runs FFmpeg, so the test needs neither FFmpeg nor the fdk-aac
7+//! library.
8+//!
9+//! Acceptance: every channel of every container must correlate with the matching reference channel
10+//! at least `MIN_CORR` at the best lag in `-LAG_MAX..=LAG_MAX`, and the channel count and sample rate
11+//! must equal FFmpeg's. The lag search absorbs the decoder's start-up delay, and a swapped channel
12+//! fails because each fixture gives every channel a different signal.
13+
14+use crate::common::deinterleave;
15+use crate::common::correlation;
16+use std::fs::File;
17+use std::io::BufReader;
18+use std::path::{Path, PathBuf};
19+
20+use ec_aac::AacDecoder;
21+use ec_core::{CodecId, Demuxer, Packet};
22+use ec_mp4::Mp4Demuxer;
23+
24+/// Per-channel correlation the reconstruction must reach against FFmpeg.
25+const MIN_CORR: f64 = 0.999;
26+/// Lag search bound, in samples, applied to each direction.
27+const LAG_MAX: i64 = 4096;
28+/// Window (in samples) the coarse lag search correlates over, and where it starts.
29+const WINDOW: usize = 8_192;
30+const WINDOW_START: usize = 4_096;
31+
32+/// One fixture: its base name, the channel count and sample rate FFmpeg decodes it to.
33+struct Fixture {
34+ name: &'static str,
35+ channels: usize,
36+ rate: u32,
37+}
38+
39+/// FFmpeg decodes the mono HE-AAC v1 stream as two identical channels ("Treating HE-AAC mono as
40+/// stereo"), so its reference has two channels. The 5.1 stream has six.
41+const FIXTURES: &[Fixture] = &[
42+ Fixture { name: "he_v1_mono", channels: 2, rate: 22_050 },
43+ Fixture { name: "he_v1_stereo", channels: 2, rate: 22_050 },
44+ Fixture { name: "he_v1_51", channels: 6, rate: 22_050 },
45+ Fixture { name: "he_v2_stereo", channels: 2, rate: 22_050 },
46+];
47+
48+fn data_dir() -> PathBuf {
49+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/he")
50+}
51+
52+/// FFmpeg's decode of the fixture, de-interleaved, scaled to [-1, 1].
53+fn reference(fixture: &Fixture) -> Vec<Vec<f32>> {
54+ let path = data_dir().join(format!("{}.s16", fixture.name));
55+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
56+ let samples: Vec<f32> = bytes
57+ .chunks(2)
58+ .filter(|b| b.len() == 2)
59+ .map(|b| f32::from(i16::from_le_bytes([b[0], b[1]])) / 32768.0)
60+ .collect();
61+ deinterleave(&samples, fixture.channels)
62+}
63+
64+/// Decodes the `.aac` (ADTS) file in one call.
65+fn decode_adts(path: &Path) -> (u16, u32, Vec<f32>) {
66+ let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
67+ let audio = AacDecoder::new()
68+ .decode(&bytes, None)
69+ .unwrap_or_else(|e| panic!("{}: decode failed: {e:?}", path.display()));
70+ (audio.channels, audio.sample_rate, audio.samples)
71+}
72+
73+/// Decodes the `.m4a` file access unit by access unit, using the `esds` AudioSpecificConfig.
74+fn decode_m4a(path: &Path) -> (u16, u32, Vec<f32>) {
75+ let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("mp4 opens")))
76+ .unwrap_or_else(|e| panic!("{}: mp4 parse failed: {e:?}", path.display()));
77+ let (idx, asc) = {
78+ let aac = demux
79+ .streams()
80+ .iter()
81+ .find(|s| s.params.codec == CodecId::Aac)
82+ .expect("mp4 has an AAC track");
83+ let asc = aac.params.extradata.as_ref().expect("esds carries the ASC").to_vec();
84+ (aac.index, asc)
85+ };
86+ let mut decoder = AacDecoder::with_config_bytes(&asc).expect("ASC parses");
87+ let (mut channels, mut rate, mut samples) = (0u16, 0u32, Vec::new());
88+ while let Ok(Packet { stream, data, .. }) = demux.next_packet() {
89+ if stream != idx {
90+ continue;
91+ }
92+ let frame = decoder
93+ .decode(&data, None)
94+ .unwrap_or_else(|e| panic!("{}: access unit failed: {e:?}", path.display()));
95+ channels = frame.channels;
96+ rate = frame.sample_rate;
97+ samples.extend_from_slice(&frame.samples);
98+ }
99+ (channels, rate, samples)
100+}
101+
102+/// The overlap of `ours` and `theirs` at `lag`: `ours[i]` pairs with `theirs[i + lag]`.
103+fn aligned<'a>(ours: &'a [f32], theirs: &'a [f32], lag: i64) -> (&'a [f32], &'a [f32]) {
104+ let (a0, b0) = if lag >= 0 { (0usize, lag as usize) } else { ((-lag) as usize, 0usize) };
105+ let n = ours.len().saturating_sub(a0).min(theirs.len().saturating_sub(b0));
106+ (&ours[a0..a0 + n], &theirs[b0..b0 + n])
107+}
108+
109+/// The best lag in `-LAG_MAX..=LAG_MAX`, found on a window past the start-up transient, then
110+/// measured as the correlation over the full overlap at that lag. A winning lag on the bound is
111+/// refused: the true alignment may lie outside the search.
112+fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
113+ let mut best = (0i64, 0.0f64);
114+ for lag in -LAG_MAX..=LAG_MAX {
115+ let (a, b) = aligned(ours, theirs, lag);
116+ if a.len() < WINDOW_START + WINDOW {
117+ continue;
118+ }
119+ let c = correlation(&a[WINDOW_START..WINDOW_START + WINDOW], &b[WINDOW_START..WINDOW_START + WINDOW]);
120+ if c.abs() > best.1.abs() {
121+ best = (lag, c);
122+ }
123+ }
124+ assert!(best.0.abs() < LAG_MAX, "winning lag {} sits at the search bound", best.0);
125+ let (a, b) = aligned(ours, theirs, best.0);
126+ (best.0, correlation(a, b))
127+}
128+
129+#[test]
130+fn he_fixtures_match_ffmpeg_per_channel() {
131+ let mut failures = Vec::new();
132+ for fixture in FIXTURES {
133+ let theirs = reference(fixture);
134+ for (container, ext) in [("adts", "aac"), ("m4a", "m4a")] {
135+ let path = data_dir().join(format!("{}.{ext}", fixture.name));
136+ assert!(path.exists(), "fixture {} is absent", path.display());
137+ let (channels, rate, samples) =
138+ if ext == "aac" { decode_adts(&path) } else { decode_m4a(&path) };
139+ let label = format!("{} {container}", fixture.name);
140+ if usize::from(channels) != fixture.channels || rate != fixture.rate {
141+ failures.push(format!(
142+ "{label}: decoded {channels} ch at {rate} Hz, FFmpeg {} ch at {} Hz",
143+ fixture.channels, fixture.rate
144+ ));
145+ continue;
146+ }
147+ let ours = deinterleave(&samples, fixture.channels);
148+ for ch in 0..fixture.channels {
149+ let (lag, corr) = best_lag(&ours[ch], &theirs[ch]);
150+ println!(
151+ "he {label} ch{ch}: ours {} frames, ffmpeg {} frames, lag {lag}, corr {corr:.6}",
152+ ours[ch].len(),
153+ theirs[ch].len()
154+ );
155+ if corr < MIN_CORR {
156+ failures.push(format!("{label} ch{ch}: corr {corr:.6} < {MIN_CORR}"));
157+ }
158+ }
159+ }
160+ }
161+ assert!(failures.is_empty(), "HE-AAC does not match ffmpeg:\n{}", failures.join("\n"));
162+}
crates/ec-aac/tests/it/implicit_ps.rsadded+39 -0
@@ -0,0 +1,39 @@
1+//! Implicit Parametric Stereo: an ADTS stream whose headers say plain AAC-LC,
2+//! and whose SBR extension carries a PS extension, is HE-AACv2 by its payload.
3+//! `ps_implicit` reports it once that PS extension has been decoded.
4+
5+use std::path::Path;
6+
7+use ec_aac::AacDecoder;
8+
9+#[test]
10+fn implicit_he_aac_v2_reports_implicit_ps() {
11+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/he/he_v2_stereo.aac");
12+ let data = std::fs::read(&path).expect("he_v2_stereo.aac is committed");
13+
14+ let mut decoder = AacDecoder::new();
15+ decoder.decode(&data, None).expect("the stream decodes");
16+
17+ assert!(
18+ decoder.sbr_implicit(),
19+ "the SBR payload switches implicit SBR on"
20+ );
21+ assert!(
22+ decoder.ps_implicit(),
23+ "the PS extension is seen in an implicit stream"
24+ );
25+}
26+
27+#[test]
28+fn explicit_he_aac_v1_has_no_implicit_ps() {
29+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/he/he_v1_stereo.aac");
30+ let data = std::fs::read(&path).expect("he_v1_stereo.aac is committed");
31+
32+ let mut decoder = AacDecoder::new();
33+ decoder.decode(&data, None).expect("the stream decodes");
34+
35+ assert!(
36+ !decoder.ps_implicit(),
37+ "a v1 stream carries no PS extension"
38+ );
39+}
crates/ec-aac/tests/it/implicit_sbr.rsadded+222 -0
@@ -0,0 +1,222 @@
1+//! Implicit SBR signalling (ISO/IEC 14496-3 1.6.5.2): a stream whose config or
2+//! ADTS header says plain AAC-LC, but whose frames carry an SBR extension
3+//! payload, is decoded as HE-AAC at twice the core rate, as ffmpeg does.
4+
5+use crate::shared::fixtures;
6+use crate::shared::have_ffmpeg;
7+use std::path::{Path, PathBuf};
8+use std::process::Command;
9+
10+use ec_aac::{AacDecoder, SbrSupport};
11+
12+/// Same contract as `oracle.rs`: an absent fixture skips loudly, and under
13+/// `EC_REQUIRE_FIXTURES=1` it is a hard failure instead.
14+fn require_fixture(path: &Path) -> bool {
15+ let present = path.exists();
16+ assert!(
17+ present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
18+ "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
19+ path.display()
20+ );
21+ if !present {
22+ eprintln!("SKIP: fixture {} absent", path.display());
23+ }
24+ present
25+}
26+
27+/// The implicit-signalling HE-AAC fixture: 2 s of `heaac_44100_48k.m4a` remuxed to
28+/// bare ADTS with `ffmpeg -c copy -f adts`. Its headers say AAC-LC at 22050 Hz.
29+fn implicit_fixture() -> PathBuf {
30+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/heaac_44100_48k_implicit_2s.aac")
31+}
32+
33+/// ffmpeg's decode of a file, as planar-by-channel `f32`.
34+fn ffmpeg_decode(path: &Path) -> Vec<Vec<f32>> {
35+ let out = Command::new("ffmpeg")
36+ .args(["-v", "error", "-i"])
37+ .arg(path)
38+ .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
39+ .output()
40+ .expect("ffmpeg runs");
41+ assert!(out.status.success(), "ffmpeg decode failed");
42+ let samples: Vec<f32> = out
43+ .stdout
44+ .as_chunks::<4>()
45+ .0
46+ .iter()
47+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
48+ .collect();
49+ deinterleave(&samples, 2)
50+}
51+
52+fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
53+ let mut out = vec![Vec::with_capacity(samples.len() / channels); channels];
54+ for (i, &v) in samples.iter().enumerate() {
55+ out[i % channels].push(v);
56+ }
57+ out
58+}
59+
60+/// Pearson correlation over the overlap of two channels.
61+fn correlation(a: &[f32], b: &[f32]) -> f64 {
62+ let n = a.len().min(b.len());
63+ assert!(n > 1024, "not enough overlap to compare: {n} samples");
64+ let (a, b) = (&a[..n], &b[..n]);
65+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
66+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
67+ let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
68+ for i in 0..n {
69+ let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
70+ num += x * y;
71+ da += x * x;
72+ db += y * y;
73+ }
74+ if da == 0.0 || db == 0.0 {
75+ return if da == db { 1.0 } else { 0.0 };
76+ }
77+ num / (da * db).sqrt()
78+}
79+
80+/// Decodes an ADTS file frame by frame, reading the output rate after each
81+/// frame, as a caller would. Returns the planes, the rate before the first
82+/// frame, and the rate after each frame.
83+fn decode_adts(path: &Path) -> (Vec<Vec<f32>>, Option<u32>, Vec<u32>, AacDecoder) {
84+ let data = std::fs::read(path).expect("fixture readable");
85+ let mut decoder = AacDecoder::new();
86+ let before = decoder.output_sample_rate();
87+ let mut planes: Vec<Vec<f32>> = Vec::new();
88+ let mut rates = Vec::new();
89+ let mut at = 0usize;
90+ while at + 7 <= data.len() {
91+ let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
92+ let end = (at + header.frame_length).min(data.len());
93+ let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
94+ assert_eq!(
95+ Some(frame.sample_rate),
96+ decoder.output_sample_rate(),
97+ "a frame's rate must match the decoder's rate after that frame"
98+ );
99+ rates.push(frame.sample_rate);
100+ let ch = usize::from(frame.channels);
101+ if planes.is_empty() {
102+ planes = vec![Vec::new(); ch];
103+ }
104+ for (i, v) in frame.samples.iter().enumerate() {
105+ planes[i % ch].push(*v);
106+ }
107+ at = end;
108+ }
109+ (planes, before, rates, decoder)
110+}
111+
112+#[test]
113+fn implicit_he_aac_adts_switches_to_double_rate() {
114+ let path = implicit_fixture();
115+ if !require_fixture(&path) {
116+ return;
117+ }
118+ let (ours, before, rates, decoder) = decode_adts(&path);
119+
120+ // Headers say 22050 Hz AAC-LC: nothing is known about the rate before frame 1.
121+ assert_eq!(before, None, "no output rate before the first frame");
122+ assert!(decoder.sbr_implicit(), "the SBR payload must switch implicit SBR on");
123+ assert_eq!(decoder.sbr_support(), SbrSupport::V1);
124+ assert_eq!(decoder.config().map(|c| c.sample_rate), None, "ADTS carries no config");
125+ assert_eq!(decoder.output_sample_rate(), Some(44_100));
126+
127+ // The first frame carries the payload, so it is already at the doubled rate.
128+ assert_eq!(rates[0], 44_100, "first frame is decoded with SBR");
129+ assert!(rates.iter().all(|&r| r == 44_100));
130+ assert_eq!(ours.len(), 2, "stereo");
131+ let frames = ours[0].len();
132+ assert!(frames > 80_000, "about 2 s at 44.1 kHz, got {frames}");
133+ assert_eq!(ours[1].len(), frames);
134+ for (ch, plane) in ours.iter().enumerate() {
135+ let rms = (plane.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / frames as f64).sqrt();
136+ assert!(rms > 1e-4, "channel {ch} is silent after SBR (rms {rms})");
137+ }
138+}
139+
140+#[test]
141+fn implicit_he_aac_adts_matches_ffmpeg_per_channel() {
142+ if !have_ffmpeg() {
143+ eprintln!("SKIP: ffmpeg not on PATH");
144+ return;
145+ }
146+ let path = implicit_fixture();
147+ if !require_fixture(&path) {
148+ return;
149+ }
150+ let (ours, _, _, _) = decode_adts(&path);
151+ let theirs = ffmpeg_decode(&path);
152+ assert_eq!(theirs.len(), ours.len());
153+ for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
154+ let c = correlation(a, b);
155+ assert!(c >= 0.999, "channel {ch}: correlation with ffmpeg {c:.6} < 0.999");
156+ }
157+}
158+
159+#[test]
160+fn plain_aac_lc_adts_is_unchanged_by_implicit_detection() {
161+ if !have_ffmpeg() {
162+ eprintln!("SKIP: ffmpeg not on PATH");
163+ return;
164+ }
165+ let path = fixtures().join("audio/aac-adts-stereo-44100.aac");
166+ if !require_fixture(&path) {
167+ return;
168+ }
169+ let (ours, _, rates, decoder) = decode_adts(&path);
170+
171+ // A plain LC stream has no SBR payload: no switch, and the rate stays at the core.
172+ assert!(!decoder.sbr_implicit());
173+ assert_eq!(decoder.sbr_support(), SbrSupport::NotSignalled);
174+ assert!(rates.iter().all(|&r| r == 44_100));
175+ assert_eq!(decoder.output_sample_rate(), Some(44_100));
176+
177+ let theirs = ffmpeg_decode(&path);
178+ for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
179+ let c = correlation(a, b);
180+ assert!(c >= 0.999, "channel {ch}: correlation with ffmpeg {c:.6} < 0.999");
181+ }
182+}
183+
184+/// Core-only decoding of the implicit HE-AAC stream: every frame carries an SBR
185+/// payload, and `core_only` must skip it, so the output stays at the 22050 Hz core
186+/// rate with 1024 samples per channel per frame. Before the switch existed, a
187+/// core-only measurement built with `with_config` re-armed implicit SBR and got the
188+/// doubled-rate full chain back, labelled as core.
189+#[test]
190+fn core_only_decode_of_implicit_he_aac_stays_at_core_rate() {
191+ let path = implicit_fixture();
192+ if !require_fixture(&path) {
193+ return;
194+ }
195+ let data = std::fs::read(&path).expect("fixture readable");
196+ let mut decoder = AacDecoder::new().core_only();
197+ let mut frames = 0usize;
198+ let mut at = 0usize;
199+ while at + 7 <= data.len() {
200+ let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
201+ let end = (at + header.frame_length).min(data.len());
202+ let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
203+ assert_eq!(
204+ frame.sample_rate, 22_050,
205+ "frame {frames} must stay at the core rate"
206+ );
207+ assert_eq!(
208+ frame.samples.len(),
209+ 1024 * usize::from(frame.channels),
210+ "frame {frames}: one core frame of 1024 samples per channel"
211+ );
212+ frames += 1;
213+ at = end;
214+ }
215+ assert!(frames > 0, "fixture has frames");
216+ assert!(
217+ !decoder.sbr_implicit(),
218+ "core-only must never arm implicit SBR"
219+ );
220+ assert_eq!(decoder.sbr_support(), SbrSupport::NotSignalled);
221+ assert_eq!(decoder.output_sample_rate(), Some(22_050));
222+}
crates/ec-aac/tests/it/main.rsadded+15 -0
@@ -0,0 +1,15 @@
1+#![forbid(unsafe_code)]
2+//! Merged integration tests for ec-aac: one module per former `tests/*.rs` file.
3+
4+#[path = "../common/mod.rs"]
5+mod shared;
6+mod common;
7+
8+mod he_parity;
9+mod implicit_ps;
10+mod implicit_sbr;
11+mod reelh_per_frame;
12+mod multichannel_parity;
13+mod no_panic;
14+mod ps_mp4;
15+mod ps_oracle;
crates/ec-aac/tests/it/multichannel_parity.rsadded+397 -0
@@ -0,0 +1,397 @@
1+//! AAC-LC multichannel parity against FFmpeg: mono, stereo, 5.1 and 7.1, in raw
2+//! ADTS and in mp4 (raw access units with an AudioSpecificConfig).
3+//!
4+//! Every fixture is a synthetic multitone with a distinct frequency per channel,
5+//! so a channel mapping error (SCE/CPE/LFE order, PCE, 7.1 config 7 vs 12) shows up
6+//! as a wrong per-channel correlation rather than passing silently.
7+//!
8+//! Each fixture is encoded by ffmpeg into a per-test temporary directory, decoded
9+//! by ec-aac, and decoded by ffmpeg as f32le. The two decodes are aligned on the
10+//! best integer lag (encoder and decoder priming differ between the two paths),
11+//! then each channel's correlation must reach 0.999. For 5.1 and 7.1 the channel
12+//! order is also checked: our channel k must correlate best with FFmpeg's channel k.
13+//!
14+//! Fixtures are generated at test time, so no media is committed. Without ffmpeg
15+//! the test skips loudly; with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg is a failure.
16+
17+use std::fs::File;
18+use std::io::BufReader;
19+use std::path::{Path, PathBuf};
20+use std::process::Command;
21+
22+use ec_aac::{AacDecoder, is_adts, parse_adts};
23+use ec_core::{CodecId, Demuxer, Packet};
24+use ec_mp4::Mp4Demuxer;
25+
26+const RATE: u32 = 48_000;
27+const SECONDS: u32 = 2;
28+/// Largest lag searched in either direction, in samples. Covers encoder delay
29+/// (1024 samples for AAC-LC) and the decoder's own priming with margin.
30+const LAG_MAX: i64 = 4096;
31+/// Samples used for the coarse lag search.
32+const LAG_WINDOW: usize = 8192;
33+const MIN_CORR: f64 = 0.999;
34+
35+#[derive(Clone, Copy, Debug)]
36+enum Container {
37+ Adts,
38+ Mp4,
39+}
40+
41+impl Container {
42+ fn label(self) -> &'static str {
43+ match self {
44+ Container::Adts => "adts",
45+ Container::Mp4 => "m4a",
46+ }
47+ }
48+ fn ext(self) -> &'static str {
49+ match self {
50+ Container::Adts => "aac",
51+ Container::Mp4 => "m4a",
52+ }
53+ }
54+ fn muxer(self) -> &'static str {
55+ match self {
56+ Container::Adts => "adts",
57+ Container::Mp4 => "mp4",
58+ }
59+ }
60+}
61+
62+/// One layout: ffmpeg channel-layout name, channel count, and a distinct tone per channel.
63+struct Layout {
64+ name: &'static str,
65+ channels: usize,
66+ /// Tone frequency per channel, in film order as ffmpeg lays it out.
67+ freqs: &'static [u32],
68+}
69+
70+const LAYOUTS: &[Layout] = &[
71+ Layout { name: "mono", channels: 1, freqs: &[300] },
72+ Layout { name: "stereo", channels: 2, freqs: &[300, 450] },
73+ Layout { name: "5.1", channels: 6, freqs: &[300, 450, 620, 780, 960, 1130] },
74+ Layout { name: "7.1", channels: 8, freqs: &[300, 450, 620, 780, 960, 1130, 1310, 1500] },
75+];
76+
77+/// The encoders under test. Native `aac` is always present; `libfdk_aac` is used
78+/// only when the local ffmpeg lists it.
79+const ENCODERS: &[&str] = &["aac", "libfdk_aac"];
80+
81+fn fixtures_dir() -> PathBuf {
82+ PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("aac_multichannel")
83+}
84+
85+fn ffmpeg_ok(args: &[&str]) -> bool {
86+ Command::new("ffmpeg")
87+ .args(args)
88+ .output()
89+ .map(|o| o.status.success())
90+ .unwrap_or(false)
91+}
92+
93+fn have_ffmpeg() -> bool {
94+ ffmpeg_ok(&["-version"])
95+}
96+
97+fn have_encoder(name: &str) -> bool {
98+ let out = Command::new("ffmpeg")
99+ .args(["-hide_banner", "-encoders"])
100+ .output();
101+ match out {
102+ Ok(o) => String::from_utf8_lossy(&o.stdout)
103+ .lines()
104+ .any(|l| l.split_whitespace().nth(1) == Some(name)),
105+ Err(_) => false,
106+ }
107+}
108+
109+/// Encodes a multitone of `layout` with `encoder` into `container`. Returns the path,
110+/// or `None` when the encoder refuses the configuration.
111+fn encode(layout: &Layout, encoder: &str, container: Container) -> Option<PathBuf> {
112+ let dir = fixtures_dir();
113+ std::fs::create_dir_all(&dir).expect("fixture dir");
114+ let out = dir.join(format!(
115+ "{}_{}_{}.{}",
116+ layout.name.replace('.', ""),
117+ encoder,
118+ container.label(),
119+ container.ext()
120+ ));
121+ let expr = layout
122+ .freqs
123+ .iter()
124+ .map(|f| format!("0.25*sin(2*PI*{f}*t)"))
125+ .collect::<Vec<_>>()
126+ .join("|");
127+ let source = format!(
128+ "aevalsrc={expr}:s={RATE}:d={SECONDS}:c={}",
129+ layout.name
130+ );
131+ // 48 kbit/s per channel keeps every layout in a comfortable quality range.
132+ let bitrate = format!("{}k", 48 * layout.channels);
133+ let status = Command::new("ffmpeg")
134+ .args(["-v", "error", "-y", "-f", "lavfi", "-i", &source])
135+ .args(["-c:a", encoder, "-profile:a", "aac_low", "-b:a", &bitrate])
136+ .args(["-ac", &layout.channels.to_string(), "-f", container.muxer()])
137+ .arg(&out)
138+ .status()
139+ .expect("ffmpeg runs");
140+ status.success().then_some(out)
141+}
142+
143+/// FFmpeg's decode of `path` as planar-by-channel `f32`, in its own channel order.
144+fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
145+ let out = Command::new("ffmpeg")
146+ .args(["-v", "error", "-i"])
147+ .arg(path)
148+ .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"])
149+ .arg(channels.to_string())
150+ .arg("-")
151+ .output()
152+ .expect("ffmpeg runs");
153+ assert!(
154+ out.status.success(),
155+ "ffmpeg decode of {} failed: {}",
156+ path.display(),
157+ String::from_utf8_lossy(&out.stderr)
158+ );
159+ let samples: Vec<f32> = out
160+ .stdout
161+ .as_chunks::<4>()
162+ .0
163+ .iter()
164+ .map(|c| f32::from_le_bytes(*c))
165+ .collect();
166+ deinterleave(&samples, channels)
167+}
168+
169+fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
170+ let mut planes = vec![Vec::with_capacity(samples.len() / channels); channels];
171+ for (i, &v) in samples.iter().enumerate() {
172+ planes[i % channels].push(v);
173+ }
174+ planes
175+}
176+
177+/// Decodes an ADTS file frame by frame, the way a container path feeds a packet per frame.
178+fn ours_adts(path: &Path) -> (Vec<Vec<f32>>, u16, u32) {
179+ let data = std::fs::read(path).expect("fixture reads");
180+ assert!(is_adts(&data), "{} is not ADTS", path.display());
181+ let mut decoder = AacDecoder::new();
182+ let mut interleaved: Vec<f32> = Vec::new();
183+ let mut channels = 0u16;
184+ let mut rate = 0u32;
185+ let mut at = 0usize;
186+ while at + 7 <= data.len() {
187+ let header = parse_adts(&data[at..]).expect("ADTS header parses");
188+ let end = (at + header.frame_length).min(data.len());
189+ let frame = decoder
190+ .decode(&data[at..end], None)
191+ .unwrap_or_else(|e| panic!("ADTS frame at {at} failed: {e:?}"));
192+ channels = frame.channels;
193+ rate = frame.sample_rate;
194+ interleaved.extend_from_slice(&frame.samples);
195+ if header.frame_length == 0 {
196+ break;
197+ }
198+ at += header.frame_length;
199+ }
200+ (deinterleave(&interleaved, usize::from(channels)), channels, rate)
201+}
202+
203+/// Decodes raw access units from an mp4 with the AudioSpecificConfig its esds carries.
204+fn ours_mp4(path: &Path) -> (Vec<Vec<f32>>, u16, u32) {
205+ let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("mp4 opens")))
206+ .expect("mp4 parses");
207+ let (idx, asc) = {
208+ let aac = demux
209+ .streams()
210+ .iter()
211+ .find(|s| s.params.codec == CodecId::Aac)
212+ .expect("mp4 has an AAC track");
213+ let asc = aac.params.extradata.as_ref().expect("esds carries the ASC").to_vec();
214+ (aac.index, asc)
215+ };
216+ let mut decoder = AacDecoder::with_config_bytes(&asc).expect("ASC parses");
217+ let mut interleaved: Vec<f32> = Vec::new();
218+ let mut channels = 0u16;
219+ let mut rate = 0u32;
220+ while let Ok(Packet { stream, data, .. }) = demux.next_packet() {
221+ if stream != idx {
222+ continue;
223+ }
224+ let frame = decoder
225+ .decode(&data, None)
226+ .unwrap_or_else(|e| panic!("access unit failed to decode: {e:?}"));
227+ channels = frame.channels;
228+ rate = frame.sample_rate;
229+ interleaved.extend_from_slice(&frame.samples);
230+ }
231+ (deinterleave(&interleaved, usize::from(channels)), channels, rate)
232+}
233+
234+/// Pearson correlation of `a[..n]` against `b[lag..]` (or `a[-lag..]` against `b`).
235+fn correlation_at(a: &[f32], b: &[f32], lag: i64, len: usize) -> Option<f64> {
236+ let (oa, ob) = if lag >= 0 {
237+ (0usize, lag as usize)
238+ } else {
239+ ((-lag) as usize, 0usize)
240+ };
241+ if oa + len > a.len() || ob + len > b.len() {
242+ return None;
243+ }
244+ let (mut num, mut da, mut db) = (0f64, 0f64, 0f64);
245+ for i in 0..len {
246+ let (x, y) = (f64::from(a[oa + i]), f64::from(b[ob + i]));
247+ num += x * y;
248+ da += x * x;
249+ db += y * y;
250+ }
251+ // Two silent spans agree; a silent span against a tone does not.
252+ if da == 0.0 && db == 0.0 {
253+ return Some(1.0);
254+ }
255+ Some(num / (da.sqrt() * db.sqrt()).max(1e-30))
256+}
257+
258+/// Finds the integer lag that best aligns `ours` with `theirs`.
259+///
260+/// A coarse search scores every lag in `±LAG_MAX` on a window from the middle of the
261+/// signal. A steady tone repeats its samples at every multiple of its period, so
262+/// several lags tie there. The near-tied candidates are then scored over the whole
263+/// overlap, where only the true alignment matches at both ends.
264+fn best_lag(ours: &[Vec<f32>], theirs: &[Vec<f32>]) -> i64 {
265+ let len = ours[0].len().min(theirs[0].len());
266+ let start = len / 2;
267+ let window = LAG_WINDOW.min(len / 4);
268+ let coarse = |lag: i64| -> Option<f64> {
269+ let mut score = 0f64;
270+ for (a, b) in ours.iter().zip(theirs) {
271+ score += correlation_at(&a[start..], &b[start..], lag, window)?;
272+ }
273+ Some(score)
274+ };
275+ let scored: Vec<(i64, f64)> = (-LAG_MAX..=LAG_MAX)
276+ .filter_map(|lag| coarse(lag).map(|c| (lag, c)))
277+ .collect();
278+ let top = scored.iter().map(|&(_, c)| c).fold(f64::MIN, f64::max);
279+ let full = |lag: i64| -> f64 {
280+ let shift = lag.unsigned_abs() as usize;
281+ let n = len.saturating_sub(shift);
282+ ours.iter()
283+ .zip(theirs)
284+ .map(|(a, b)| correlation_at(a, b, lag, n).unwrap_or(f64::MIN))
285+ .sum()
286+ };
287+ scored
288+ .iter()
289+ .filter(|&&(_, c)| c >= top - 1e-3)
290+ .map(|&(lag, _)| (lag, full(lag)))
291+ .fold((0i64, f64::MIN), |acc, (lag, c)| if c > acc.1 { (lag, c) } else { acc })
292+ .0
293+}
294+
295+/// Correlation of every our-channel `k` against every FFmpeg channel `j` at `lag`.
296+fn matrix(ours: &[Vec<f32>], theirs: &[Vec<f32>], lag: i64) -> Vec<Vec<f64>> {
297+ let shift = lag.unsigned_abs() as usize;
298+ ours.iter()
299+ .map(|a| {
300+ theirs
301+ .iter()
302+ .map(|b| {
303+ let len = a.len().min(b.len()).saturating_sub(shift);
304+ correlation_at(a, b, lag, len).unwrap_or(f64::MIN)
305+ })
306+ .collect()
307+ })
308+ .collect()
309+}
310+
311+fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &mut Vec<String>) {
312+ let label = format!("{:<6} {:<5} {:<10}", layout.name, container.label(), encoder);
313+ let Some(path) = encode(layout, encoder, container) else {
314+ println!("SKIP {label}: encoder refused the configuration");
315+ return;
316+ };
317+ let theirs = ffmpeg_decode(&path, layout.channels);
318+ let (ours, channels, rate) = match container {
319+ Container::Adts => ours_adts(&path),
320+ Container::Mp4 => ours_mp4(&path),
321+ };
322+ if usize::from(channels) != layout.channels || rate != RATE {
323+ failures.push(format!(
324+ "{label}: decoded {channels} ch at {rate} Hz, expected {} ch at {RATE} Hz",
325+ layout.channels
326+ ));
327+ return;
328+ }
329+ let lag = best_lag(&ours, &theirs);
330+ let grid = matrix(&ours, &theirs, lag);
331+ let diag: Vec<String> = grid
332+ .iter()
333+ .enumerate()
334+ .map(|(k, row)| format!("{:.6}", row[k]))
335+ .collect();
336+ println!("{label} lag {lag:>5} corr [{}]", diag.join(", "));
337+ if std::env::var_os("EC_AAC_PARITY_DEBUG").is_some() {
338+ let rms = |p: &[f32]| (p.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / p.len() as f64).sqrt();
339+ let fmt = |planes: &[Vec<f32>]| planes.iter().map(|p| format!("{:.4}", rms(p))).collect::<Vec<_>>().join(" ");
340+ println!(" rms ours [{}]", fmt(&ours));
341+ println!(" rms ffmpeg [{}]", fmt(&theirs));
342+ for (k, row) in grid.iter().enumerate() {
343+ let cells: Vec<String> = row.iter().map(|c| format!("{c:+.3}")).collect();
344+ println!(" ours {k}: {}", cells.join(" "));
345+ }
346+ }
347+
348+ for (k, row) in grid.iter().enumerate() {
349+ let own = row[k];
350+ let (best_j, best_c) = row
351+ .iter()
352+ .enumerate()
353+ .fold((0usize, f64::MIN), |acc, (j, &c)| if c > acc.1 { (j, c) } else { acc });
354+ if own < MIN_CORR {
355+ failures.push(format!(
356+ "{label}: channel {k} correlates {own:.6} with ffmpeg channel {k}, best is ffmpeg channel {best_j} at {best_c:.6}"
357+ ));
358+ }
359+ // The order check applies where the task names it (5.1 and 7.1).
360+ // A silent channel matches every silent one, so the order is wrong only when
361+ // some other channel correlates strictly better than the one at this position.
362+ if layout.channels >= 6 && own + 1e-6 < best_c {
363+ failures.push(format!(
364+ "{label}: our channel {k} matches ffmpeg channel {best_j} better than ffmpeg channel {k}, channel order differs"
365+ ));
366+ }
367+ }
368+}
369+
370+#[test]
371+fn multichannel_matches_ffmpeg_per_channel() {
372+ if !have_ffmpeg() {
373+ assert!(
374+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
375+ "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
376+ );
377+ eprintln!("SKIP: ffmpeg not installed");
378+ return;
379+ }
380+ let mut failures = Vec::new();
381+ for encoder in ENCODERS {
382+ if *encoder != "aac" && !have_encoder(encoder) {
383+ println!("SKIP encoder {encoder}: not built into this ffmpeg");
384+ continue;
385+ }
386+ for layout in LAYOUTS {
387+ for container in [Container::Adts, Container::Mp4] {
388+ check_case(layout, encoder, container, &mut failures);
389+ }
390+ }
391+ }
392+ assert!(
393+ failures.is_empty(),
394+ "multichannel parity failures:\n {}",
395+ failures.join("\n ")
396+ );
397+}
crates/ec-aac/tests/it/no_panic.rsadded+166 -0
@@ -0,0 +1,166 @@
1+//! No-panic gate for the decode path: malformed input must come back as `Err`,
2+//! never as a panic. Covers truncated and byte-corrupted copies of the committed
3+//! ADTS fixtures, plus random ADTS-looking frames (valid sync header, random payload).
4+//!
5+//! Every input is decoded inside `catch_unwind` so a panic reports which input
6+//! produced it instead of aborting the whole run.
7+
8+use std::panic::{catch_unwind, AssertUnwindSafe};
9+use std::path::{Path, PathBuf};
10+
11+use ec_aac::AacDecoder;
12+
13+const ADTS_FIXTURES: [&str; 6] = [
14+ "aac-adts-mono-44100.aac",
15+ "aac-adts-mono-48000.aac",
16+ "aac-adts-stereo-44100.aac",
17+ "aac-adts-stereo-48000.aac",
18+ "aac-adts-5.1-44100.aac",
19+ "aac-adts-5.1-48000.aac",
20+];
21+
22+/// Fixed seed so a failure reproduces exactly.
23+const SEED: u64 = 0x5EED_AAC0_0D15_EA5E;
24+
25+/// Small xorshift64 generator; the crate has no RNG dev-dependency.
26+struct Rng(u64);
27+
28+impl Rng {
29+ fn next_u64(&mut self) -> u64 {
30+ let mut x = self.0;
31+ x ^= x << 13;
32+ x ^= x >> 7;
33+ x ^= x << 17;
34+ self.0 = x;
35+ x
36+ }
37+
38+ fn below(&mut self, n: u64) -> u64 {
39+ self.next_u64() % n
40+ }
41+}
42+
43+fn audio_dir() -> PathBuf {
44+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
45+}
46+
47+/// Decodes one packet with a fresh decoder. Returns false if it panicked.
48+fn decode_no_panic(label: &str, packet: &[u8]) -> bool {
49+ let outcome = catch_unwind(AssertUnwindSafe(|| {
50+ let mut dec = AacDecoder::new();
51+ let _ = dec.decode(packet, None);
52+ }));
53+ if outcome.is_err() {
54+ eprintln!("PANIC: {label} ({} bytes)", packet.len());
55+ return false;
56+ }
57+ true
58+}
59+
60+/// Byte offsets of ADTS frame starts, walked with each header's frame_length.
61+fn adts_frame_starts(data: &[u8]) -> Vec<usize> {
62+ let mut starts = Vec::new();
63+ let mut at = 0usize;
64+ while at + 7 <= data.len() && data[at] == 0xFF && data[at + 1] & 0xF6 == 0xF0 {
65+ starts.push(at);
66+ let len = (((data[at + 3] & 0x03) as usize) << 11)
67+ | ((data[at + 4] as usize) << 3)
68+ | ((data[at + 5] as usize) >> 5);
69+ if len < 7 {
70+ break;
71+ }
72+ at += len;
73+ }
74+ starts
75+}
76+
77+#[test]
78+fn fixtures_truncated_and_corrupted_never_panic() {
79+ let dir = audio_dir();
80+ let mut found = 0usize;
81+ let mut failures: Vec<String> = Vec::new();
82+ let mut rng = Rng(SEED);
83+
84+ for name in ADTS_FIXTURES {
85+ let path = dir.join(name);
86+ let data = match std::fs::read(&path) {
87+ Ok(d) => d,
88+ Err(_) => {
89+ if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
90+ panic!(
91+ "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: scripts/gen-fixtures.sh",
92+ path.display()
93+ );
94+ }
95+ eprintln!("SKIP: fixture {} absent", path.display());
96+ continue;
97+ }
98+ };
99+ found += 1;
100+ assert!(!adts_frame_starts(&data).is_empty(), "{name} is not an ADTS stream");
101+
102+ // Ten truncation points spread across the file (never the full length).
103+ for i in 1..=10usize {
104+ let cut = data.len() * i / 11;
105+ let label = format!("{name} truncated at {cut}");
106+ if !decode_no_panic(&label, &data[..cut]) {
107+ failures.push(label);
108+ }
109+ }
110+
111+ // Fifty single-byte corruptions at seeded positions with seeded values.
112+ for i in 0..50 {
113+ let pos = rng.below(data.len() as u64) as usize;
114+ let mut value = rng.below(256) as u8;
115+ if value == data[pos] {
116+ value = value.wrapping_add(1);
117+ }
118+ let mut copy = data.clone();
119+ copy[pos] = value;
120+ let label = format!("{name} corruption #{i} at byte {pos} -> {value:#04x}");
121+ if !decode_no_panic(&label, &copy) {
122+ failures.push(label);
123+ }
124+ }
125+ }
126+
127+ if found == 0 {
128+ if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
129+ panic!("no ADTS fixtures found under {}", dir.display());
130+ }
131+ eprintln!("SKIP: no ADTS fixtures under {}", dir.display());
132+ }
133+ assert!(failures.is_empty(), "{} inputs panicked: {:?}", failures.len(), failures);
134+}
135+
136+#[test]
137+fn random_adts_frames_never_panic() {
138+ let mut rng = Rng(SEED ^ 0xAD75);
139+ let mut failures: Vec<String> = Vec::new();
140+
141+ for i in 0..500usize {
142+ // Valid syncword, MPEG-4, layer 0, protection absent (7-byte header).
143+ let sf_index = rng.below(13) as u8; // 13..=15 are reserved; keep the rate table in range
144+ let channel_config = rng.below(8) as u8;
145+ let payload_len = rng.below(600) as usize;
146+ let frame_length = 7 + payload_len;
147+ let object_type_bits = rng.below(4) as u8; // profile field; decoder maps it to object type
148+ let mut frame = vec![0u8; frame_length];
149+ frame[0] = 0xFF;
150+ frame[1] = 0xF1;
151+ frame[2] = (object_type_bits << 6) | (sf_index << 2) | ((channel_config >> 2) & 0x01);
152+ frame[3] = ((channel_config & 0x03) << 6) | ((frame_length >> 11) as u8 & 0x03);
153+ frame[4] = (frame_length >> 3) as u8;
154+ frame[5] = (((frame_length & 0x07) as u8) << 5) | 0x1F;
155+ frame[6] = 0xFC;
156+ for b in frame.iter_mut().skip(7) {
157+ *b = rng.below(256) as u8;
158+ }
159+ let label = format!("random ADTS frame #{i} (sf {sf_index}, ch {channel_config}, {frame_length} bytes)");
160+ if !decode_no_panic(&label, &frame) {
161+ failures.push(label);
162+ }
163+ }
164+
165+ assert!(failures.is_empty(), "{} random frames panicked: {:?}", failures.len(), failures);
166+}
crates/ec-aac/tests/it/ps_mp4.rsadded+109 -0
@@ -0,0 +1,109 @@
1+//! HE-AACv2 (Parametric Stereo) through the mp4 container path.
2+//!
3+//! The PS fixture is remuxed to mp4 with ffmpeg (stream copy), then its access
4+//! units are read back through `ec_mp4::Mp4Demuxer` and decoded with the
5+//! AudioSpecificConfig the `esds` box carries, as `AacDecoder::with_config_bytes`
6+//! does for any container. Nothing on this path may refuse PS: the decode must
7+//! produce two channels at the extension rate, matching FFmpeg's own decode of
8+//! the same mp4.
9+
10+use crate::shared::have_ffmpeg;
11+use crate::common::fixture;
12+use std::fs::File;
13+use std::io::BufReader;
14+use std::path::{Path, PathBuf};
15+use std::process::Command;
16+
17+use ec_aac::AacDecoder;
18+use ec_core::{CodecId, Demuxer, Packet};
19+use ec_mp4::Mp4Demuxer;
20+
21+const FIXTURE: &str = "ps_48000_music.aac";
22+const RATE: u32 = 48_000;
23+
24+/// FFmpeg's decode of `path` as interleaved f32, two channels at `RATE`.
25+fn ffmpeg_stereo(path: &Path) -> Vec<f32> {
26+ let out = Command::new("ffmpeg")
27+ .args(["-v", "error", "-i"])
28+ .arg(path)
29+ .args(["-f", "f32le", "-ac", "2", "-ar", "48000", "-"])
30+ .output()
31+ .expect("ffmpeg runs");
32+ assert!(out.status.success(), "ffmpeg decode failed");
33+ out.stdout
34+ .chunks(4)
35+ .map(|b| f32::from_le_bytes(b.try_into().expect("whole f32 samples")))
36+ .collect()
37+}
38+
39+fn correlation(a: &[f32], b: &[f32]) -> f64 {
40+ let n = a.len().min(b.len());
41+ let (mut num, mut da, mut db) = (0f64, 0f64, 0f64);
42+ for i in 0..n {
43+ let (x, y) = (f64::from(a[i]), f64::from(b[i]));
44+ num += x * y;
45+ da += x * x;
46+ db += y * y;
47+ }
48+ num / (da.sqrt() * db.sqrt()).max(1e-30)
49+}
50+
51+#[test]
52+fn ps_in_mp4_decodes_to_stereo_like_ffmpeg() {
53+ if !have_ffmpeg() {
54+ eprintln!("SKIP: ffmpeg not installed");
55+ return;
56+ }
57+ let src = fixture(FIXTURE);
58+ assert!(src.exists(), "fixture {} is absent", src.display());
59+ let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"));
60+ std::fs::create_dir_all(&dir).expect("temp dir");
61+ let mp4 = dir.join("ps_48000_music.m4a");
62+ let status = Command::new("ffmpeg")
63+ .args(["-v", "error", "-y", "-i"])
64+ .arg(&src)
65+ .args(["-c", "copy", "-f", "mp4"])
66+ .arg(&mp4)
67+ .status()
68+ .expect("ffmpeg runs");
69+ assert!(status.success(), "ffmpeg could not remux the PS fixture to mp4");
70+
71+ let mut demux = Mp4Demuxer::new(BufReader::new(File::open(&mp4).expect("mp4 opens")))
72+ .expect("mp4 parses");
73+ let (idx, asc) = {
74+ let aac = demux
75+ .streams()
76+ .iter()
77+ .find(|s| s.params.codec == CodecId::Aac)
78+ .expect("mp4 has an AAC track");
79+ let asc = aac.params.extradata.as_ref().expect("esds carries the ASC").to_vec();
80+ (aac.index, asc)
81+ };
82+ let mut decoder = AacDecoder::with_config_bytes(&asc).expect("ASC parses");
83+ // The config is implicit HE-AACv2 (an LC config at the core rate), so the rate
84+ // is only known once the first frame has revealed the SBR/PS extension.
85+
86+ let mut ours: Vec<f32> = Vec::new();
87+ let mut channels = 0u16;
88+ let mut rate = 0u32;
89+ while let Ok(Packet { stream, data, .. }) = demux.next_packet() {
90+ if stream != idx {
91+ continue;
92+ }
93+ let frame = decoder
94+ .decode(&data, None)
95+ .unwrap_or_else(|e| panic!("access unit failed to decode: {e:?}"));
96+ channels = frame.channels;
97+ rate = frame.sample_rate;
98+ ours.extend_from_slice(&frame.samples);
99+ }
100+ assert_eq!(channels, 2, "PS must decode to two channels");
101+ assert_eq!(rate, RATE, "PS must decode at the extension rate");
102+
103+ let theirs = ffmpeg_stereo(&mp4);
104+ let n = ours.len().min(theirs.len());
105+ assert!(n > RATE as usize, "too few samples decoded: {n}");
106+ let corr = correlation(&ours[..n], &theirs[..n]);
107+ println!("ps mp4: ours {} samples, ffmpeg {} samples, corr {corr:.6}", ours.len(), theirs.len());
108+ assert!(corr >= 0.999, "PS in mp4 correlates {corr:.6} with ffmpeg, below 0.999");
109+}
crates/ec-aac/tests/it/ps_oracle.rsadded+146 -0
@@ -0,0 +1,146 @@
1+//! Parametric Stereo (HE-AACv2) against FFmpeg's native AAC decoder.
2+//!
3+//! Each fixture is a 2-second HE-AACv2 stereo ADTS stream (generated by
4+//! `scripts/aac-tables/make-ps-fixtures.sh`). The reference is FFmpeg's own
5+//! decode of the same file. The acceptance bar is a per-channel correlation of
6+//! at least 0.999 after a bounded lag search, which absorbs decoder priming
7+//! delay, as `sbr_real_library.rs` does for HE-AAC v1.
8+
9+use crate::shared::have_ffmpeg;
10+use crate::common::fixture;
11+use crate::common::deinterleave;
12+use crate::common::correlation;
13+use ec_aac::AacDecoder;
14+use std::path::Path;
15+use std::process::Command;
16+
17+/// Per-channel correlation the reconstruction must reach against FFmpeg.
18+const MIN_CORR: f64 = 0.999;
19+/// Fixtures whose PS reconstruction is known to differ from FFmpeg, with the
20+/// correlation floor the current code is held to. Empty: every PS fixture
21+/// matches FFmpeg at `MIN_CORR` or better. An entry here needs a one-line reason
22+/// and a measured floor; remove it once the fixture passes at `MIN_CORR`.
23+const KNOWN_INEXACT: &[&str] = &[];
24+const KNOWN_INEXACT_FLOOR: f64 = 0.69;
25+/// Lag search bound, in samples. A winning lag at this bound is not a measurement.
26+const LAG_MAX: i64 = 4096;
27+/// Window (in samples) the coarse lag search correlates over.
28+const WINDOW: usize = 16_384;
29+/// Where the coarse window starts, past the decoder's start-up transient.
30+const WINDOW_START: usize = 32_768;
31+
32+/// (fixture, sample rate it decodes to)
33+const FIXTURES: &[(&str, u32)] = &[
34+ ("ps_44100_sine.aac", 44_100),
35+ ("ps_44100_music.aac", 44_100),
36+ ("ps_48000_sine.aac", 48_000),
37+ ("ps_48000_music.aac", 48_000),
38+];
39+
40+/// FFmpeg's decode of `path` as planar stereo `f32`.
41+fn ffmpeg_reference(path: &Path) -> Vec<Vec<f32>> {
42+ let out = Command::new("ffmpeg")
43+ .args(["-v", "error", "-i"])
44+ .arg(path)
45+ .args(["-ac", "2", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
46+ .output()
47+ .expect("ffmpeg runs");
48+ assert!(
49+ out.status.success(),
50+ "ffmpeg decode failed: {}",
51+ String::from_utf8_lossy(&out.stderr)
52+ );
53+ deinterleave(
54+ &out.stdout
55+ .chunks(4)
56+ .filter(|c| c.len() == 4)
57+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
58+ .collect::<Vec<f32>>(),
59+ 2,
60+ )
61+}
62+
63+/// The overlap of `ours` and `theirs` at `lag`: `ours[i]` pairs with `theirs[i + lag]`.
64+fn aligned<'a>(ours: &'a [f32], theirs: &'a [f32], lag: i64) -> (&'a [f32], &'a [f32]) {
65+ let (a0, b0) = if lag >= 0 {
66+ (0usize, lag as usize)
67+ } else {
68+ ((-lag) as usize, 0usize)
69+ };
70+ let n = ours.len().saturating_sub(a0).min(theirs.len().saturating_sub(b0));
71+ (&ours[a0..a0 + n], &theirs[b0..b0 + n])
72+}
73+
74+/// The lag that best aligns `ours` with `theirs`, and the full-overlap
75+/// correlation at that lag. A winning lag on the search bound is refused: the
76+/// true alignment may lie outside the search, so the number would be noise.
77+fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
78+ let mut best = (0i64, 0.0f64);
79+ for lag in -LAG_MAX..=LAG_MAX {
80+ let (a, b) = aligned(ours, theirs, lag);
81+ if a.len() < WINDOW_START + WINDOW {
82+ continue;
83+ }
84+ let c = correlation(&a[WINDOW_START..WINDOW_START + WINDOW], &b[WINDOW_START..WINDOW_START + WINDOW]);
85+ if c.abs() > best.1.abs() {
86+ best = (lag, c);
87+ }
88+ }
89+ assert!(
90+ best.0.abs() < LAG_MAX,
91+ "winning lag {} sits at the search bound -- the alignment is outside the search",
92+ best.0
93+ );
94+ let (a, b) = aligned(ours, theirs, best.0);
95+ (best.0, correlation(a, b))
96+}
97+
98+#[test]
99+fn ps_fixtures_decode_to_stereo_matching_ffmpeg() {
100+ let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some();
101+ if !have_ffmpeg() {
102+ assert!(!require, "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed");
103+ eprintln!("SKIP: ffmpeg not installed");
104+ return;
105+ }
106+ let mut failures = Vec::new();
107+ for &(name, rate) in FIXTURES {
108+ let path = fixture(name);
109+ assert!(
110+ path.exists() || !require,
111+ "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
112+ path.display()
113+ );
114+ if !path.exists() {
115+ eprintln!("SKIP: fixture {} absent", path.display());
116+ continue;
117+ }
118+ let bytes = std::fs::read(&path).expect("fixture reads");
119+ let audio = AacDecoder::new()
120+ .decode(&bytes, None)
121+ .unwrap_or_else(|e| panic!("{name}: decode failed: {e:?}"));
122+ assert_eq!(audio.channels, 2, "{name}: PS must decode to two channels");
123+ assert_eq!(audio.sample_rate, rate, "{name}: PS must decode at the extension rate");
124+ let ours = deinterleave(&audio.samples, 2);
125+ let theirs = ffmpeg_reference(&path);
126+ for ch in 0..2 {
127+ // The primary check is the full overlap at zero lag: both decoders
128+ // emit the same frame count and the same start, so no delay is
129+ // expected. The bounded search is reported as a diagnostic only, since
130+ // on a pure tone it returns aliases of the period.
131+ let (a, b) = aligned(&ours[ch], &theirs[ch], 0);
132+ let corr = correlation(a, b);
133+ let (lag, search_corr) = best_lag(&ours[ch], &theirs[ch]);
134+ println!(
135+ "{name} ch{ch}: ours {} frames, ffmpeg {} frames, corr@0 {corr:.6}, search lag {lag} corr {search_corr:.6}",
136+ ours[ch].len(),
137+ theirs[ch].len()
138+ );
139+ let floor = if KNOWN_INEXACT.contains(&name) { KNOWN_INEXACT_FLOOR } else { MIN_CORR };
140+ if corr < floor {
141+ failures.push(format!("{name} ch{ch}: corr@0 {corr:.6} < {floor}"));
142+ }
143+ }
144+ }
145+ assert!(failures.is_empty(), "PS does not match ffmpeg:\n{}", failures.join("\n"));
146+}
crates/ec-aac/tests/reelh_per_frame.rs → crates/ec-aac/tests/it/reelh_per_frame.rsrenamed+3 -12
@@ -3,6 +3,7 @@
3 //! collapses mid-stream, sequentially, with no seek/reset. Finds the first3 //! collapses mid-stream, sequentially, with no seek/reset. Finds the first
4 //! bad frame and its side info, to compare with the frame before.4 //! bad frame and its side info, to compare with the frame before.
5 5
6+use crate::shared::have_ffmpeg;
6 use std::fs::File;7 use std::fs::File;
7 use std::io::BufReader;8 use std::io::BufReader;
8 use std::path::Path;9 use std::path::Path;
@@ -12,14 +13,6 @@ use ec_aac::AacDecoder;
12 use ec_core::{CodecId, Demuxer, Packet};13 use ec_core::{CodecId, Demuxer, Packet};
13 use ec_mp4::Mp4Demuxer;14 use ec_mp4::Mp4Demuxer;
14 15
15-fn have_ffmpeg() -> bool {
16- Command::new("ffmpeg")
17- .arg("-version")
18- .output()
19- .map(|o| o.status.success())
20- .unwrap_or(false)
21-}
22-
23 #[test]16 #[test]
24 fn reelh_per_frame_scan() {17 fn reelh_per_frame_scan() {
25 if !have_ffmpeg() {18 if !have_ffmpeg() {
@@ -31,9 +24,7 @@ fn reelh_per_frame_scan() {
31 eprintln!("skip: file not present");24 eprintln!("skip: file not present");
32 return;25 return;
33 }26 }
34- unsafe {27+ let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true));
35- std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1");
36- }
37 28
38 // ffmpeg's channel-0-only decode (pan, not -ac, per the repro).29 // ffmpeg's channel-0-only decode (pan, not -ac, per the repro).
39 let out = Command::new("ffmpeg")30 let out = Command::new("ffmpeg")
@@ -47,7 +38,7 @@ fn reelh_per_frame_scan() {
47 assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));38 assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
48 let theirs: Vec<f32> = out39 let theirs: Vec<f32> = out
49 .stdout40 .stdout
50- .chunks_exact(4)41+ .as_chunks::<4>().0.iter()
51 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))42 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
52 .collect();43 .collect();
53 44
crates/ec-aac/tests/obs_real_content.rsmodified+5 -12
@@ -2,6 +2,9 @@
2 //! PNS/M/S decorrelation the consumer sweep found in that encoder's output2 //! PNS/M/S decorrelation the consumer sweep found in that encoder's output
3 //! (see repo ledger). Real files, read-only, absent directory skips loudly.3 //! (see repo ledger). Real files, read-only, absent directory skips loudly.
4 4
5+mod common;
6+
7+use common::have_ffmpeg;
5 use std::path::{Path, PathBuf};8 use std::path::{Path, PathBuf};
6 use std::process::Command;9 use std::process::Command;
7 10
@@ -15,14 +18,6 @@ const MAX_SAMPLES: usize = 480_000; // 10s @ 48kHz
15 const LAG_MAX: usize = 4_000;18 const LAG_MAX: usize = 4_000;
16 const WINDOW: usize = 200_000;19 const WINDOW: usize = 200_000;
17 20
18-fn have_ffmpeg() -> bool {
19- Command::new("ffmpeg")
20- .arg("-version")
21- .output()
22- .map(|o| o.status.success())
23- .unwrap_or(false)
24-}
25-
26 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {21 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
27 let out = Command::new("ffmpeg")22 let out = Command::new("ffmpeg")
28 .args(["-v", "error", "-i"])23 .args(["-v", "error", "-i"])
@@ -47,7 +42,7 @@ fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
47 );42 );
48 let samples: Vec<f32> = out43 let samples: Vec<f32> = out
49 .stdout44 .stdout
50- .chunks_exact(4)45+ .as_chunks::<4>().0.iter()
51 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))46 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
52 .collect();47 .collect();
53 let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];48 let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
@@ -203,9 +198,7 @@ fn obs_content_table() {
203 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4"))198 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4"))
204 .collect();199 .collect();
205 files.sort();200 files.sort();
206- unsafe {201+ let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true));
207- std::env::set_var("EC_AAC_TOOL_SIDEINFO_DEBUG", "1");
208- }
209 for path in files {202 for path in files {
210 eprintln!("== {}", path.display());203 eprintln!("== {}", path.display());
211 let before = ec_aac::tool_sideinfo_log().len();204 let before = ec_aac::tool_sideinfo_log().len();
crates/ec-aac/tests/oracle.rsmodified+229 -20
@@ -2,23 +2,14 @@
2 //! real library. Every test that needs a fixture or ffmpeg skips loudly when it2 //! real library. Every test that needs a fixture or ffmpeg skips loudly when it
3 //! is absent rather than passing quietly.3 //! is absent rather than passing quietly.
4 4
5+mod common;
6+
7+use common::{fixtures, have_ffmpeg};
5 use std::path::{Path, PathBuf};8 use std::path::{Path, PathBuf};
6 use std::process::Command;9 use std::process::Command;
7 10
8 use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};11 use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};
9 12
10-fn fixtures() -> PathBuf {
11- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
12-}
13-
14-fn have_ffmpeg() -> bool {
15- Command::new("ffmpeg")
16- .arg("-version")
17- .output()
18- .map(|o| o.status.success())
19- .unwrap_or(false)
20-}
21-
22 /// Fixture-presence probe for the committed `fixtures/audio` media this file13 /// Fixture-presence probe for the committed `fixtures/audio` media this file
23 /// decodes. Returns whether the fixture is present, but never silently: under14 /// decodes. Returns whether the fixture is present, but never silently: under
24 /// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path15 /// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
@@ -61,7 +52,7 @@ fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
61 52
62 fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> {53 fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> {
63 bytes54 bytes
64- .chunks_exact(4)55+ .as_chunks::<4>().0.iter()
65 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))56 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
66 .collect()57 .collect()
67 }58 }
@@ -361,10 +352,9 @@ fn asc_round_trips_every_sample_rate() {
361 assert_eq!(ec_aac::sf_index_for_rate(37_000), None);352 assert_eq!(ec_aac::sf_index_for_rate(37_000), None);
362 }353 }
363 354
364-/// A refusal is a claim: this pins the current contract -- plain SBR (no355+/// A refusal is a claim: this pins the current contract -- SBR and HE-AACv2
365-/// Parametric Stereo) is reconstructed and reports the extension rate; a356+/// (SBR with Parametric Stereo) are reconstructed and report the extension
366-/// Parametric Stereo stream still falls back to its core (PS itself is a357+/// rate; plain AAC-LC reports nothing missing.
367-/// separate, unimplemented tool); plain AAC-LC reports nothing missing.
368 #[test]358 #[test]
369 fn sbr_is_reported_not_silently_upsampled() {359 fn sbr_is_reported_not_silently_upsampled() {
370 // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz),360 // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz),
@@ -379,13 +369,15 @@ fn sbr_is_reported_not_silently_upsampled() {
379 );369 );
380 370
381 // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010.371 // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010.
372+ // Parametric Stereo is reconstructed now, so this reports the extension
373+ // rate (the decoder also outputs two channels for it).
382 let ps_asc = [0xEBu8, 0x11, 0x88];374 let ps_asc = [0xEBu8, 0x11, 0x88];
383 let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses");375 let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses");
384- assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly);376+ assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::V1);
385 assert_eq!(377 assert_eq!(
386 ps_decoder.output_sample_rate(),378 ps_decoder.output_sample_rate(),
387- Some(24_000),379+ Some(48_000),
388- "PS is still unreconstructed: must report the core rate it actually produces"380+ "a reconstructed HE-AACv2 stream must report the extension rate it produces"
389 );381 );
390 382
391 let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2))383 let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2))
@@ -480,6 +472,223 @@ fn encoder_beats_the_incumbent_bar() {
480 assert!(checked > 0, "no lossless fixtures found");472 assert!(checked > 0, "no lossless fixtures found");
481 }473 }
482 474
475+/// Every channel count the encoder claims (1 to 6 and 8), at 64 kbps per channel, the
476+/// scaling the stereo row uses (128 kbps for 2 channels). Each row is
477+/// (layout, channels, kbps, bar, which incumbent the bar is). rusty_aac 0.5.0 (the
478+/// INCUMBENT_BAR incumbent above) refuses 7+ channels, so the 8-channel bar is ffmpeg's
479+/// native AAC encoder on the same fixture at the same bitrate, a stricter proxy.
480+/// Measured 2026-10-18 by running each incumbent through the same decode and
481+/// best-lag correlation (`~/.cache/aacencbar-inc`, not in the repo).
482+const LAYOUT_BAR: &[(&str, usize, u32, f64, &str)] = &[
483+ ("mono", 1, 64, 0.9698, "rusty_aac 0.5.0"),
484+ ("stereo", 2, 128, 0.9743, "rusty_aac 0.5.0"),
485+ ("3.0", 3, 192, 0.9711, "rusty_aac 0.5.0"),
486+ ("4.0", 4, 256, 0.9645, "rusty_aac 0.5.0"),
487+ ("5.0", 5, 320, 0.9712, "rusty_aac 0.5.0"),
488+ ("5.1", 6, 384, 0.9648, "rusty_aac 0.5.0"),
489+ ("7.1", 8, 512, 0.9994, "ffmpeg native aac"),
490+];
491+
492+/// Every LAYOUT_BAR row: worst-channel correlation against its incumbent's bar, and the
493+/// ADTS rate within 5% of the target.
494+#[test]
495+fn encoder_meets_every_layout_bar() {
496+ if !have_ffmpeg() {
497+ eprintln!("SKIP: ffmpeg not on PATH");
498+ return;
499+ }
500+ let dir = fixtures().join("audio");
501+ let tmp = std::env::temp_dir().join("ec-aac-layout-bar");
502+ std::fs::create_dir_all(&tmp).expect("temp dir");
503+ let mut checked = 0;
504+ let mut failed = Vec::new();
505+ for (name, channels, kbps, bar, incumbent) in LAYOUT_BAR {
506+ let src = dir.join(format!("flac-{name}-48000.flac"));
507+ if !require_fixture(&src, "scripts/gen-aac-layouts.sh OUTDIR (3.0, 4.0, 5.0, 7.1)") {
508+ continue;
509+ }
510+ let source = ffmpeg_decode(&src, *channels);
511+ let mut interleaved = Vec::with_capacity(source[0].len() * channels);
512+ for i in 0..source[0].len() {
513+ for plane in &source {
514+ interleaved.push(plane[i]);
515+ }
516+ }
517+ let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps);
518+ let path = tmp.join(format!("{name}-{kbps}k.aac"));
519+ std::fs::write(&path, &adts).expect("write");
520+ let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
521+ let ours = ffmpeg_decode(&path, *channels);
522+ let corr: Vec<f64> = source
523+ .iter()
524+ .zip(&ours)
525+ .map(|(a, b)| best_correlation(a, b))
526+ .collect();
527+ let worst = corr.iter().copied().fold(f64::MAX, f64::min);
528+ println!(
529+ "layout {name} {kbps}k: {rate:.1} kbps ({:+.1}%), worst channel {worst:.4} \
530+ (bar {bar:.4}, {incumbent}) per-channel {corr:.4?}",
531+ (rate / f64::from(*kbps) - 1.0) * 100.0
532+ );
533+ if (rate / f64::from(*kbps) - 1.0).abs() > 0.05 {
534+ failed.push(format!("{name} {kbps}k: rate {rate:.1} kbps outside +-5%"));
535+ }
536+ if worst < *bar {
537+ failed.push(format!(
538+ "{name} {kbps}k: worst channel {worst:.4} under the bar {bar:.4} ({incumbent})"
539+ ));
540+ }
541+ checked += 1;
542+ }
543+ assert!(checked > 0, "no lossless fixtures found");
544+ assert!(failed.is_empty(), "layout bars missed:\n{}", failed.join("\n"));
545+}
546+
547+/// Noise-bearing synthetic content for NOISY_BAR. Each clip is 10 s, 48 kHz, stereo, built
548+/// here by ffmpeg's lavfi sources, so no media is committed. Each entry is
549+/// (name, lavfi inputs, filter_complex ending in [o]).
550+const NOISY_CLIPS: &[(&str, &[&str], &str)] = &[
551+ (
552+ // (a) the bench content: two slow-AM tone pairs plus independent pink noise at 0.03.
553+ "bench",
554+ &[
555+ "aevalsrc='0.25*sin(2*PI*220*t)+0.12*sin(2*PI*277.18*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*329.63*t)|0.25*sin(2*PI*222*t)+0.12*sin(2*PI*280*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*331*t)':s=48000:d=10",
556+ "anoisesrc=d=10:c=pink:a=0.03:s=48000:r=48000:seed=1",
557+ "anoisesrc=d=10:c=pink:a=0.03:s=48000:r=48000:seed=2",
558+ ],
559+ "[1:a][2:a]amerge=inputs=2,aformat=channel_layouts=stereo[n];[0:a][n]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
560+ ),
561+ (
562+ // (b) music-like: four harmonics with 5.5 Hz vibrato per channel, a white burst every
563+ // 0.5 s (exponential decay), and a low-level white noise floor.
564+ "music",
565+ &[
566+ "aevalsrc='0.12*sin(2*PI*(196*t+2*sin(2*PI*5.5*t))) + 0.07*sin(2*PI*(392*t+2*sin(2*PI*5.5*t))) + 0.05*sin(2*PI*(588*t+2*sin(2*PI*5.5*t))) + 0.04*sin(2*PI*(784*t+2*sin(2*PI*5.5*t)))|0.12*sin(2*PI*(247*t+2*sin(2*PI*5.3*t+1))) + 0.07*sin(2*PI*(494*t+2*sin(2*PI*5.3*t+1))) + 0.05*sin(2*PI*(741*t+2*sin(2*PI*5.3*t+1))) + 0.04*sin(2*PI*(988*t+2*sin(2*PI*5.3*t+1)))':s=48000:d=10",
567+ "anoisesrc=d=10:c=white:a=0.5:s=48000:r=48000:seed=3",
568+ "anoisesrc=d=10:c=white:a=0.004:s=48000:r=48000:seed=5",
569+ "anoisesrc=d=10:c=white:a=0.004:s=48000:r=48000:seed=6",
570+ ],
571+ "[1:a]aeval='val(0)*exp(-30*mod(t,0.5))|val(0)*exp(-30*mod(t,0.5))':c=stereo[b];[2:a][3:a]amerge=inputs=2,aformat=channel_layouts=stereo[f];[0:a][b]amix=inputs=2:normalize=0[t1];[t1][f]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
572+ ),
573+ (
574+ // (c) speech-like: white noise bursts through two formant band pairs, gated at 4 Hz,
575+ // plus 120 Hz and 118 Hz decaying pitch pulses.
576+ "speech",
577+ &[
578+ "anoisesrc=d=10:c=white:a=0.3:s=48000:r=48000:seed=7",
579+ "anoisesrc=d=10:c=white:a=0.3:s=48000:r=48000:seed=8",
580+ "aevalsrc='exp(-600*mod(t,1/120))*sin(2*PI*120*t)*0.5|exp(-600*mod(t,1/118))*sin(2*PI*118*t)*0.5':s=48000:d=10",
581+ ],
582+ "[0:a]bandpass=f=700:width_type=h:w=150,bandpass=f=1200:width_type=h:w=200[a1];[1:a]bandpass=f=1200:width_type=h:w=200,bandpass=f=2600:width_type=h:w=300[a2];[a1][a2]amerge=inputs=2[nz];[nz]aeval='val(0)*(0.5+0.5*sin(2*PI*4*t))|val(1)*(0.5+0.5*sin(2*PI*4*t))'[nzg];[2:a]aeval='val(0)*0.3|val(1)*0.3'[p];[nzg][p]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
583+ ),
584+ (
585+ // (d) independent white noise per channel at about -20 dBFS RMS (measured -19.97).
586+ "white",
587+ &[
588+ "anoisesrc=d=10:c=white:a=0.1738:s=48000:r=48000:seed=9",
589+ "anoisesrc=d=10:c=white:a=0.1738:s=48000:r=48000:seed=10",
590+ ],
591+ "[0:a][1:a]amerge=inputs=2,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
592+ ),
593+];
594+
595+/// Incumbent (ffmpeg's native AAC encoder, `-c:a aac -b:a <kbps>k`, 2026-10-18) per-channel
596+/// correlation on each NOISY_CLIPS entry, at the best lag in {0, 1024, 2048}, minimum over
597+/// the two channels. The bar is the incumbent minus 0.002, rounded down to four decimals.
598+/// Only 128k and 192k are gated (the 96k rows are measured and reported only).
599+/// (clip, kbps, incumbent, bar, gated)
600+const NOISY_BAR: &[(&str, u32, f64, f64, bool)] = &[
601+ ("bench", 96, 0.999344, 0.9973, false),
602+ ("bench", 128, 0.999594, 0.9975, true),
603+ ("bench", 192, 0.999618, 0.9976, true),
604+ ("music", 96, 0.942434, 0.9404, false),
605+ ("music", 128, 0.962250, 0.9602, true),
606+ ("music", 192, 0.978655, 0.9766, true),
607+ ("speech", 96, 0.991754, 0.9897, false),
608+ ("speech", 128, 0.999023, 0.9970, true),
609+ ("speech", 192, 0.999609, 0.9976, true),
610+ ("white", 96, 0.572339, 0.5703, false),
611+ ("white", 128, 0.668895, 0.6668, true),
612+ ("white", 192, 0.702850, 0.7008, true),
613+];
614+
615+/// Renders one NOISY_CLIPS entry to a 16-bit WAV in `dir` (cached across rows).
616+fn noisy_clip(name: &str, dir: &Path) -> PathBuf {
617+ let out = dir.join(format!("noisy-{name}.wav"));
618+ if out.exists() {
619+ return out;
620+ }
621+ let (_, inputs, filter) = NOISY_CLIPS
622+ .iter()
623+ .find(|(n, _, _)| *n == name)
624+ .expect("a NOISY_CLIPS entry");
625+ let mut cmd = Command::new("ffmpeg");
626+ cmd.args(["-v", "error", "-y"]);
627+ for input in *inputs {
628+ cmd.args(["-f", "lavfi", "-i", input]);
629+ }
630+ cmd.args(["-filter_complex", filter, "-map", "[o]", "-c:a", "pcm_s16le"])
631+ .arg(&out);
632+ let run = cmd.output().expect("ffmpeg runs");
633+ assert!(
634+ run.status.success(),
635+ "ffmpeg could not render {name}: {}",
636+ String::from_utf8_lossy(&run.stderr)
637+ );
638+ out
639+}
640+
641+/// Stereo AAC-LC at each NOISY_BAR bitrate on the noise-bearing clips: worst-channel
642+/// correlation against the incumbent's bar, and the ADTS rate within 5% of the target.
643+#[test]
644+fn encoder_meets_noisy_bar() {
645+ if !have_ffmpeg() {
646+ eprintln!("SKIP: ffmpeg not on PATH");
647+ return;
648+ }
649+ let tmp = std::env::temp_dir().join("ec-aac-noisy-bar");
650+ std::fs::create_dir_all(&tmp).expect("temp dir");
651+ let mut failed = Vec::new();
652+ for (name, kbps, incumbent, bar, gated) in NOISY_BAR {
653+ let src = noisy_clip(name, &tmp);
654+ let source = ffmpeg_decode(&src, 2);
655+ let mut interleaved = Vec::with_capacity(source[0].len() * 2);
656+ for i in 0..source[0].len() {
657+ for plane in &source {
658+ interleaved.push(plane[i]);
659+ }
660+ }
661+ let adts = encode_to_adts(&interleaved, 2, 48_000, *kbps);
662+ let path = tmp.join(format!("{name}-{kbps}k.aac"));
663+ std::fs::write(&path, &adts).expect("write");
664+ let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
665+ let ours = ffmpeg_decode(&path, 2);
666+ let corr: Vec<f64> = source
667+ .iter()
668+ .zip(&ours)
669+ .map(|(a, b)| best_correlation(a, b))
670+ .collect();
671+ let worst = corr.iter().copied().fold(f64::MAX, f64::min);
672+ println!(
673+ "noisy {name} {kbps}k: {rate:.1} kbps ({:+.1}%), worst channel {worst:.4} \
674+ (incumbent {incumbent:.4}, bar {bar:.4}, gated {gated}) per-channel {corr:.4?}",
675+ (rate / f64::from(*kbps) - 1.0) * 100.0
676+ );
677+ if !gated {
678+ continue;
679+ }
680+ if (rate / f64::from(*kbps) - 1.0).abs() > 0.05 {
681+ failed.push(format!("{name} {kbps}k: rate {rate:.1} kbps outside +-5%"));
682+ }
683+ if worst < *bar {
684+ failed.push(format!(
685+ "{name} {kbps}k: worst channel {worst:.4} under the bar {bar:.4}"
686+ ));
687+ }
688+ }
689+ assert!(failed.is_empty(), "noisy bars missed:\n{}", failed.join("\n"));
690+}
691+
483 fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {692 fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {
484 let frames = (f64::from(rate) * secs) as usize;693 let frames = (f64::from(rate) * secs) as usize;
485 let mut pcm = Vec::with_capacity(frames * channels);694 let mut pcm = Vec::with_capacity(frames * channels);
crates/ec-aac/tests/sbr_real_library.rsdeleted+0 -5065

Diff too large; view file

@@ -1,5065 +0,0 @@
1-//! The SBR chain, against real HE-AAC files pulled from the user's own media
2-//! directories, decoded through their real container (mp4 `esds` / Matroska
3-//! `CodecPrivate`) so `AacDecoder::with_config_bytes` actually arms the SBR
4-//! path -- `tests/oracle.rs` remuxes everything to bare ADTS first, and an
5-//! ADTS stream carries no AudioSpecificConfig, so its SBR chain never sees a
6-//! frame. Every file here is a live discovery over `~/Music`, `~/Downloads`,
7-//! `~/Videos`: absent files skip loudly, nothing is generated or bundled.
8-
9-use std::fs::File;
10-use std::io::{BufReader, Read};
11-use std::path::{Path, PathBuf};
12-use std::process::Command;
13-
14-use ec_aac::{AacDecoder, parse_audio_specific_config};
15-use ec_core::{CodecId, Demuxer, Packet};
16-use ec_matroska::MatroskaDemuxer;
17-use ec_mp4::Mp4Demuxer;
18-
19-/// Every `#[test]` in this file decodes real SBR content through
20-/// `our_decode`/`our_decode_uncapped`, and a handful of them steer that
21-/// decode with process-global env vars (`EC_AAC_SBR_HF_BYPASS`,
22-/// `EC_AAC_SBR_SIDEINFO_DEBUG`, `EC_AAC_SBR_NOISE_ZERO`,
23-/// `EC_AAC_SBR_NOISE_FRACTION`) as debug toggles, set then removed mid-test.
24-/// Cargo runs this binary's tests in parallel threads by default, so an
25-/// unguarded `set_var`/`remove_var` window in one test can flip decode
26-/// behaviour out from under another test's own concurrent decode -- this is
27-/// exactly what turned `sbr_real_library_matches_reference`'s HF-band
28-/// correlation into a full-suite-only flake (`sbr_hf_window_band_probe`
29-/// toggling `EC_AAC_SBR_HF_BYPASS` while it ran). Every test locks this for
30-/// its whole body so no toggle window and no concurrent read can interleave.
31-static DECODE_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
32-
33-fn have_ffmpeg() -> bool {
34- Command::new("ffmpeg")
35- .arg("-version")
36- .output()
37- .map(|o| o.status.success())
38- .unwrap_or(false)
39-}
40-
41-/// Fixture-presence probe for the generated HE-AAC matrix under
42-/// `<repo>/.cache/heaac-fixtures` (`scripts/aac-tables/make-heaac-fixtures.sh`).
43-/// Returns whether the fixture is present, but never silently: under
44-/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
45-/// and the script that regenerates it, so a host whose fixture library drifted
46-/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
47-/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
48-/// short-circuited because the probe ran first in a compound `if`).
49-///
50-/// Order is load-bearing: probe, assert, return. Never merge the probe into
51-/// the same `if` as the escape. The `~/Music` / `~/Downloads` / `~/Videos`
52-/// scans in this file are host corpora, not the committed fixture library, and
53-/// keep their plain skip.
54-fn require_fixture(path: &Path, generator: &str) -> bool {
55- let present = path.exists();
56- assert!(
57- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
58- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
59- path.display(),
60- generator
61- );
62- if !present {
63- eprintln!("SKIP: fixture {} absent", path.display());
64- }
65- present
66-}
67-
68-/// A film's audio track is hours long; the correlation only needs a bounded
69-/// window near the start, so both sides cap how much they ever decode.
70-const MAX_SAMPLES: usize = 1_000_000;
71-
72-/// ffmpeg's decode of a file's given absolute stream index, as
73-/// planar-by-channel `f32`.
74-fn ffmpeg_decode(path: &Path, absolute_stream: usize, channels: usize) -> Vec<Vec<f32>> {
75- let out = Command::new("ffmpeg")
76- .args(["-v", "error", "-i"])
77- .arg(path)
78- .args([
79- "-map",
80- &format!("0:{absolute_stream}"),
81- "-t",
82- "30",
83- "-f",
84- "f32le",
85- "-acodec",
86- "pcm_f32le",
87- "-",
88- ])
89- .output()
90- .expect("ffmpeg runs");
91- assert!(
92- out.status.success(),
93- "ffmpeg decode failed: {}",
94- String::from_utf8_lossy(&out.stderr)
95- );
96- let samples: Vec<f32> = out
97- .stdout
98- .chunks_exact(4)
99- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
100- .collect();
101- let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
102- for (i, &v) in samples.iter().enumerate() {
103- planes[i % channels].push(v);
104- }
105- planes
106-}
107-
108-/// One AAC stream pulled out of its container: the AudioSpecificConfig bytes
109-/// exactly as the container carried them, and its access units in decode
110-/// order. Whichever of `ec-mp4`/`ec-matroska` the file's header names does the
111-/// actual box/EBML walk -- this is a thin `Demuxer`-trait harness over them,
112-/// not a parser of its own.
113-fn extract_aac_track(path: &Path, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
114- let mut head = [0u8; 12];
115- File::open(path).ok()?.read_exact(&mut head).ok()?;
116- if ec_mp4::is_mp4(&head) {
117- let f = File::open(path).ok()?;
118- let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?;
119- extract_from(&mut d, stream_index)
120- } else if ec_matroska::is_matroska(&head) {
121- let f = File::open(path).ok()?;
122- let mut d = MatroskaDemuxer::new(BufReader::new(f)).ok()?;
123- extract_from(&mut d, stream_index)
124- } else {
125- None
126- }
127-}
128-
129-/// `stream_index` picks the Nth AAC stream the container lists, in listed
130-/// order -- a file can carry more than one audio track (FMJ's mkv has both an
131-/// LC 5.1 track and an HE-AAC stereo commentary track).
132-fn extract_from(d: &mut dyn Demuxer, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
133- let aac = d
134- .streams()
135- .iter()
136- .filter(|s| s.params.codec == CodecId::Aac)
137- .nth(stream_index)?;
138- let idx = aac.index;
139- let asc = aac.params.extradata.as_ref()?.to_vec();
140- let mut aus = Vec::new();
141- // A film's audio track is a couple thousand AAC access units for the
142- // handful of seconds the correlation actually needs; capped here so the
143- // packet walk does not have to read the whole multi-gigabyte video
144- // stream past it just to reach `Eof`.
145- while aus.len() < 1_500 {
146- match d.next_packet() {
147- Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()),
148- Ok(_) => continue,
149- Err(_) => break,
150- }
151- }
152- Some((asc, aus))
153-}
154-
155-/// Our decode of one container-native AAC stream, through its real
156-/// AudioSpecificConfig, as planar-by-channel `f32`.
157-fn our_decode(
158- path: &Path,
159- stream_index: usize,
160-) -> Option<(Vec<Vec<f32>>, ec_aac::SbrSupport, u32)> {
161- let Some((asc, aus)) = extract_aac_track(path, stream_index) else {
162- eprintln!(" extract_aac_track returned None");
163- return None;
164- };
165- eprintln!(" asc={asc:02x?} aus={}", aus.len());
166- let mut decoder = match AacDecoder::with_config_bytes(&asc) {
167- Ok(d) => d,
168- Err(e) => {
169- eprintln!(" with_config_bytes failed: {e:?}");
170- return None;
171- }
172- };
173- let sbr = decoder.sbr_support();
174- let rate = decoder.output_sample_rate().unwrap_or(0);
175- let mut planes: Vec<Vec<f32>> = Vec::new();
176- let mut failed = 0;
177- let debug_failures = std::env::var("EC_AAC_SBR_AU_FAIL_DEBUG").as_deref() == Ok("1");
178- for (au_idx, au) in aus.iter().enumerate() {
179- let frame = match decoder.decode(au, None) {
180- Ok(f) => f,
181- Err(e) => {
182- failed += 1;
183- if debug_failures {
184- let head: Vec<u8> = au.iter().take(16).copied().collect();
185- eprintln!(
186- " AU {au_idx} FAILED len={} err={e:?} head={head:02x?}",
187- au.len()
188- );
189- }
190- continue;
191- }
192- };
193- let ch = usize::from(frame.channels);
194- if ch == 0 {
195- continue;
196- }
197- if planes.is_empty() {
198- planes = vec![Vec::new(); ch];
199- }
200- for (i, v) in frame.samples.iter().enumerate() {
201- planes[i % ch].push(*v);
202- }
203- if planes[0].len() >= MAX_SAMPLES {
204- break;
205- }
206- }
207- if failed > 0 {
208- eprintln!(" {failed}/{} access units failed to decode", aus.len());
209- }
210- if planes.is_empty() {
211- eprintln!(" no channels decoded");
212- return None;
213- }
214- Some((planes, sbr, rate))
215-}
216-
217-/// Search window bound: keeps the correlation sum bounded, per the charter
218-/// -- an unbounded version over a whole film's worth of samples was too slow
219-/// to be an every-run test.
220-const WINDOW: usize = 200_000;
221-
222-/// Wide lag search bound for the specific gate proven to need it
223-/// (`sbr_real_library_matches_reference`, ours-vs-reference across a real
224-/// container's remux/priming delay). Measured (round-54 wide-lag probe,
225-/// worktree sbr-per-au) FMJ's true full-chain delay vs the reference is
226-/// ~22,913 samples @48kHz -- that gate's old `LAG_MAX=4_000` search clipped
227-/// at its own edge and silently reported the edge's noise as the answer for
228-/// 50+ rounds (class: "an alignment instrument whose result sits at its own
229-/// search edge is invalid"). 100_000 covers that with 4x headroom and is
230-/// already the bound round-53's own `WIDE_LAG_MAX=100_000` probe used to
231-/// find it. NOT used as the default everywhere: a wider bound also widens
232-/// the coarse pass's exposure to spurious short-slice noise peaks, so
233-/// call sites whose true delay is known-small (container/decoder priming,
234-/// ours-vs-own-core self-consistency) keep their original, narrower bound
235-/// -- round-54 first tried blanket-widening every call site to this value
236-/// and it flipped `full_chain_low_band_matches_own_core` and the LC control
237-/// row of `synthetic_heaac_matrix` from a correct small-lag answer to a
238-/// wrong, noise-driven distant one, still comfortably inside the bound
239-/// (not `at_edge`) but wrong regardless.
240-const SEARCH_LAG_MAX: i64 = 100_000;
241-/// Original bound for the plain `best_lag_correlation` wrapper, used by the
242-/// file's other (ours-vs-reference small-priming-delay, or ours-vs-ours)
243-/// callers that were never shown to need more.
244-const PLAIN_LAG_MAX: i64 = 4_000;
245-/// Odd stride `best_lag_correlation_ex`'s coarse pass steps by, so it
246-/// doesn't alias against frame-length periodicity.
247-const SEARCH_STRIDE: i64 = 11;
248-
249-fn dot(a: &[f32], b: &[f32]) -> f64 {
250- a.iter()
251- .zip(b)
252- .map(|(x, y)| f64::from(*x) * f64::from(*y))
253- .sum()
254-}
255-
256-fn correlation(a: &[f32], b: &[f32]) -> f64 {
257- let n = a.len().min(b.len());
258- if n < 1024 {
259- return 0.0;
260- }
261- let (a, b) = (&a[..n], &b[..n]);
262- let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
263- let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
264- let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect();
265- let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect();
266- let num = dot(&ac, &bc);
267- let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt();
268- if den == 0.0 { 0.0 } else { num / den }
269-}
270-
271-/// Best correlation over a bounded lag search, PLUS whether the winning lag
272-/// sits at the search's own edge -- the single instrument every asserting
273-/// test in this file now routes through (class fix, round-54: a search that
274-/// silently clips at its bound and reports the edge's noise as "the
275-/// answer" is not an instrument, it's a lie). Two passes keep the whole
276-/// search O(reasonable) even at `SEARCH_LAG_MAX`-sized bounds on a
277-/// film-length file: an odd-`SEARCH_STRIDE` coarse pass over a short slice
278-/// finds roughly where the alignment is (the stride, not full 1-by-1
279-/// stepping, is what keeps a `lag_max` in the tens of thousands cheap, and
280-/// also avoids aliasing against frame-length periodicity), then one
281-/// full-`WINDOW` correlation at that lag (and its immediate neighbours, in
282-/// case the coarse slice picked a noisy lag) gives the reported number.
283-fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) {
284- const COARSE: usize = 4_096;
285- let start = ours
286- .len()
287- .min(theirs.len())
288- .saturating_sub(WINDOW)
289- .min(ours.len() / 4);
290- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
291- let (oa, ob) = if lag >= 0 {
292- (start, start + lag as usize)
293- } else {
294- (start + (-lag) as usize, start)
295- };
296- if oa + len > ours.len() || ob + len > theirs.len() {
297- None
298- } else {
299- Some((oa, ob))
300- }
301- };
302- // The winning lag is the one that maximizes |correlation|, not signed
303- // correlation: a channel that is a pure phase/sign inversion of the
304- // reference reads strongly NEGATIVE at its true alignment lag, and a
305- // signed-max search rejects that lag for whatever unrelated lag gives a
306- // merely positive value -- reporting a real inversion as near-zero
307- // noise. `found` (not "best abs value >= 0", which every real
308- // correlation already satisfies) is what actually distinguishes "no
309- // in-bounds lag existed" from "the best in-bounds lag was negative" --
310- // an earlier version used `best.1 < 0.0` for that check, which treats
311- // every genuinely negative (inverted) result as "not found" and falls
312- // back to the COARSE, `COARSE`-sample-window-only candidate instead;
313- // that coarse window is short enough to spuriously correlate at 0.87 on
314- // real audio, so the fallback was silently replacing an honest,
315- // correctly-refined negative full-`WINDOW` result with a noise-driven
316- // positive one from a 20x-shorter slice. Carry the signed value through
317- // so callers can see the sign, not just |corr|.
318- // Stride 1, not `SEARCH_STRIDE` (round-61): a real correlation peak
319- // between two decodes of the same audio is often ONE sample wide (on
320- // reeln's core-only PCM: 0.9998 at lag 481, 0.94 at 479), so a
321- // strided grid samples only the noise floor around it and the "best
322- // coarse lag" it hands the refine pass is arbitrary. That is how a
323- // 0.9998 match printed as corr 0.408 at lag -52. Stride 1 over the
324- // narrow bound is ~33M multiply-adds; the wide bound is 25x that and
325- // only runs on escalation, so this is not worth a resolution trade.
326- let mut coarse_best = (0i64, -1.0f64, 0.0f64);
327- for lag in -lag_max..=lag_max {
328- if let Some((oa, ob)) = slice_at(lag, COARSE) {
329- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
330- if c.abs() > coarse_best.1 {
331- coarse_best = (lag, c.abs(), c);
332- }
333- }
334- }
335- let at_edge = coarse_best.0.abs() >= lag_max - SEARCH_STRIDE;
336- let mut best = (coarse_best.0, -1.0f64, 0.0f64);
337- let mut found = false;
338- for lag in (coarse_best.0 - 2 * SEARCH_STRIDE)..=(coarse_best.0 + 2 * SEARCH_STRIDE) {
339- let Some((oa, ob)) = slice_at(lag, WINDOW) else {
340- continue;
341- };
342- let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
343- if n < 1024 {
344- continue;
345- }
346- let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]);
347- if c.abs() > best.1 {
348- best = (lag, c.abs(), c);
349- }
350- found = true;
351- }
352- if !found {
353- best = coarse_best;
354- }
355- // A winning lag at the search bound is not a measurement (the true
356- // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if
357- // it still sits at the edge fail here rather than hand any caller a
358- // noise-driven number (instrument-at-bound class).
359- if at_edge && lag_max < SEARCH_LAG_MAX {
360- return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX);
361- }
362- assert!(
363- !at_edge,
364- "winning lag {} sits at the +/-{lag_max} search bound -- the true \
365- alignment is outside the search, corr {:.6} is noise, not a measurement",
366- best.0, best.2
367- );
368- (best.0, best.2, at_edge)
369-}
370-
371-/// Thin wrapper over `best_lag_correlation_ex` at `PLAIN_LAG_MAX`, for the
372-/// many non-asserting call sites that only want `(lag, corr)` and whose true
373-/// delay was never shown to exceed the original 4_000 bound. The one gate
374-/// proven to need the wide bound (`sbr_real_library_matches_reference`)
375-/// calls `_ex` directly with `SEARCH_LAG_MAX` instead of going through this
376-/// wrapper.
377-fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
378- let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, PLAIN_LAG_MAX);
379- (lag, corr)
380-}
381-
382-/// Thin wrapper over `best_lag_correlation_ex` at a caller-supplied bound,
383-/// for non-asserting call sites (asserting ones use `_ex` directly).
384-fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) {
385- let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, lag_max);
386- (lag, corr)
387-}
388-
389-/// The robust two-stage lag search `sbr441_family_sample_drift_probe` proved
390-/// out (round-55/56): a plain coarse-stride search picks the SINGLE best
391-/// `COARSE`-sample-window candidate, which on periodic/tonal real music
392-/// content routinely aliases onto a wrong lag (this file family's ref-L-vs-
393-/// ref-R self-check scored a coarse-search lag=-24 corr=0.213, worse than
394-/// the true fixed-lag comparison's 0.873). Instead of trusting the single
395-/// coarse winner, keep the top `K` coarse candidates and refine EACH with a
396-/// full-resolution, narrow (+/-128) search restricted to the file's first
397-/// 10 seconds (`sample_rate`-derived) -- periodic aliasing needs many
398-/// seconds of a repeating pattern to fool a full-resolution window, so the
399-/// candidate that is genuinely aligned wins there even when it wasn't the
400-/// coarse pass's top pick. Returns `(lag, corr, at_edge)` for the winning
401-/// refined candidate, `at_edge` inherited from that candidate's own coarse
402-/// Stride-1 lag search: correlates a `COARSE`-sized window at EVERY lag in
403-/// `+/-lag_max`, then refines the winner with a full `WINDOW`.
404-///
405-/// `robust_lag_topk`'s coarse pass steps by `SEARCH_STRIDE` (11) and then
406-/// refines only its top-K coarse scorers. That ranking is meaningless when
407-/// the true peak is narrower than the stride: on reeln's core-only PCM
408-/// the correlation is 0.9998 at lag 481 and already 0.94 at 479, so no
409-/// stride-11 grid point (the grid is 4 mod 11; 481 is 8 mod 11) scores
410-/// anything but noise, the top-K is drawn from noise, and the search
411-/// returned lag -52 corr 0.408 for a pair that is actually a 0.9998 match.
412-/// FMJ, same instrument, same true lag 481, happened to land a noise-ranked
413-/// candidate within the +/-128 refine window and read correctly -- the
414-/// failure is luck-dependent, not file-dependent. Stride 1 over a 4_096
415-/// window is ~33M multiply-adds at `PLAIN_LAG_MAX`, cheaper than the top-K
416-/// refinement it replaces, so the resolution is simply not worth trading.
417-fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) {
418- const COARSE: usize = 4_096;
419- let start = ours
420- .len()
421- .min(theirs.len())
422- .saturating_sub(WINDOW)
423- .min(ours.len() / 4);
424- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
425- let (oa, ob) = if lag >= 0 {
426- (start, start + lag as usize)
427- } else {
428- (start + (-lag) as usize, start)
429- };
430- if oa + len > ours.len() || ob + len > theirs.len() {
431- None
432- } else {
433- Some((oa, ob))
434- }
435- };
436- let mut best = (0i64, -1.0f64);
437- for lag in -lag_max..=lag_max {
438- if let Some((oa, ob)) = slice_at(lag, COARSE) {
439- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs();
440- if c > best.1 {
441- best = (lag, c);
442- }
443- }
444- }
445- let at_edge = best.0.abs() >= lag_max - 1;
446- let mut refined = (best.0, -1.0f64);
447- for lag in (best.0 - 2)..=(best.0 + 2) {
448- let Some((oa, ob)) = slice_at(lag, WINDOW) else {
449- continue;
450- };
451- let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
452- if n < 1024 {
453- continue;
454- }
455- let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]).abs();
456- if c > refined.1 {
457- refined = (lag, c);
458- }
459- }
460- if refined.1 < 0.0 {
461- refined = best;
462- }
463- (refined.0, refined.1, at_edge)
464-}
465-
466-/// bucket (true if ITS coarse lag sat at the +/-`lag_max` search bound).
467-fn robust_lag_topk(
468- ours: &[f32],
469- theirs: &[f32],
470- lag_max: i64,
471- rate: u32,
472- k: usize,
473-) -> (i64, f64, bool) {
474- const COARSE: usize = 4_096;
475- let start = ours
476- .len()
477- .min(theirs.len())
478- .saturating_sub(WINDOW)
479- .min(ours.len() / 4);
480- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
481- let (oa, ob) = if lag >= 0 {
482- (start, start + lag as usize)
483- } else {
484- (start + (-lag) as usize, start)
485- };
486- if oa + len > ours.len() || ob + len > theirs.len() {
487- None
488- } else {
489- Some((oa, ob))
490- }
491- };
492- // Stride 1 (round-61), for the reason spelled out on
493- // `exhaustive_lag_correlation`: a strided grid can miss a 1-sample-wide
494- // peak entirely, and then the top-K is a ranking of noise.
495- let mut coarse: Vec<(i64, f64)> = Vec::new();
496- for lag in -lag_max..=lag_max {
497- if let Some((oa, ob)) = slice_at(lag, COARSE) {
498- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
499- coarse.push((lag, c.abs()));
500- }
501- }
502- coarse.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
503- let ten_s = 10 * rate.max(1) as usize;
504- let mut best: (i64, f64, bool) = (0, -2.0, false);
505- for &(cand_lag, _) in coarse.iter().take(k) {
506- let at_edge = cand_lag.abs() >= lag_max - SEARCH_STRIDE;
507- // `narrow_lag_at` computes `ob_i = oa0 + lag` directly (no sign
508- // split the way `slice_at` above does), so a fixed `oa0 = 0` goes
509- // negative -- and every lag in the whole +/-128 window skips --
510- // whenever `cand_lag` is negative enough (this file family's true
511- // lag is -4674). Shift the window's start so it stays anchored to
512- // "the first 10s of real content" while guaranteeing `ob_i >= 0`
513- // even at the most-negative lag in the +/-128 refine range.
514- let oa0 = (128 - cand_lag).max(0) as usize;
515- let refine_len = ten_s.min(ours.len().saturating_sub(oa0)).min(
516- theirs
517- .len()
518- .saturating_sub((oa0 as i64 + cand_lag).max(0) as usize),
519- );
520- if refine_len < 1024 {
521- continue;
522- }
523- let (rlag, rcorr) = narrow_lag_at(ours, theirs, oa0, refine_len, cand_lag, 128);
524- if rcorr > best.1 {
525- best = (rlag, rcorr, at_edge);
526- }
527- }
528- best
529-}
530-
531-/// Signed correlation of `ours` against `theirs` at one fixed `lag`, full
532-/// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation`
533-/// uses internally -- used to test a hypothesized sign inversion by reusing
534-/// a KNOWN-good lag (and window) from a healthy channel instead of trusting
535-/// the (signed, positive-biased) search above to relocate both for a
536-/// channel that may be exactly inverted at that same lag. Anchoring must
537-/// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows
538-/// otherwise cover different seconds of audio and are not comparable.
539-fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 {
540- let start = ours
541- .len()
542- .min(theirs.len())
543- .saturating_sub(WINDOW)
544- .min(ours.len() / 4);
545- let (oa, ob) = if lag >= 0 {
546- (start, start + lag as usize)
547- } else {
548- (start + (-lag) as usize, start)
549- };
550- let n = WINDOW
551- .min(ours.len().saturating_sub(oa))
552- .min(theirs.len().saturating_sub(ob));
553- if n < 1024 {
554- return 0.0;
555- }
556- correlation(&ours[oa..oa + n], &theirs[ob..ob + n])
557-}
558-
559-/// A first-order RC low-pass, run forward then backward to cancel its own
560-/// phase shift, giving a clean low-band/high-band split without pulling in a
561-/// filter design dependency for a diagnostic.
562-fn lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
563- let dt = 1.0 / f64::from(rate);
564- let rc = 1.0 / (2.0 * std::f64::consts::PI * cutoff_hz);
565- let alpha = (dt / (rc + dt)) as f32;
566- let mut fwd = Vec::with_capacity(samples.len());
567- let mut y = 0.0f32;
568- for &x in samples {
569- y += alpha * (x - y);
570- fwd.push(y);
571- }
572- let mut out = vec![0.0f32; fwd.len()];
573- y = 0.0;
574- for i in (0..fwd.len()).rev() {
575- y += alpha * (fwd[i] - y);
576- out[i] = y;
577- }
578- out
579-}
580-
581-fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
582- let low = lowpass(samples, rate, cutoff_hz);
583- samples.iter().zip(&low).map(|(a, b)| a - b).collect()
584-}
585-
586-/// DIAGNOSTIC (round-13): cascades `lowpass` three times for a much sharper
587-/// stopband than the single first-order zero-phase filter the real
588-/// assertion uses -- checking whether the below-crossover bar is actually
589-/// being missed because of above-crossover energy leaking through the
590-/// gentle single-pass rolloff, not because the low band itself is wrong.
591-fn sharp_lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
592- let a = lowpass(samples, rate, cutoff_hz);
593- let b = lowpass(&a, rate, cutoff_hz);
594- lowpass(&b, rate, cutoff_hz)
595-}
596-
597-/// Decisive-experiment diagnostic: correlates consecutive short (`WIN`)
598-/// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g.
599-/// the winning full-file lag from `best_lag_correlation`), searching a small
600-/// local lag range per window. A per-frame continuity bug (dropped/duplicated
601-/// samples at access-unit boundaries) shows up as the winning local lag
602-/// DRIFTING linearly window to window; a bug that is not about concatenation
603-/// (wrong band mapping, spectral corruption) shows up as a roughly constant
604-/// lag with low/noisy correlation instead.
605-fn windowed_lag_drift(
606- o: &[f32],
607- t: &[f32],
608- oa: usize,
609- ob: usize,
610- windows: usize,
611-) -> Vec<(i64, f64)> {
612- const WIN: usize = 4_096;
613- const LOCAL_LAG: i64 = 2_000;
614- let mut out = Vec::with_capacity(windows);
615- for w in 0..windows {
616- let base_o = oa + w * WIN;
617- let base_t = ob + w * WIN;
618- let mut best = (0i64, -1.0f64, 0.0f64);
619- for lag in -LOCAL_LAG..=LOCAL_LAG {
620- let ao = base_o as i64 + lag;
621- if ao < 0 {
622- continue;
623- }
624- let ao = ao as usize;
625- if ao + WIN > o.len() || base_t + WIN > t.len() {
626- continue;
627- }
628- let c = correlation(&o[ao..ao + WIN], &t[base_t..base_t + WIN]);
629- if c.abs() > best.1 {
630- best = (lag, c.abs(), c);
631- }
632- }
633- out.push((best.0, best.2));
634- }
635- out
636-}
637-
638-/// DIAGNOSTIC (round-14, Task 2): per-QMF-band correlation over the
639-/// above-crossover region. No 64-band QMF Analysis exists standalone in this
640-/// crate, so this substitutes an STFT: magnitude-per-bin time series (one
641-/// value per hop) for `ours` and `theirs`, correlated bin by bin, then
642-/// averaged over the bins a QMF band of width `rate/128` Hz covers. A patch
643-/// boundary in `build_patches`' target ranges landing on a low-correlation
644-/// block convicts patch construction; an even spread across all HF bands
645-/// with the map otherwise right points at gain mapping instead.
646-/// Pearson correlation with no minimum-length floor -- `correlation`'s
647-/// 1024-sample floor exists for raw audio windows, not the much shorter
648-/// per-bin magnitude series this diagnostic correlates.
649-fn magnitude_series_correlation(a: &[f32], b: &[f32]) -> f64 {
650- let n = a.len().min(b.len());
651- if n < 2 {
652- return 0.0;
653- }
654- let (a, b) = (&a[..n], &b[..n]);
655- let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
656- let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
657- let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect();
658- let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect();
659- let num = dot(&ac, &bc);
660- let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt();
661- if den == 0.0 { 0.0 } else { num / den }
662-}
663-
664-fn per_band_correlation(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> {
665- const FFT_LEN: usize = 2048;
666- const HOP: usize = 1024;
667- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
668- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
669- let bins = rfft.spectrum_len();
670- let n = o.len().min(t.len());
671- let hops = if n >= FFT_LEN {
672- (n - FFT_LEN) / HOP + 1
673- } else {
674- 0
675- };
676- let mut o_mag = vec![Vec::with_capacity(hops); bins];
677- let mut t_mag = vec![Vec::with_capacity(hops); bins];
678- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
679- for (src, dst) in [(o, &mut o_mag), (t, &mut t_mag)] {
680- for h in 0..hops {
681- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
682- win.apply(&mut block);
683- rfft.forward(&block, &mut spectrum);
684- for (b, c) in spectrum.iter().enumerate() {
685- dst[b].push(c.norm_sqr().sqrt());
686- }
687- }
688- }
689- // QMF band width is `core_rate/128` where `core_rate` is the core
690- // decoder's own sample rate -- half the SBR extension/output rate for a
691- // plain (2x) HE-AAC stream -- not `output_rate/128`: measured against
692- // this file's own kx=14 crossover, the correlation break lands exactly
693- // at 14*(rate/256) Hz (2412 Hz), not at 14*(rate/128).
694- let band_hz = f64::from(rate) / 256.0;
695- let bin_hz = f64::from(rate) / FFT_LEN as f64;
696- let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
697- let mut out = Vec::with_capacity(num_bands);
698- for band in 0..num_bands {
699- let lo = (band as f64 * band_hz / bin_hz).floor() as usize;
700- let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins);
701- if lo >= hi {
702- continue;
703- }
704- // round-16: correlating bin-by-bin then averaging the |corr| values
705- // was the bug -- a QMF band's bins share one slowly-varying envelope,
706- // but a tiny (sub-Hz) frequency offset between our filterbank and the
707- // reference's shifts energy between adjacent bins hop to hop, so each
708- // bin's OWN magnitude series decorrelates even though the band's
709- // total energy (what a QMF band's single subband signal actually
710- // carries) tracks the reference closely. Summing the bins' magnitudes
711- // into one band-energy series per side FIRST, then correlating that
712- // single pair, is robust to that intra-band leakage the way the
713- // per-bin version wasn't.
714- let hops_here = o_mag[lo].len().min(t_mag[lo].len());
715- let mut o_band = vec![0.0f32; hops_here];
716- let mut t_band = vec![0.0f32; hops_here];
717- for b in lo..hi {
718- for h in 0..hops_here {
719- o_band[h] += o_mag[b][h];
720- t_band[h] += t_mag[b][h];
721- }
722- }
723- let c = magnitude_series_correlation(&o_band, &t_band);
724- if c.is_finite() {
725- out.push((band as f64 * band_hz, c.abs(), band as f64));
726- }
727- }
728- out
729-}
730-
731-/// Per-band PCM-domain lag search (round-15 candidate-A discriminator):
732-/// `per_band_correlation`'s magnitude series has one sample per 1024-sample
733-/// STFT `HOP`, far coarser than a single QMF slot (64 samples) -- a stage
734-/// delay of one or a few slots between our HF path and the reference's would
735-/// vanish into that hop bucket instead of showing up as a lag. This instead
736-/// bandpasses `o`/`t` to each HF QMF band (the same zero-phase RC
737-/// `highpass`/`lowpass` primitives the crossover split already uses) and
738-/// searches PCM-sample lag directly, coarse-then-refine like
739-/// `best_lag_correlation`, so a consistent nonzero peak lag (especially a
740-/// multiple of 64 samples) convicts a per-stage time-alignment bug; lags
741-/// clustered at/near zero exonerate it in favour of a patch-map or
742-/// gain-mapping bug instead. Bands below kx (already known clean from
743-/// `per_band_correlation`) are skipped -- only HF bands (14..) are searched.
744-///
745-/// CONVICTED (round-26, Task 1): `bandpass_offset_probe` correlated this same
746-/// `sharp_lowpass`/`sharp_highpass` cascade's band-k output against the
747-/// REFERENCE's band-(k+/-10) output for several HF `k` -- and the DOWNWARD
748-/// offset (band k-10, closer to the strongly-correlated below-crossover
749-/// content) read a HIGHER correlation than the nominal same-band pairing in
750-/// every HF band tried (e.g. band 34: same 0.937 vs -10 0.966). A filter
751-/// with real ~172Hz selectivity cannot produce that; a "sharp" 3x-cascaded
752-/// single-pole RC (~18dB/oct) at a 9kHz center still passes a wide swath
753-/// below its corner, so each "band k" reading here is really "everything up
754-/// to and including band k" -- cumulative correlation, dominated by the
755-/// genuinely-matching low band, which manufactures the smooth monotonic
756-/// decline earlier rounds chased. The reported LAG values are still valid
757-/// (a filter with no stopband selectivity still has a passband delay that
758-/// tracks the true alignment), but the reported per-band |corr| AMPLITUDE
759-/// here is NOT a trustworthy per-band figure -- use `per_band_phase`'s
760-/// cross-spectrum magnitude ratio (or the bin-level `bin_level_conviction`)
761-/// for that instead.
762-fn per_band_lag_search(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, i64, f64)> {
763- const LAG_MAX: i64 = 1_024;
764- const COARSE_STEP: i64 = 8;
765- const COARSE: usize = 4_096;
766- const WIN: usize = 65_536;
767- let band_hz = f64::from(rate) / 256.0;
768- let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
769- let n = o.len().min(t.len());
770- let start = n.saturating_sub(WIN + LAG_MAX as usize).min(n / 4);
771- let mut out = Vec::new();
772- for band in 14..num_bands {
773- let lo = (band as f64 * band_hz).max(1.0);
774- let hi = ((band + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0);
775- // A single-pole RC (the plain `highpass`/`lowpass` used for the
776- // crossover split) has too gentle a rolloff to isolate a ~172Hz-wide
777- // QMF band -- it leaks in the much stronger, well-correlated
778- // below-crossover energy, which was confirmed here as a smooth,
779- // frequency-monotonic false-high correlation with no matching cliff
780- // in `per_band_correlation`'s FFT-bin version of the same bands.
781- // `sharp_lowpass` (3x cascade, already used for the crossover-band
782- // debug check) plus its highpass complement sharpens the stopband
783- // enough that leakage from outside this one band stops dominating.
784- let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> {
785- s.iter()
786- .zip(&sharp_lowpass(s, rate, cutoff))
787- .map(|(a, b)| a - b)
788- .collect::<Vec<f32>>()
789- };
790- let bp = |s: &[f32]| -> Vec<f32> { sharp_lowpass(&sharp_highpass(s, lo), rate, hi) };
791- let ob = bp(o);
792- let tb = bp(t);
793- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
794- let (oa, ta) = if lag >= 0 {
795- (start, start + lag as usize)
796- } else {
797- (start + (-lag) as usize, start)
798- };
799- if oa + len > ob.len() || ta + len > tb.len() {
800- None
801- } else {
802- Some((oa, ta))
803- }
804- };
805- let mut coarse = (0i64, -1.0f64, 0.0f64);
806- let mut lag = -LAG_MAX;
807- while lag <= LAG_MAX {
808- if let Some((oa, ta)) = slice_at(lag, COARSE) {
809- let c = correlation(&ob[oa..oa + COARSE], &tb[ta..ta + COARSE]);
810- if c.abs() > coarse.1 {
811- coarse = (lag, c.abs(), c);
812- }
813- }
814- lag += COARSE_STEP;
815- }
816- let mut best = coarse;
817- for lag in (coarse.0 - COARSE_STEP)..=(coarse.0 + COARSE_STEP) {
818- if let Some((oa, ta)) = slice_at(lag, WIN) {
819- let c = correlation(&ob[oa..oa + WIN], &tb[ta..ta + WIN]);
820- if c.abs() > best.1 {
821- best = (lag, c.abs(), c);
822- }
823- }
824- }
825- out.push((band as f64 * band_hz, best.0, best.2));
826- }
827- out
828-}
829-
830-/// DIAGNOSTIC (round-16, Task 2): per-band phase offset and magnitude
831-/// transfer between `o` and `t`, over the SAME aligned window
832-/// `per_band_correlation` uses. Reuses the STFT-and-coherent-band-sum
833-/// machinery `per_band_correlation` was just fixed to use (sum the complex
834-/// spectrum, not just its magnitude, across a band's bins first, so a
835-/// per-bin sub-band redistribution doesn't wash out a genuine per-band
836-/// phase relationship) but keeps the complex value: the cross-spectrum
837-/// `sum_h O_band(h) * conj(T_band(h))` accumulated over every hop gives one
838-/// phasor per band whose angle is the (hop-weighted) phase offset between
839-/// `o` and `t` in that band and whose radius, once normalized by each side's
840-/// own energy, gives the magnitude transfer ratio.
841-fn per_band_phase(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> {
842- const FFT_LEN: usize = 2048;
843- const HOP: usize = 1024;
844- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
845- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
846- let bins = rfft.spectrum_len();
847- let n = o.len().min(t.len());
848- let hops = if n >= FFT_LEN {
849- (n - FFT_LEN) / HOP + 1
850- } else {
851- 0
852- };
853- let mut o_spec = vec![Vec::with_capacity(hops); bins];
854- let mut t_spec = vec![Vec::with_capacity(hops); bins];
855- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
856- for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
857- for h in 0..hops {
858- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
859- win.apply(&mut block);
860- rfft.forward(&block, &mut spectrum);
861- for (b, c) in spectrum.iter().enumerate() {
862- dst[b].push(*c);
863- }
864- }
865- }
866- let band_hz = f64::from(rate) / 256.0;
867- let bin_hz = f64::from(rate) / FFT_LEN as f64;
868- let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
869- let mut out = Vec::with_capacity(num_bands);
870- for band in 0..num_bands {
871- let lo = (band as f64 * band_hz / bin_hz).floor() as usize;
872- let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins);
873- if lo >= hi || hops == 0 {
874- continue;
875- }
876- // Cross-spectrum accumulated PER BIN over hops, THEN summed across
877- // the band's bins -- not the reverse. Complex-summing the band's
878- // bins together at each hop first (as an earlier version of this
879- // function did) mixes in `O_b * conj(T_b')` cross terms for every
880- // b != b' pair once the per-hop products are formed; two adjacent
881- // FFT bins carry unrelated instantaneous phase (they are different
882- // frequencies), so those cross terms are pure noise that swamped the
883- // real per-bin coherence and produced an incoherent, near-random
884- // phase reading across exactly the HF bands `per_band_lag_search`'s
885- // direct PCM correlation shows are highly correlated at lag 0/-1.
886- let mut cross_re = 0.0f64;
887- let mut cross_im = 0.0f64;
888- let mut o_energy = 0.0f64;
889- let mut t_energy = 0.0f64;
890- for b in lo..hi {
891- for h in 0..hops {
892- let ob = o_spec[b][h];
893- let tb = t_spec[b][h];
894- let cross = ob * tb.conj();
895- cross_re += f64::from(cross.re);
896- cross_im += f64::from(cross.im);
897- o_energy +=
898- f64::from(ob.re) * f64::from(ob.re) + f64::from(ob.im) * f64::from(ob.im);
899- t_energy +=
900- f64::from(tb.re) * f64::from(tb.re) + f64::from(tb.im) * f64::from(tb.im);
901- }
902- }
903- let phase = cross_im.atan2(cross_re);
904- let mag_ratio = if t_energy > 0.0 {
905- (o_energy / t_energy).sqrt()
906- } else {
907- 0.0
908- };
909- out.push((band as f64 * band_hz, phase, mag_ratio));
910- }
911- out
912-}
913-
914-/// Round-26, Task 1: convicts (or acquits) `per_band_lag_search`'s bandpass.
915-/// Applies the SAME 3x-cascaded RC bandpass that diagnostic uses to `o` at
916-/// band `band` and to `t` at band `band` (same-band control), `band+offset`
917-/// and `band-offset`. A single-pole cascade's stopband is gentle enough that
918-/// "band k" may really pass "everything below f_k" -- if so, `o`-band-k and
919-/// `t`-band-(k+offset) still both carry the same dominant low-band leakage
920-/// and read highly correlated even though their nominal passbands don't
921-/// overlap at all, which convicts the filter, not the content. Below the SBR
922-/// crossover, genuinely narrowband-matching content should decorrelate
923-/// quickly as `offset` grows; a HF band that does NOT decorrelate at
924-/// `offset` bands away is evidence the filter has no real selectivity there.
925-fn bandpass_offset_probe(
926- o: &[f32],
927- t: &[f32],
928- rate: u32,
929- band: usize,
930- offset: i64,
931-) -> (f64, f64, f64) {
932- let band_hz = f64::from(rate) / 256.0;
933- let bp_at = |s: &[f32], b: usize| -> Vec<f32> {
934- let lo = (b as f64 * band_hz).max(1.0);
935- let hi = ((b + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0);
936- let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> {
937- s.iter()
938- .zip(&sharp_lowpass(s, rate, cutoff))
939- .map(|(a, b)| a - b)
940- .collect::<Vec<f32>>()
941- };
942- sharp_lowpass(&sharp_highpass(s, lo), rate, hi)
943- };
944- let ob = bp_at(o, band);
945- let same_corr = correlation(&ob, &bp_at(t, band));
946- let hi_band = band as i64 + offset;
947- let hi_corr = if hi_band >= 0 {
948- correlation(&ob, &bp_at(t, hi_band as usize))
949- } else {
950- 0.0
951- };
952- let lo_band = band as i64 - offset;
953- let lo_corr = if lo_band >= 0 {
954- correlation(&ob, &bp_at(t, lo_band as usize))
955- } else {
956- 0.0
957- };
958- (same_corr, hi_corr, lo_corr)
959-}
960-
961-/// Round-26, Task 2: bin-level (no filter, no cross-band summing) comparison
962-/// of `o` against `t` in the most energetic HF SBR bands at/above `min_band`,
963-/// three ways: DIRECT (bin i vs bin i), MIRROR (bin i vs the band's bins in
964-/// REVERSED order -- the signature of a QMF band-orientation/parity flip
965-/// between our own-design synthesis and the reference's convention: energies
966-/// right, direct corr ~0, phase random, exactly what round-14/16 observed),
967-/// and SHIFT (the whole `BINS_PER_SBR_BAND`-bin band matched one band up or
968-/// down -- the signature of a `build_patches` source-mapping offset).
969-/// Coherence per bin pair is
970-/// `|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)` (in
971-/// [0,1]; 1 = perfectly phase+magnitude locked, ~0 = unrelated), accumulated
972-/// over the SAME aligned hops `per_band_phase` uses, then averaged over the
973-/// band's 8 bins. Bands are picked by OUR OWN energy (the "real" HF content),
974-/// not the reference's, so a genuinely-silent HF band can't crowd out an
975-/// energetic one just because it happens to sort first.
976-fn bin_level_conviction(
977- o: &[f32],
978- t: &[f32],
979- rate: u32,
980- min_band: usize,
981- top_n: usize,
982-) -> Vec<(f64, f64, f64, f64, f64, f64)> {
983- const FFT_LEN: usize = 2048;
984- const HOP: usize = 1024;
985- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
986- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
987- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
988- let bins = rfft.spectrum_len();
989- let n = o.len().min(t.len());
990- let hops = if n >= FFT_LEN {
991- (n - FFT_LEN) / HOP + 1
992- } else {
993- 0
994- };
995- let mut o_spec = vec![Vec::with_capacity(hops); bins];
996- let mut t_spec = vec![Vec::with_capacity(hops); bins];
997- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
998- for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
999- for h in 0..hops {
1000- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1001- win.apply(&mut block);
1002- rfft.forward(&block, &mut spectrum);
1003- for (b, c) in spectrum.iter().enumerate() {
1004- dst[b].push(*c);
1005- }
1006- }
1007- }
1008- if hops == 0 {
1009- return Vec::new();
1010- }
1011- let band_hz = f64::from(rate) / 256.0;
1012- let num_bands = bins / BINS_PER_SBR_BAND;
1013- let coh = |ob: usize, tb: usize| -> f64 {
1014- if ob >= bins || tb >= bins {
1015- return 0.0;
1016- }
1017- let mut cross_re = 0.0f64;
1018- let mut cross_im = 0.0f64;
1019- let mut o_e = 0.0f64;
1020- let mut t_e = 0.0f64;
1021- for h in 0..hops {
1022- let oc = o_spec[ob][h];
1023- let tc = t_spec[tb][h];
1024- let cross = oc * tc.conj();
1025- cross_re += f64::from(cross.re);
1026- cross_im += f64::from(cross.im);
1027- o_e += f64::from(oc.norm_sqr());
1028- t_e += f64::from(tc.norm_sqr());
1029- }
1030- let den = (o_e * t_e).sqrt();
1031- if den > 0.0 {
1032- (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1033- } else {
1034- 0.0
1035- }
1036- };
1037- // Rank HF bands by OUR OWN energy, so the energetic-band handful is
1038- // chosen by real content, not by whatever the reference happens to carry.
1039- let mut ranked: Vec<(usize, f64)> = (min_band..num_bands)
1040- .map(|band| {
1041- let lo = band * BINS_PER_SBR_BAND;
1042- let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1043- let e: f64 = (lo..hi)
1044- .flat_map(|b| o_spec[b].iter())
1045- .map(|c| f64::from(c.norm_sqr()))
1046- .sum();
1047- (band, e)
1048- })
1049- .collect();
1050- ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
1051- let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect();
1052- selected.sort_unstable();
1053-
1054- let mut out = Vec::with_capacity(selected.len());
1055- for band in selected {
1056- let lo = band * BINS_PER_SBR_BAND;
1057- let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1058- if lo >= hi {
1059- continue;
1060- }
1061- let mut energy = 0.0f64;
1062- let mut direct = 0.0f64;
1063- let mut mirror = 0.0f64;
1064- let mut shift_up = 0.0f64;
1065- let mut shift_down = 0.0f64;
1066- let count = (hi - lo) as f64;
1067- // `i` feeds several derived indices (mirror/shift math below), not a
1068- // plain element access -- an iterator/enumerate rewrite would be
1069- // less readable here, not more.
1070- #[allow(clippy::needless_range_loop)]
1071- for i in lo..hi {
1072- energy += o_spec[i]
1073- .iter()
1074- .map(|c| f64::from(c.norm_sqr()))
1075- .sum::<f64>();
1076- direct += coh(i, i);
1077- mirror += coh(i, hi + lo - 1 - i);
1078- shift_up += coh(i, i + BINS_PER_SBR_BAND);
1079- shift_down += if i >= BINS_PER_SBR_BAND {
1080- coh(i, i - BINS_PER_SBR_BAND)
1081- } else {
1082- 0.0
1083- };
1084- }
1085- out.push((
1086- band as f64 * band_hz,
1087- energy,
1088- direct / count,
1089- mirror / count,
1090- shift_up / count,
1091- shift_down / count,
1092- ));
1093- }
1094- out
1095-}
1096-
1097-/// Round-38, Task 1: sweeps a constant HF-only sample-domain lag `k*64`
1098-/// (`k` in -8..=8; one QMF synthesis slot = 64 output samples) applied ONLY
1099-/// to `o`'s STFT read position, holding `t` fixed at the globally-aligned
1100-/// `ob` offset -- the low band (which drives the global `lag` this window is
1101-/// already re-sliced to via `oa`/`ob`) is never touched by this probe. Per
1102-/// bin, coherence is the SAME "direct" measure `bin_level_conviction` uses
1103-/// (`|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)`), then
1104-/// averaged uniformly over every bin in every HF SBR band from `min_band`
1105-/// upward (both parity regions together, not just the top-energy handful) --
1106-/// a clear peak at k != 0 convicts a constant reference-vs-ours HF alignment
1107-/// offset of that many QMF slots; a flat or zero-peaked curve refutes it.
1108-fn hf_lag_sweep(
1109- o: &[f32],
1110- t: &[f32],
1111- oa: usize,
1112- ob: usize,
1113- n: usize,
1114- min_band: usize,
1115-) -> Vec<(i64, f64)> {
1116- const FFT_LEN: usize = 2048;
1117- const HOP: usize = 1024;
1118- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1119- const MAX_K: i64 = 8;
1120- const SLOT: i64 = 64;
1121- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1122- let probe_bins = ec_dsp::RealFft::<f32>::new(FFT_LEN).spectrum_len();
1123- let num_bands = probe_bins / BINS_PER_SBR_BAND;
1124- let lo_bin = min_band * BINS_PER_SBR_BAND;
1125- let hi_bin = (num_bands * BINS_PER_SBR_BAND).min(probe_bins);
1126- if lo_bin >= hi_bin {
1127- return Vec::new();
1128- }
1129- let hops = if n >= FFT_LEN {
1130- (n - FFT_LEN) / HOP + 1
1131- } else {
1132- 0
1133- };
1134- if hops == 0 {
1135- return Vec::new();
1136- }
1137- let spec_of = |s: &[f32], start: usize| -> Vec<Vec<ec_dsp::Complex<f32>>> {
1138- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1139- let mut spec = vec![Vec::with_capacity(hops); probe_bins];
1140- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); probe_bins];
1141- for h in 0..hops {
1142- let mut block = s[start + h * HOP..start + h * HOP + FFT_LEN].to_vec();
1143- win.apply(&mut block);
1144- rfft.forward(&block, &mut spectrum);
1145- for (b, c) in spectrum.iter().enumerate() {
1146- spec[b].push(*c);
1147- }
1148- }
1149- spec
1150- };
1151- let mut out = Vec::with_capacity((2 * MAX_K + 1) as usize);
1152- for k in -MAX_K..=MAX_K {
1153- let shift = k * SLOT;
1154- // Prefer shifting `o`'s read start (the literal ask), but `o` has no
1155- // samples before its own decode origin -- when the global alignment
1156- // already pins `oa` at (or near) 0, negative `k` has nowhere to read
1157- // from on that side. `coh(o[x], t[y])` only depends on `x - y`, so
1158- // shifting `t`'s read start the OPPOSITE direction instead
1159- // (`ob - shift`) tests the exact same relative offset and `t` (the
1160- // reference, decoded in full) always has the room. Only actually
1161- // falls back for `o`-boundary-starved `k`; the un-shifted `t` path
1162- // above is untouched for every `k` that fits within `o`.
1163- let (o_start, t_start) = {
1164- let os = oa as i64 + shift;
1165- if os >= 0 && os as usize + n <= o.len() {
1166- (os as usize, ob)
1167- } else {
1168- let ts = ob as i64 - shift;
1169- if ts >= 0 && ts as usize + n <= t.len() {
1170- (oa, ts as usize)
1171- } else {
1172- continue;
1173- }
1174- }
1175- };
1176- let o_spec = spec_of(o, o_start);
1177- let t_spec = spec_of(t, t_start);
1178- let mut sum = 0.0f64;
1179- let mut count = 0usize;
1180- for b in lo_bin..hi_bin {
1181- let mut cross_re = 0.0f64;
1182- let mut cross_im = 0.0f64;
1183- let mut o_e = 0.0f64;
1184- let mut t_e = 0.0f64;
1185- for h in 0..hops {
1186- let oc = o_spec[b][h];
1187- let tc = t_spec[b][h];
1188- let cross = oc * tc.conj();
1189- cross_re += f64::from(cross.re);
1190- cross_im += f64::from(cross.im);
1191- o_e += f64::from(oc.norm_sqr());
1192- t_e += f64::from(tc.norm_sqr());
1193- }
1194- let den = (o_e * t_e).sqrt();
1195- if den > 0.0 {
1196- sum += (cross_re * cross_re + cross_im * cross_im).sqrt() / den;
1197- count += 1;
1198- }
1199- }
1200- out.push((k, if count > 0 { sum / count as f64 } else { 0.0 }));
1201- }
1202- out
1203-}
1204-
1205-/// Round-40, Task 1: fine spectral-BIN shift scan on patched HF content.
1206-/// `hf_lag_sweep` (round-38) only tested whole-QMF-slot SAMPLE-domain lags and
1207-/// round-26's `bin_level_conviction` shift columns only tested whole
1208-/// `BINS_PER_SBR_BAND` (8-bin) band shifts; neither ever tried a FEW-bin
1209-/// spectral offset, which is what a half-QMF-band (~4-bin, ~86Hz at this
1210-/// 2048-window scale) carrier convention mismatch on patched content would
1211-/// look like -- it would leave envelope/magnitude tracking (and therefore
1212-/// `hf_lag_sweep`'s k=0 peak) intact while destroying bin-level phase
1213-/// coherence via linear phase drift across the band. The audio itself is
1214-/// never shifted; only the bin INDEX used to pair `o` against `t` moves, by
1215-/// `b` in -7..=+7 (deliberately short of the 8-bin whole-band-shift case
1216-/// round-26 already ruled out). Reports mean direct coherence
1217-/// (`bin_level_conviction`'s same `|sum_h O(h)*conj(T(h))| /
1218-/// sqrt(sum|O|^2*sum|T|^2)` measure) separately over the even-gap [14,28) and
1219-/// odd-gap [28,43) SBR-band regions -- the offset, if real, could differ by
1220-/// patch parity given round-35/36's convention-fix history. A clear peak at
1221-/// `b != 0` (region-dependent sign allowed) convicts a constant sub-band
1222-/// frequency offset; a flat/0-peaked curve refutes it.
1223-fn hf_bin_shift_sweep(
1224- o: &[f32],
1225- t: &[f32],
1226- _rate: u32,
1227- region_lo_band: usize,
1228- region_hi_band: usize,
1229-) -> Vec<(i64, f64)> {
1230- const FFT_LEN: usize = 2048;
1231- const HOP: usize = 1024;
1232- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1233- const MAX_B: i64 = 7;
1234- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1235- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1236- let bins = rfft.spectrum_len();
1237- let n = o.len().min(t.len());
1238- let hops = if n >= FFT_LEN {
1239- (n - FFT_LEN) / HOP + 1
1240- } else {
1241- 0
1242- };
1243- if hops == 0 {
1244- return Vec::new();
1245- }
1246- let mut o_spec = vec![Vec::with_capacity(hops); bins];
1247- let mut t_spec = vec![Vec::with_capacity(hops); bins];
1248- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1249- for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1250- for h in 0..hops {
1251- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1252- win.apply(&mut block);
1253- rfft.forward(&block, &mut spectrum);
1254- for (b, c) in spectrum.iter().enumerate() {
1255- dst[b].push(*c);
1256- }
1257- }
1258- }
1259- let lo_bin = region_lo_band * BINS_PER_SBR_BAND;
1260- let hi_bin = (region_hi_band * BINS_PER_SBR_BAND).min(bins);
1261- let coh = |ob: usize, tb: usize| -> f64 {
1262- if ob >= bins || tb >= bins {
1263- return 0.0;
1264- }
1265- let mut cross_re = 0.0f64;
1266- let mut cross_im = 0.0f64;
1267- let mut o_e = 0.0f64;
1268- let mut t_e = 0.0f64;
1269- for h in 0..hops {
1270- let oc = o_spec[ob][h];
1271- let tc = t_spec[tb][h];
1272- let cross = oc * tc.conj();
1273- cross_re += f64::from(cross.re);
1274- cross_im += f64::from(cross.im);
1275- o_e += f64::from(oc.norm_sqr());
1276- t_e += f64::from(tc.norm_sqr());
1277- }
1278- let den = (o_e * t_e).sqrt();
1279- if den > 0.0 {
1280- (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1281- } else {
1282- 0.0
1283- }
1284- };
1285- let mut out = Vec::with_capacity((2 * MAX_B + 1) as usize);
1286- if lo_bin >= hi_bin {
1287- return out;
1288- }
1289- for b in -MAX_B..=MAX_B {
1290- let mut sum = 0.0f64;
1291- let mut count = 0usize;
1292- for i in lo_bin..hi_bin {
1293- let oi = i as i64 + b;
1294- if oi < 0 || oi as usize >= bins {
1295- continue;
1296- }
1297- sum += coh(oi as usize, i);
1298- count += 1;
1299- }
1300- out.push((b, if count > 0 { sum / count as f64 } else { 0.0 }));
1301- }
1302- out
1303-}
1304-
1305-/// Round-40, Task 2: per-STFT-frame complex-gain fingerprint. For the same
1306-/// top-energy HF bands `bin_level_conviction` picks (ranked by `o`'s own
1307-/// energy), takes each band's single dominant bin (highest total `|O(h)|^2`
1308-/// across hops) and reports the per-hop complex ratio `O(h)/T(h)` trajectory
1309-/// -- `(magnitude, phase_radians)` per STFT frame -- for that bin across
1310-/// every frame. Read afterward, not here: constant magnitude+phase is a pure
1311-/// gain (would predict HIGH coherence, contradicting the low bin-coherence
1312-/// measured elsewhere -- flags a measurement issue, not a real
1313-/// transformation); phase advancing at a roughly fixed per-frame rate is a
1314-/// genuine carrier frequency offset (the rate converts directly to Hz and
1315-/// cross-checks `hf_bin_shift_sweep`'s peak); phase jumping specifically at
1316-/// hop indices lining up with SBR envelope borders is a per-envelope
1317-/// gain/phase re-seed; anything else (magnitude and phase both wandering with
1318-/// no fixed rate) is genuinely uncorrelated content frame to frame.
1319-fn hf_complex_ratio_trajectory(
1320- o: &[f32],
1321- t: &[f32],
1322- rate: u32,
1323- min_band: usize,
1324- top_n: usize,
1325-) -> Vec<(f64, Vec<(f64, f64)>)> {
1326- const FFT_LEN: usize = 2048;
1327- const HOP: usize = 1024;
1328- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1329- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1330- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1331- let bins = rfft.spectrum_len();
1332- let n = o.len().min(t.len());
1333- let hops = if n >= FFT_LEN {
1334- (n - FFT_LEN) / HOP + 1
1335- } else {
1336- 0
1337- };
1338- if hops == 0 {
1339- return Vec::new();
1340- }
1341- let mut o_spec = vec![Vec::with_capacity(hops); bins];
1342- let mut t_spec = vec![Vec::with_capacity(hops); bins];
1343- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1344- for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1345- for h in 0..hops {
1346- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1347- win.apply(&mut block);
1348- rfft.forward(&block, &mut spectrum);
1349- for (b, c) in spectrum.iter().enumerate() {
1350- dst[b].push(*c);
1351- }
1352- }
1353- }
1354- let band_hz = f64::from(rate) / 256.0;
1355- let num_bands = bins / BINS_PER_SBR_BAND;
1356- if min_band >= num_bands {
1357- return Vec::new();
1358- }
1359- let mut ranked: Vec<(usize, f64)> = (min_band..num_bands)
1360- .map(|band| {
1361- let lo = band * BINS_PER_SBR_BAND;
1362- let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1363- let e: f64 = (lo..hi)
1364- .flat_map(|b| o_spec[b].iter())
1365- .map(|c| f64::from(c.norm_sqr()))
1366- .sum();
1367- (band, e)
1368- })
1369- .collect();
1370- ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
1371- let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect();
1372- selected.sort_unstable();
1373-
1374- let mut out = Vec::with_capacity(selected.len());
1375- for band in selected {
1376- let lo = band * BINS_PER_SBR_BAND;
1377- let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1378- if lo >= hi {
1379- continue;
1380- }
1381- let dom = (lo..hi)
1382- .max_by(|&a, &b| {
1383- let ea: f64 = o_spec[a].iter().map(|c| f64::from(c.norm_sqr())).sum();
1384- let eb: f64 = o_spec[b].iter().map(|c| f64::from(c.norm_sqr())).sum();
1385- ea.partial_cmp(&eb).unwrap()
1386- })
1387- .unwrap();
1388- // Complex division `O/T` done by hand (`ec_dsp::Complex` carries no
1389- // `Div` impl -- it is a from-scratch minimal type, see fft.rs): `O *
1390- // conj(T) / |T|^2`.
1391- let traj: Vec<(f64, f64)> = (0..hops)
1392- .map(|h| {
1393- let oc = o_spec[dom][h];
1394- let tc = t_spec[dom][h];
1395- let t_e = f64::from(tc.norm_sqr());
1396- if t_e > 1e-12 {
1397- let (or, oi) = (f64::from(oc.re), f64::from(oc.im));
1398- let (tr, ti) = (f64::from(tc.re), f64::from(tc.im));
1399- let rr = (or * tr + oi * ti) / t_e;
1400- let ri = (oi * tr - or * ti) / t_e;
1401- ((rr * rr + ri * ri).sqrt(), ri.atan2(rr))
1402- } else {
1403- (0.0, 0.0)
1404- }
1405- })
1406- .collect();
1407- out.push((band as f64 * band_hz, traj));
1408- }
1409- out
1410-}
1411-
1412-/// Round-45, Task 3 THIRD WITNESS. Every prior round compared OURS against
1413-/// the REFERENCE directly -- a pairwise measurement that can never say which
1414-/// side is wrong when they disagree. This builds a reference-free model: a
1415-/// pure "plain patch-copy + per-band energy match" reconstruction of HF
1416-/// content from the REFERENCE's own LOW band (the one piece of ground truth
1417-/// both decoders start from and our own low-band round-trip already measures
1418-/// as near-identity), using the verified patch map
1419-/// `[(0,14,14),(3,28,11),(0,39,3),(13,42,1)]` and this file's own established
1420-/// `band_hz = rate/256`, `BINS_PER_SBR_BAND = FFT_LEN/256 = 8` convention
1421-/// (round-14/16; NOT the `rate/128` scale the naive spec reading suggests --
1422-/// that value indexes the QMF/hybrid analysis grid, not this STFT-bin grid,
1423-/// and using it here would be the "trap" that bit round-42 elsewhere in this
1424-/// file. The patch map's own band numbers (14/28/39/42/43) only make sense
1425-/// under the `/256` convention already used everywhere else in this file that
1426-/// touches the patch map -- confirmed by construction, not re-derived here).
1427-///
1428-/// For each HF band in `[14, 43)` and each STFT hop, the simulated bins are
1429-/// the REFERENCE's low-band bins at the patch-mapped source position, then
1430-/// RESCALED per (band, hop) to match the comparison side's own energy in
1431-/// that band/hop -- two separate rescalings, "sim-normalized-to-ours" and
1432-/// "sim-normalized-to-reference" -- so the only thing left for the
1433-/// coherence measure to see is phase/content structure, not a gain
1434-/// difference (the gain question is already closed by prior rounds). Returns
1435-/// `(band, coherence)` pairs for sim-vs-reference and sim-vs-ours.
1436-type BandCoherenceTable = Vec<(usize, f64)>;
1437-
1438-fn hf_patch_simulator(o: &[f32], t: &[f32], rate: u32) -> (BandCoherenceTable, BandCoherenceTable) {
1439- const FFT_LEN: usize = 2048;
1440- const HOP: usize = 1024;
1441- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1442- const PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1443- let _ = rate; // band Hz not needed here; caller converts band index itself.
1444- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1445- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1446- let bins = rfft.spectrum_len();
1447- let n = o.len().min(t.len());
1448- let hops = if n >= FFT_LEN {
1449- (n - FFT_LEN) / HOP + 1
1450- } else {
1451- 0
1452- };
1453- if hops == 0 {
1454- return (Vec::new(), Vec::new());
1455- }
1456- let mut o_spec = vec![Vec::with_capacity(hops); bins];
1457- let mut t_spec = vec![Vec::with_capacity(hops); bins];
1458- let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1459- for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1460- for h in 0..hops {
1461- let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1462- win.apply(&mut block);
1463- rfft.forward(&block, &mut spectrum);
1464- for (b, c) in spectrum.iter().enumerate() {
1465- dst[b].push(*c);
1466- }
1467- }
1468- }
1469- // Plain patch copy: sim's target bins, per hop, are the reference's
1470- // source bins, unmodified (no phase adjustment) -- modelling exactly the
1471- // "plain patch+gain" hypothesis the charter names.
1472- let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f32, 0.0); hops]; bins];
1473- for (src, tgt, width) in PATCHES {
1474- let src_lo = src * BINS_PER_SBR_BAND;
1475- let tgt_lo = tgt * BINS_PER_SBR_BAND;
1476- let len = width * BINS_PER_SBR_BAND;
1477- for i in 0..len {
1478- if src_lo + i >= bins || tgt_lo + i >= bins {
1479- continue;
1480- }
1481- for h in 0..hops {
1482- sim_spec[tgt_lo + i][h] = t_spec[src_lo + i][h];
1483- }
1484- }
1485- }
1486- let num_bands = bins / BINS_PER_SBR_BAND;
1487- let top_band = 43.min(num_bands);
1488- // Per (band, hop) rescale of `sim` to match `target`'s energy in that
1489- // band/hop, then the same magnitude-of-summed-cross-spectrum coherence
1490- // measure every prior round's `coh` helper uses (already scale-invariant
1491- // to a CONSTANT gain across hops; this rescale additionally removes a
1492- // gain that varies hop-to-hop, isolating phase/content agreement).
1493- let band_coherence = |target: &[Vec<ec_dsp::Complex<f32>>]| -> Vec<(usize, f64)> {
1494- (14..top_band)
1495- .map(|band| {
1496- let lo = band * BINS_PER_SBR_BAND;
1497- let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1498- let mut cross_re = 0.0f64;
1499- let mut cross_im = 0.0f64;
1500- let mut sim_e = 0.0f64;
1501- let mut tgt_e = 0.0f64;
1502- for h in 0..hops {
1503- let se: f64 = (lo..hi).map(|b| f64::from(sim_spec[b][h].norm_sqr())).sum();
1504- let te: f64 = (lo..hi).map(|b| f64::from(target[b][h].norm_sqr())).sum();
1505- if se <= 1e-20 || te <= 0.0 {
1506- continue;
1507- }
1508- let scale = (te / se).sqrt() as f32;
1509- for b in lo..hi {
1510- let sc = sim_spec[b][h].scale(scale);
1511- let tc = target[b][h];
1512- let cross = sc * tc.conj();
1513- cross_re += f64::from(cross.re);
1514- cross_im += f64::from(cross.im);
1515- sim_e += f64::from(sc.norm_sqr());
1516- tgt_e += f64::from(tc.norm_sqr());
1517- }
1518- }
1519- let den = (sim_e * tgt_e).sqrt();
1520- let coh = if den > 0.0 {
1521- (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1522- } else {
1523- 0.0
1524- };
1525- (band, coh)
1526- })
1527- .collect()
1528- };
1529- (band_coherence(&t_spec), band_coherence(&o_spec))
1530-}
1531-
1532-/// (Round-46) The QMF-domain exact version of [`hf_patch_simulator`]: same
1533-/// plain-patch+gain model, same verified patch map, but read through the
1534-/// crate's own [`ec_aac::sbr_qmf::HfAnalysis`] (64-band, `rate/128`-wide
1535-/// bands -- exactly the patch map's own band unit) instead of an 8-bin-wide
1536-/// STFT approximation, closing the "too crude to reach a verdict" gap
1537-/// round-45's STFT simulator hit. Validated by
1538-/// `hf_analysis_self_consistency_control` in `sbr_qmf.rs` before use here
1539-/// (own-band plurality + self-coherence + round-trip control). Same
1540-/// per-(band, window) energy-rescale-then-coherence method as the STFT
1541-/// version, windowed over `WIN` consecutive QMF slots (`WIN * SYNTHESIS_BANDS
1542-/// = 1024` samples, matching the STFT version's hop) so the rescale has
1543-/// enough samples to estimate energy from, not so many that within-window
1544-/// phase drift is averaged away.
1545-const QMF_PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1546-
1547-/// Shared build step for the QMF-domain third-witness instruments: both
1548-/// PCMs read through [`ec_aac::sbr_qmf::HfAnalysis`], plus the plain
1549-/// patch-copy simulation of the reference's own low band, all in the
1550-/// `(band, slot)` domain. Returns `(ours, reference, sim)`.
1551-/// `[band][slot]` complex QMF-domain series.
1552-type QmfBandSlots = Vec<Vec<ec_dsp::Complex<f64>>>;
1553-
1554-fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBandSlots) {
1555- use ec_aac::sbr_qmf::{HfAnalysis, SYNTHESIS_BANDS};
1556- let n = o.len().min(t.len());
1557- let slots = n / SYNTHESIS_BANDS;
1558- let analyze = |pcm: &[f32]| -> QmfBandSlots {
1559- let mut ana = HfAnalysis::new();
1560- let mut out: QmfBandSlots = (0..SYNTHESIS_BANDS)
1561- .map(|_| Vec::with_capacity(slots))
1562- .collect();
1563- for s in 0..slots {
1564- let mut chunk = [0.0f32; SYNTHESIS_BANDS];
1565- chunk.copy_from_slice(&pcm[s * SYNTHESIS_BANDS..(s + 1) * SYNTHESIS_BANDS]);
1566- let sub = ana.process_slot(&chunk);
1567- for (b, c) in sub.iter().enumerate() {
1568- out[b].push(*c);
1569- }
1570- }
1571- out
1572- };
1573- let o_spec = analyze(o);
1574- let t_spec = analyze(t);
1575- // Plain patch copy: sim's target-band slot series is the reference's
1576- // source-band slot series, unmodified.
1577- let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f64, 0.0); slots]; SYNTHESIS_BANDS];
1578- for (src, tgt, width) in QMF_PATCHES {
1579- for i in 0..width {
1580- if src + i >= SYNTHESIS_BANDS || tgt + i >= SYNTHESIS_BANDS {
1581- continue;
1582- }
1583- sim_spec[tgt + i] = t_spec[src + i].clone();
1584- }
1585- }
1586- (o_spec, t_spec, sim_spec)
1587-}
1588-
1589-/// Returns `(sim-vs-reference, sim-vs-ours, ours-vs-reference)` -- the last
1590-/// pairing (round-48, Task 4a) is the ultimate content-match witness: how
1591-/// well our actual HF QMF content agrees with the reference's, with no
1592-/// simulator in between.
1593-fn hf_patch_simulator_qmf(
1594- o: &[f32],
1595- t: &[f32],
1596-) -> (BandCoherenceTable, BandCoherenceTable, BandCoherenceTable) {
1597- use ec_aac::sbr_qmf::SYNTHESIS_BANDS;
1598- const WIN: usize = 16;
1599- let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1600- let slots = sim_spec.first().map(Vec::len).unwrap_or(0);
1601- if slots < WIN {
1602- return (Vec::new(), Vec::new(), Vec::new());
1603- }
1604- let top_band = 43.min(SYNTHESIS_BANDS);
1605- let windows = slots / WIN;
1606- let band_coherence = |source: &[Vec<ec_dsp::Complex<f64>>],
1607- target: &[Vec<ec_dsp::Complex<f64>>]|
1608- -> Vec<(usize, f64)> {
1609- (14..top_band)
1610- .map(|band| {
1611- let mut cross_re = 0.0f64;
1612- let mut cross_im = 0.0f64;
1613- let mut sim_e = 0.0f64;
1614- let mut tgt_e = 0.0f64;
1615- for w in 0..windows {
1616- let lo = w * WIN;
1617- let hi = lo + WIN;
1618- let se: f64 = source[band][lo..hi]
1619- .iter()
1620- .map(|c| c.re * c.re + c.im * c.im)
1621- .sum();
1622- let te: f64 = target[band][lo..hi]
1623- .iter()
1624- .map(|c| c.re * c.re + c.im * c.im)
1625- .sum();
1626- if se <= 1e-20 || te <= 0.0 {
1627- continue;
1628- }
1629- let scale = (te / se).sqrt();
1630- for i in lo..hi {
1631- let sc = source[band][i].scale(scale);
1632- let tc = target[band][i];
1633- let cross = sc * tc.conj();
1634- cross_re += cross.re;
1635- cross_im += cross.im;
1636- sim_e += sc.re * sc.re + sc.im * sc.im;
1637- tgt_e += tc.re * tc.re + tc.im * tc.im;
1638- }
1639- }
1640- let den = (sim_e * tgt_e).sqrt();
1641- let coh = if den > 0.0 {
1642- (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1643- } else {
1644- 0.0
1645- };
1646- (band, coh)
1647- })
1648- .collect()
1649- };
1650- (
1651- band_coherence(&sim_spec, &t_spec),
1652- band_coherence(&sim_spec, &o_spec),
1653- band_coherence(&o_spec, &t_spec),
1654- )
1655-}
1656-
1657-/// (Round-46, Task 2) Per-band 2nd-order complex prediction transfer fit
1658-/// between the plain-copy sim series and the REFERENCE's own HF series for
1659-/// that band: `ref[l] ~= a0*sim[l] + a1*sim[l-1] + a2*sim[l-2]`, least
1660-/// squares over the whole file -- the same shape `sbr_hf::generate`'s own
1661-/// chirp filter has (`y = residual + ca1*y[n-1] + ca2*y[n-2]`, an IIR rather
1662-/// than this FIR, but both are order-2 linear reshapings of the same copied
1663-/// content), so the fitted taps are directly comparable in spirit to our own
1664-/// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is
1665-/// also just a plain copy here", taps with real weight on lag 1/2 mean a
1666-/// genuine order-2 transformation is present.
1667-/// `target_is_ours`: fit against our own decode (`o_spec`) instead of the
1668-/// reference's (`t_spec`) -- same `sim` (built from the reference's own low
1669-/// band either way), so the two calls' fitted taps are directly comparable:
1670-/// what transform sim would need to become ours vs. to become the reference.
1671-#[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout
1672-fn hf_patch_transfer_fit(
1673- o: &[f32],
1674- t: &[f32],
1675- bands: &[usize],
1676- target_is_ours: bool,
1677-) -> Vec<(usize, [ec_dsp::Complex<f64>; 3])> {
1678- let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1679- let target_spec = if target_is_ours { &o_spec } else { &t_spec };
1680- let mut results = Vec::new();
1681- for &band in bands {
1682- if band >= sim_spec.len() {
1683- continue;
1684- }
1685- let sim_raw = &sim_spec[band];
1686- let ref_raw = &target_spec[band];
1687- let len = sim_raw.len().min(ref_raw.len());
1688- if len < 8 {
1689- continue;
1690- }
1691- // Normalize each series to unit RMS first: the raw QMF-domain
1692- // amplitudes differ by orders of magnitude (sim carries no envelope
1693- // gain, `ref` does), which would otherwise make every fitted
1694- // coefficient collapse toward the gain ratio rather than the
1695- // fraction-of-`ref`-explained-by-which-lag this fit is meant to
1696- // read off.
1697- let rms = |s: &[ec_dsp::Complex<f64>]| -> f64 {
1698- (s[..len]
1699- .iter()
1700- .map(|c| c.re * c.re + c.im * c.im)
1701- .sum::<f64>()
1702- / len as f64)
1703- .sqrt()
1704- .max(1e-300)
1705- };
1706- let sim_scale = 1.0 / rms(sim_raw);
1707- let ref_scale = 1.0 / rms(ref_raw);
1708- let sim: Vec<ec_dsp::Complex<f64>> =
1709- sim_raw[..len].iter().map(|c| c.scale(sim_scale)).collect();
1710- let refb: Vec<ec_dsp::Complex<f64>> =
1711- ref_raw[..len].iter().map(|c| c.scale(ref_scale)).collect();
1712- let sim = &sim[..];
1713- let refb = &refb[..];
1714- // Complex 3x3 Hermitian normal equations: r[i][j] = sum sim[l-i] conj(sim[l-j]),
1715- // p[i] = sum sim[l-i] conj(ref[l])... solved as R^T a = p with R real basis in
1716- // complex arithmetic (Gaussian elimination with partial pivoting by magnitude).
1717- let mut r = [[ec_dsp::Complex::new(0.0f64, 0.0); 3]; 3];
1718- let mut p = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1719- for l in 2..len {
1720- let s = [sim[l], sim[l - 1], sim[l - 2]];
1721- let y = refb[l];
1722- for i in 0..3 {
1723- p[i] = p[i] + s[i].conj() * y;
1724- for j in 0..3 {
1725- r[i][j] = r[i][j] + s[i].conj() * s[j];
1726- }
1727- }
1728- }
1729- // Gaussian elimination on the augmented [r | p] system.
1730- let mut aug = r;
1731- let mut rhs = p;
1732- for col in 0..3 {
1733- let mut piv = col;
1734- let mut best = aug[col][col].norm_sqr();
1735- for row in (col + 1)..3 {
1736- let m = aug[row][col].norm_sqr();
1737- if m > best {
1738- best = m;
1739- piv = row;
1740- }
1741- }
1742- if best < 1e-24 {
1743- continue;
1744- }
1745- aug.swap(col, piv);
1746- rhs.swap(col, piv);
1747- let inv = aug[col][col].conj().scale(1.0 / best);
1748- for row in (col + 1)..3 {
1749- let f = aug[row][col] * inv;
1750- for k in 0..3 {
1751- aug[row][k] = aug[row][k] - f * aug[col][k];
1752- }
1753- rhs[row] = rhs[row] - f * rhs[col];
1754- }
1755- }
1756- let mut a = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1757- for row in (0..3).rev() {
1758- let mut acc = rhs[row];
1759- for k in (row + 1)..3 {
1760- acc = acc - aug[row][k] * a[k];
1761- }
1762- let d = aug[row][row];
1763- a[row] = if d.norm_sqr() > 1e-24 {
1764- acc * d.conj().scale(1.0 / d.norm_sqr())
1765- } else {
1766- ec_dsp::Complex::new(0.0, 0.0)
1767- };
1768- }
1769- results.push((band, a));
1770- }
1771- results
1772-}
1773-
1774-/// A file discovered under the user's own media directories: its path, which
1775-/// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
1776-/// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
1777-/// only to draw the below/above-crossover line for localization, not as a
1778-/// spec-exact `kx` band edge.
1779-struct Candidate {
1780- path: PathBuf,
1781- /// Which AAC stream, 0-based among AAC streams only -- what
1782- /// `extract_from` selects out of the demuxer's stream list.
1783- aac_stream: usize,
1784- /// The same stream's absolute ffprobe/ffmpeg index -- what `-map`
1785- /// selects, and not the same number when the container also carries a
1786- /// non-AAC audio track before it (FMJ's mkv has an AC-3 track between its
1787- /// two AAC ones).
1788- ffmpeg_stream: usize,
1789- crossover_hz: f64,
1790-}
1791-
1792-/// Round-20 residual/side-info correlation. Builds a (frame x band) residual
1793-/// ENERGY grid at AU-aligned 2048-output-sample blocks -- a plain (2x) SBR
1794-/// stream reconstructs exactly one 2048-sample block per core access unit,
1795-/// so `n`-th block lines up 1:1 with `ec_aac::sbr_sideinfo_log()`'s `frame`
1796-/// counter -- then cross-tabulates that grid against every side-info feature
1797-/// the log carries. FFT is linear, so `FFT(o_block) - FFT(t_block) ==
1798-/// FFT(o_block - t_block)`: the residual's own per-bin energy is obtained
1799-/// directly from each side's spectrum without ever materializing a
1800-/// time-domain residual array. `band` is the same `rate/256`-wide index
1801-/// domain `per_band_correlation`/`tables.kx`/`f_high`/`f_noise` all already
1802-/// share (measured in round-14/round-16), so a side-info row's `f_high`/
1803-/// `f_noise` boundaries index straight into this grid's bins with no
1804-/// rescaling.
1805-fn residual_sideinfo_analysis(o: &[f32], t: &[f32], oa: usize, ob: usize, rate: u32, ch: usize) {
1806- let rows: Vec<_> = ec_aac::sbr_sideinfo_log()
1807- .into_iter()
1808- .filter(|r| r.ch == ch)
1809- .collect();
1810- if rows.is_empty() {
1811- eprintln!(" ch{ch} SIDEINFO: no rows logged (set EC_AAC_SBR_SIDEINFO_DEBUG too)");
1812- return;
1813- }
1814- const FFT_LEN: usize = 2048;
1815- let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1816- let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1817- let bins = rfft.spectrum_len();
1818- let mut o_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1819- let mut t_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1820-
1821- // Per-frame residual bin-energy vector (index = `band`, per-bin, not yet
1822- // grouped) and, alongside it, a per-bin peakiness ratio (own-bin energy
1823- // vs its 3-bin neighbourhood mean) used by the whiteness check.
1824- let mut energy: std::collections::HashMap<usize, Vec<f64>> = std::collections::HashMap::new();
1825- for row in &rows {
1826- if energy.contains_key(&row.frame) {
1827- continue;
1828- }
1829- let base_o = oa + row.frame * FFT_LEN;
1830- let base_t = ob + row.frame * FFT_LEN;
1831- if base_o + FFT_LEN > o.len() || base_t + FFT_LEN > t.len() {
1832- continue;
1833- }
1834- let mut ob_win = o[base_o..base_o + FFT_LEN].to_vec();
1835- let mut tb_win = t[base_t..base_t + FFT_LEN].to_vec();
1836- win.apply(&mut ob_win);
1837- win.apply(&mut tb_win);
1838- rfft.forward(&ob_win, &mut o_spec);
1839- rfft.forward(&tb_win, &mut t_spec);
1840- let e: Vec<f64> = o_spec
1841- .iter()
1842- .zip(&t_spec)
1843- .map(|(a, b)| f64::from((*a - *b).norm_sqr()))
1844- .collect();
1845- energy.insert(row.frame, e);
1846- }
1847- if energy.is_empty() {
1848- eprintln!(" ch{ch} SIDEINFO: no frame overlapped the aligned window");
1849- return;
1850- }
1851- // SBR-band-index units (`kx`/`k2`/`f_high`/`f_noise`) are `band_hz =
1852- // rate/256` wide; FFT bins here are `bin_hz = rate/FFT_LEN` wide. The
1853- // ratio `band_hz/bin_hz = FFT_LEN/256 = 8` is rate-independent, matching
1854- // `per_band_correlation`'s own `lo = band*band_hz/bin_hz` conversion --
1855- // one SBR band is exactly 8 of these FFT bins, never 1.
1856- const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1857- let band_range = |lo: i64, hi: i64| -> (usize, usize) {
1858- let lo = ((lo.max(0) as usize) * BINS_PER_SBR_BAND).min(bins);
1859- let hi = (((hi.max(0) as usize) * BINS_PER_SBR_BAND).max(lo + 1)).min(bins);
1860- (lo, hi)
1861- };
1862- let sum_range = |e: &[f64], lo: usize, hi: usize| -> f64 { e[lo..hi].iter().sum() };
1863-
1864- // --- predictor 1: add_harmonic bands (and their immediate neighbours) ---
1865- let (mut harm_sum, mut harm_n) = (0.0f64, 0usize);
1866- let (mut noharm_sum, mut noharm_n) = (0.0f64, 0usize);
1867- let (mut adj_sum, mut adj_n) = (0.0f64, 0usize);
1868- for row in &rows {
1869- let Some(e) = energy.get(&row.frame) else {
1870- continue;
1871- };
1872- let Some(harm) = &row.add_harmonic else {
1873- continue;
1874- };
1875- for (i, &flag) in harm.iter().enumerate() {
1876- let (lo, hi) = match (row.f_high.get(i), row.f_high.get(i + 1)) {
1877- (Some(&a), Some(&b)) => band_range(a, b),
1878- _ => continue,
1879- };
1880- let s = sum_range(e, lo, hi);
1881- let cells = (hi - lo).max(1);
1882- if flag != 0 {
1883- harm_sum += s / cells as f64;
1884- harm_n += 1;
1885- } else {
1886- noharm_sum += s / cells as f64;
1887- noharm_n += 1;
1888- }
1889- // adjacent band (off-by-one probe): the band one slot up.
1890- if flag != 0
1891- && let (Some(&a2), Some(&b2)) = (row.f_high.get(i + 1), row.f_high.get(i + 2))
1892- {
1893- let (lo2, hi2) = band_range(a2, b2);
1894- adj_sum += sum_range(e, lo2, hi2) / (hi2 - lo2).max(1) as f64;
1895- adj_n += 1;
1896- }
1897- }
1898- }
1899-
1900- // --- predictor 2: envelope time borders vs envelope interior ---
1901- // Envelope borders are in `t_env` (pre-`RATE`-scale envelope time-slot
1902- // units); one unit is `RATE(2) * SYNTHESIS_BANDS(64) = 128` output
1903- // samples. Time-domain residual energy (broadband, not per-band) near
1904- // (+/-64 samples) each INTERIOR border vs the envelope's own midpoint.
1905- let (mut border_sum, mut border_n) = (0.0f64, 0usize);
1906- let (mut mid_sum, mut mid_n) = (0.0f64, 0usize);
1907- let sample_energy = |global: usize| -> Option<f64> {
1908- let oi = oa + global;
1909- let ti = ob + global;
1910- if oi >= o.len() || ti >= t.len() {
1911- return None;
1912- }
1913- let d = f64::from(o[oi]) - f64::from(t[ti]);
1914- Some(d * d)
1915- };
1916- for row in &rows {
1917- let frame_base = row.frame * FFT_LEN;
1918- for w in row.t_env.windows(2) {
1919- let (b0, b1) = (w[0] * 128, w[1] * 128);
1920- if b1 <= b0 {
1921- continue;
1922- }
1923- let mid = (b0 + b1) / 2;
1924- for d in -64i64..=64 {
1925- let s0 = b0 + d;
1926- if s0 >= 0
1927- && let Some(v) = sample_energy(frame_base + s0 as usize)
1928- {
1929- border_sum += v;
1930- border_n += 1;
1931- }
1932- }
1933- for off in 0..(b1 - b0).min(256) {
1934- let s = mid - (b1 - b0).min(256) / 2 + off;
1935- if s >= 0
1936- && (s - mid).abs() > 64
1937- && let Some(v) = sample_energy(frame_base + s as usize)
1938- {
1939- mid_sum += v;
1940- mid_n += 1;
1941- }
1942- }
1943- }
1944- }
1945-
1946- // --- predictor 3: hold-state (apply_last) vs fresh-payload frames ---
1947- let (mut hold_sum, mut hold_n) = (0.0f64, 0usize);
1948- let (mut fresh_sum, mut fresh_n) = (0.0f64, 0usize);
1949- for row in &rows {
1950- let Some(e) = energy.get(&row.frame) else {
1951- continue;
1952- };
1953- let total: f64 = e.iter().sum();
1954- if row.source == "hold" {
1955- hold_sum += total;
1956- hold_n += 1;
1957- } else {
1958- fresh_sum += total;
1959- fresh_n += 1;
1960- }
1961- }
1962-
1963- // --- predictor 4: frame immediately after a coupling flip ---
1964- let (mut flip_sum, mut flip_n) = (0.0f64, 0usize);
1965- let (mut noflip_sum, mut noflip_n) = (0.0f64, 0usize);
1966- let mut sorted = rows.clone();
1967- sorted.sort_by_key(|r| r.frame);
1968- for pair in sorted.windows(2) {
1969- let (prev, cur) = (&pair[0], &pair[1]);
1970- let Some(e) = energy.get(&cur.frame) else {
1971- continue;
1972- };
1973- let total: f64 = e.iter().sum();
1974- if cur.coupling != prev.coupling {
1975- flip_sum += total;
1976- flip_n += 1;
1977- } else {
1978- noflip_sum += total;
1979- noflip_n += 1;
1980- }
1981- }
1982-
1983- // --- predictor 5: residual scaling per invf_mode level, per noise band ---
1984- let mut per_level = [(0.0f64, 0usize); 4];
1985- for row in &rows {
1986- let Some(e) = energy.get(&row.frame) else {
1987- continue;
1988- };
1989- for (i, &mode) in row.invf_mode.iter().enumerate() {
1990- let (lo, hi) = match (row.f_noise.get(i), row.f_noise.get(i + 1)) {
1991- (Some(&a), Some(&b)) => band_range(a, b),
1992- _ => continue,
1993- };
1994- let cells = (hi - lo).max(1);
1995- let level = (mode as usize).min(3);
1996- per_level[level].0 += sum_range(e, lo, hi) / cells as f64;
1997- per_level[level].1 += 1;
1998- }
1999- }
2000-
crates/ec-aac/tests/sbr_real_library/chunk_a.rsadded+1243 -0
@@ -0,0 +1,1243 @@
1+//! SBR real-library checks and probes, part A.
2+
3+use super::*;
4+
5+/// Root-cause triage (round-51): is a real file's SBR-chain break actually
6+/// downstream of a broken LC core, or does the core decode cleanly and the
7+/// break lives only in the SBR chain layered on top of it? Prints a
8+/// core-rate correlation per channel; not asserted on, this is a diagnostic,
9+/// not a regression gate (the asserted gate is
10+/// `sbr_real_library_matches_reference`, which already covers the full-band
11+/// SBR-reconstructed output).
12+///
13+/// Round-61: this printed corr 0.402349 for reeln ch0 while that file's
14+/// core is provably fine (the asserted reference gate scores its below-5kHz
15+/// band 0.999988, and `full_chain_low_band_matches_own_core` scores this very
16+/// core-only PCM 0.998 against our own full chain). The number was the
17+/// instrument, not the codec: `robust_lag_topk`'s stride-11 coarse grid
18+/// cannot see a 1-sample-wide correlation peak, so its top-K was ranked from
19+/// noise. At the true lag -- 481, ffmpeg's resampler delay, the same lag FMJ
20+/// reads -- these two signals correlate 0.999845. The search here is now
21+/// stride-1 (`exhaustive_lag_correlation`), and both sides are low-passed at
22+/// `0.9 * crossover` first, since only the reference side (ffmpeg's full SBR
23+/// reconstruction, resampled down to the core rate) can hold anything above
24+/// the crossover at all.
25+#[test]
26+pub(super) fn core_only_matches_reference() {
27+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
28+ if !have_ffmpeg() {
29+ eprintln!("SKIP: ffmpeg not on PATH");
30+ return;
31+ }
32+ for c in &candidates() {
33+ let Some((ours, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else {
34+ eprintln!("SKIP {}: could not core-decode", c.path.display());
35+ continue;
36+ };
37+ let theirs = ffmpeg_decode_at_rate(&c.path, c.ffmpeg_stream, ours.len(), core_rate);
38+ println!(
39+ "{} core-only ({} ch, {} Hz):",
40+ c.path.display(),
41+ ours.len(),
42+ core_rate
43+ );
44+ let cutoff = c.crossover_hz * 0.9;
45+ for (ch, (o, t)) in ours.iter().zip(&theirs).enumerate() {
46+ let ol = lowpass(o, core_rate, cutoff);
47+ let tl = lowpass(t, core_rate, cutoff);
48+ let (mut lag, mut corr, mut at_edge) =
49+ exhaustive_lag_correlation(&ol, &tl, PLAIN_LAG_MAX);
50+ if at_edge {
51+ (lag, corr, at_edge) = exhaustive_lag_correlation(&ol, &tl, SEARCH_LAG_MAX);
52+ }
53+ let edge = if at_edge {
54+ " (AT SEARCH BOUND -- noise, not a measurement)"
55+ } else {
56+ ""
57+ };
58+ println!(" ch{ch}: below {cutoff:.0}Hz lag {lag}, corr {corr:.6}{edge}");
59+ }
60+ }
61+}
62+
63+/// Round-51 triage: dumps `kx`/`k2` (the SBR crossover/top band) for the
64+/// first several frames of every candidate, unconditionally (no ffmpeg
65+/// needed) -- a wrong `kx` would corrupt bands BELOW the crossover too, not
66+/// just the HF-generated ones, since `adjust()` gain-scales everything from
67+/// `kx` up, and `kx` computed too low would pull real core content into
68+/// that scaling.
69+#[test]
70+pub(super) fn dump_sideinfo_kx() {
71+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
72+ let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
73+ for c in &candidates() {
74+ let Some((asc, aus)) = extract_aac_track(&c.path, c.aac_stream) else {
75+ continue;
76+ };
77+ let Ok(mut decoder) = AacDecoder::with_config_bytes(&asc) else {
78+ continue;
79+ };
80+ let before = ec_aac::sbr_sideinfo_log().len();
81+ for au in aus.iter().take(50) {
82+ let _ = decoder.decode(au, None);
83+ }
84+ let rows = ec_aac::sbr_sideinfo_log();
85+ println!("{}:", c.path.display());
86+ for row in rows[before..].iter().filter(|r| r.ch == 0).take(6) {
87+ println!(
88+ " frame={} source={} kx={} k2={} t_env={:?} f_high={:?}",
89+ row.frame, row.source, row.kx, row.k2, row.t_env, row.f_high
90+ );
91+ }
92+ }
93+}
94+
95+/// Round-51 triage: FMJ's full-chain best-lag search (`LAG_MAX` = 4000)
96+/// finds no usable alignment (|corr| ~0.02) even though the core-only
97+/// decode matches almost exactly -- this widens the search far past
98+/// `LAG_MAX` to see whether the true alignment just lies outside the normal
99+/// bound (a large, rate-family-specific extra delay) rather than the SBR
100+/// content itself being wrong.
101+#[test]
102+pub(super) fn wide_lag_search_full_chain() {
103+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
104+ if !have_ffmpeg() {
105+ eprintln!("SKIP: ffmpeg not on PATH");
106+ return;
107+ }
108+ for c in &candidates() {
109+ let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
110+ continue;
111+ };
112+ if sbr != ec_aac::SbrSupport::V1 {
113+ continue;
114+ }
115+ let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len());
116+ let o = &ours[0];
117+ let t = &theirs[0];
118+ println!(
119+ "{} ({} Hz): ours len={} theirs len={}",
120+ c.path.display(),
121+ rate,
122+ o.len(),
123+ t.len()
124+ );
125+ const COARSE: usize = 4096;
126+ const WIDE_LAG_MAX: i64 = 200_000;
127+ let mut best = (0i64, -1.0f64);
128+ let mut lag = -WIDE_LAG_MAX;
129+ while lag <= WIDE_LAG_MAX {
130+ let (oa, ob) = if lag >= 0 {
131+ (0usize, lag as usize)
132+ } else {
133+ ((-lag) as usize, 0usize)
134+ };
135+ if oa + COARSE <= o.len() && ob + COARSE <= t.len() {
136+ let c = correlation(&o[oa..oa + COARSE], &t[ob..ob + COARSE]).abs();
137+ if c > best.1 {
138+ best = (lag, c);
139+ }
140+ }
141+ lag += 97; // odd stride so it doesn't alias against 2048-sample AU boundaries
142+ }
143+ println!(" widest coarse best: lag={} |corr|={:.4}", best.0, best.1);
144+ }
145+}
146+
147+/// Round-51 triage: compares OUR full-chain (SBR-reconstructed) output's
148+/// low band directly against OUR OWN core-only decode of the same stream --
149+/// no reference decoder involved. `v[0..kx]` in `sbr_chain.rs` is a literal
150+/// copy of the same core analysis QMF data the core-only path also
151+/// produces, so if the synthesis/gain-adjust stage is corrupting even that
152+/// untouched region, this shows a real self-inconsistency with no external
153+/// factor (alignment against a reference, different tool, etc.) to blame.
154+#[test]
155+pub(super) fn full_chain_low_band_matches_own_core() {
156+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
157+ for c in &candidates() {
158+ let Some((core, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else {
159+ continue;
160+ };
161+ let Some((full, sbr, full_rate)) = our_decode(&c.path, c.aac_stream) else {
162+ continue;
163+ };
164+ if sbr != ec_aac::SbrSupport::V1 {
165+ continue;
166+ }
167+ println!(
168+ "{} (core {} Hz, full {} Hz):",
169+ c.path.display(),
170+ core_rate,
171+ full_rate
172+ );
173+ for ch in 0..core.len().min(full.len()) {
174+ // Naive nearest-neighbor 2x upsample of the core so it lines up
175+ // sample-for-sample with the full-chain output's rate --
176+ // crude, but a low-pass well below the core Nyquist erases the
177+ // stairstep artifacts this introduces.
178+ let up: Vec<f32> = core[ch].iter().flat_map(|&s| [s, s]).collect();
179+ let cutoff = f64::from(core_rate) * 0.4;
180+ let ol = lowpass(&full[ch], full_rate, cutoff);
181+ let ul = lowpass(&up, full_rate, cutoff);
182+ // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's
183+ // original bound) first, widen to `SEARCH_LAG_MAX` only if that
184+ // narrow search hit its own edge (`at_edge`). A single shared
185+ // wide bound was tried first (round-54) and, unconditionally
186+ // widening this comparison, flipped reeln from its correct
187+ // small-lag answer (-576, corr 0.9967) to a wrong, noise-driven
188+ // distant one (-912, corr -0.295) -- a genuinely low-quality
189+ // low-passed signal's coarse correlation surface has enough
190+ // stray peaks over a 100_000-wide range to beat a real but
191+ // modest true peak. Escalating only when the narrow bound
192+ // proves insufficient (FMJ's own core-vs-full delay lands AT
193+ // the 20_000 edge, corr 0.217393 there, the same edge-noise
194+ // class the reference-vs-ours gate had) gets both files right
195+ // without exposing the well-behaved one to the wider bound's
196+ // noise floor.
197+ const WIDE_LAG_MAX: i64 = 20_000;
198+ // Top-K refinement, not the single coarse winner: FMJ's single
199+ // coarse pick landed on an in-bounds noise peak (lag 18995,
200+ // corr 0.10) while its true alignment scores >0.99 on refine.
201+ // A winner at the bound widens once, then is asserted off it.
202+ let (mut lag, mut corr, mut at_edge) =
203+ robust_lag_topk(&ol, &ul, WIDE_LAG_MAX, core_rate, 8);
204+ let mut bound = WIDE_LAG_MAX;
205+ // A sub-bar winner inside the narrow bound is the same symptom
206+ // (true peak outside the search), so it widens too.
207+ if at_edge || corr < 0.99 {
208+ bound = SEARCH_LAG_MAX;
209+ (lag, corr, at_edge) = robust_lag_topk(&ol, &ul, SEARCH_LAG_MAX, core_rate, 8);
210+ }
211+ println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");
212+ assert!(
213+ !at_edge,
214+ "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \
215+ search bound -- corr {corr:.6} is noise, not a measurement",
216+ c.path.display()
217+ );
218+ assert!(
219+ corr >= 0.99,
220+ "{} ch{ch}: full-chain low band vs our own core-only decode \
221+ corr {corr:.6} at measured lag {lag} < 0.99 -- the \
222+ synthesis/gain-adjust stage is corrupting even the untouched \
223+ low-band region copied straight from core analysis",
224+ c.path.display()
225+ );
226+ }
227+ }
228+}
229+
230+/// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real
231+/// file each, whose sample rate, bitrate and content all differ at once),
232+/// every row here decodes the SAME synthesized source (three summed sine
233+/// sweeps 100 Hz-18 kHz + seeded pink noise, per-channel phase offset),
234+/// varying only sample rate (44100/48000) and bitrate (32k/48k/64k/96k,
235+/// which sweeps the SBR crossover `kx`/`k2`), so a break tied to a rate
236+/// FAMILY or to `kx` GEOMETRY shows as a pattern across the table instead
237+/// of being confounded with one file's own content. `aac_low` control rows
238+/// (no SBR at all) prove the harness itself -- container extraction,
239+/// decode, correlation -- is sound before the HE-AAC rows next to them are
240+/// trusted; those are the only asserted numbers here, everything else is
241+/// instrumentation for the ledger, not a regression gate yet.
242+///
243+/// Env-gated on `EC_AAC_HEAAC_FIXTURES` (defaults to the same
244+/// `<repo>/.cache/heaac-fixtures` `scripts/aac-tables/make-heaac-fixtures.sh`
245+/// writes to) -- skips loudly, generates nothing itself, when that
246+/// directory is absent.
247+#[test]
248+pub(super) fn synthetic_heaac_matrix() {
249+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
250+ if !have_ffmpeg() {
251+ eprintln!("SKIP: ffmpeg not on PATH");
252+ return;
253+ }
254+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
255+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
256+ let dir = PathBuf::from(dir);
257+ if !require_fixture(&dir, "scripts/aac-tables/make-heaac-fixtures.sh") {
258+ return;
259+ }
260+ let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
261+ println!(
262+ "{:>5} {:>6} {:>4} {:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
263+ "rate",
264+ "kbps",
265+ "prof",
266+ "kx",
267+ "k2",
268+ "full",
269+ "below",
270+ "above",
271+ "lag",
272+ "ours_v_core",
273+ "ovc_lag",
274+ "core_v_ref",
275+ "cvr_lag",
276+ "core_rate",
277+ "full_rate"
278+ );
279+ // Wide enough that the WIDE_LAG_MAX==LC's own decoder priming delay
280+ // (2048) plus a full SBR-chain worth of extra delay (a few thousand
281+ // samples at the doubled/full output rate) both land well inside it,
282+ // not right at the edge the way the plain (LAG_MAX=4000) search did.
283+ const WIDE_LAG_MAX: i64 = 20_000;
284+ // Floor: the matrix is 2 rates x 4 bitrates x 2 profiles. Without a count
285+ // the whole test is green having probed nothing, which is the same
286+ // false-green this file's `require_fixture` exists to kill.
287+ let mut probed = 0usize;
288+ for rate in [48_000u32, 44_100] {
289+ for br in ["32k", "48k", "64k", "96k"] {
290+ // LC first: its winning lag is the pure container/decoder
291+ // priming delay with no SBR chain involved, and is reused below
292+ // as the anchor for the HE row's own delay-candidate probe.
293+ let mut lc_lag: Option<i64> = None;
294+ for (profile, prefix) in [("LC", "lc"), ("HE", "heaac")] {
295+ let path = dir.join(format!("{prefix}_{rate}_{br}.m4a"));
296+ if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
297+ continue;
298+ }
299+ probed += 1;
300+ let before = ec_aac::sbr_sideinfo_log().len();
301+ let Some((ours, _sbr, our_rate)) = our_decode(&path, 0) else {
302+ eprintln!("SKIP {}: could not decode", path.display());
303+ continue;
304+ };
305+ let rows = ec_aac::sbr_sideinfo_log();
306+ let (kx, k2) = rows[before..]
307+ .iter()
308+ .find(|r| r.ch == 0)
309+ .map(|r| (r.kx, r.k2))
310+ .unwrap_or((-1, -1));
311+ let theirs = ffmpeg_decode(&path, 0, ours.len());
312+ let o = &ours[0];
313+ let t = &theirs[0];
314+ const TOPK: usize = 5;
315+ let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK);
316+ assert!(
317+ !edge,
318+ "{}: {profile} row's refined winning lag {lag} sits at the \
319+ +/-{WIDE_LAG_MAX} search's own edge",
320+ path.display()
321+ );
322+ if profile == "LC" {
323+ lc_lag = Some(lag);
324+ }
325+ // HE rows: a per-channel free lag search on periodic/tonal
326+ // content is unreliable (coupled_cpe_channel_swap_probe
327+ // proved this file's ref L vs ref R itself mis-searches --
328+ // lag=-24 corr=0.213 vs the fixed lag=0 corr=0.873 -- and
329+ // the same coarse search can land two channels of the SAME
330+ // stream on DIFFERENT, individually-wrong lags, faking a
331+ // channel swap that a fixed-lag check rules out). Derive
332+ // ONE lag per stream from the summed (mono) signal instead,
333+ // and reuse it for both channels -- more robust than
334+ // trusting a single, possibly-periodic channel's own search
335+ // -- via the same top-K/refine-on-first-10s robust method.
336+ if profile == "HE" && ours.len() >= 2 && theirs.len() >= 2 {
337+ let mono_o: Vec<f32> =
338+ ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
339+ let mono_t: Vec<f32> = theirs[0]
340+ .iter()
341+ .zip(&theirs[1])
342+ .map(|(a, b)| a + b)
343+ .collect();
344+ let (mono_lag, _, mono_edge) =
345+ robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK);
346+ assert!(
347+ !mono_edge,
348+ "{}: HE row's mono-derived refined lag {mono_lag} sits at the \
349+ +/-{WIDE_LAG_MAX} search's own edge",
350+ path.display()
351+ );
352+ lag = mono_lag;
353+ full = correlation_at_lag(o, t, lag);
354+ }
355+ // Crossover in Hz from the actual parsed kx (band width
356+ // rate/128, same domain `sbr_chain.rs`'s own doc comment
357+ // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist
358+ // split for the LC controls, which carry no kx at all.
359+ let crossover_hz = if kx > 0 {
360+ f64::from(our_rate) * (kx as f64) / 128.0
361+ } else {
362+ f64::from(our_rate) * 0.25
363+ };
364+ // Same single robust `lag` the full/above bands use, not an
365+ // independent search: a narrowband low-passed signal's
366+ // correlation surface is broad and flat across nearby lags,
367+ // which used to let an independent search here silently
368+ // report a different (and unvalidated) alignment than the
369+ // one everything else in the row is anchored at.
370+ let below = correlation_at_lag(
371+ &lowpass(o, our_rate, crossover_hz),
372+ &lowpass(t, our_rate, crossover_hz),
373+ lag,
374+ );
375+ // `above` re-slices at the FULL-band winning `lag` before
376+ // splitting, same convention `sbr_real_library_matches_reference`
377+ // uses -- round-52's first cut of this row measured `o[..n]`
378+ // against `t[..n]` with no lag offset at all, which is only
379+ // valid by accident at lag 0 and was silently wrong for
380+ // every other winning lag in that table.
381+ let (oa, ob) = if lag >= 0 {
382+ (0usize, lag as usize)
383+ } else {
384+ ((-lag) as usize, 0usize)
385+ };
386+ let n = WINDOW
387+ .min(o.len().saturating_sub(oa))
388+ .min(t.len().saturating_sub(ob));
389+ let above = if n >= 1024 {
390+ correlation(
391+ &highpass(&o[oa..oa + n], our_rate, crossover_hz),
392+ &highpass(&t[ob..ob + n], our_rate, crossover_hz),
393+ )
394+ } else {
395+ 0.0
396+ };
397+ // Round-51's self-consistency probe (our full chain's low
398+ // band vs our own core-only decode), run per-row so a
399+ // rate/kx-specific self-inconsistency shows in the same
400+ // table instead of needing a second pass.
401+ //
402+ // Fixed (this round): the original convention naively
403+ // nearest-neighbor UPSAMPLED the core 2x and compared it
404+ // against the full-rate signal, low-passed at
405+ // `core_rate*0.4` -- that stairstep-and-lowpass round trip
406+ // is lossy enough on its own to sink a genuinely-correct
407+ // pair's correlation (measured flat ~-0.12 here even on
408+ // rows whose `full`/`below` columns read 0.999+ against the
409+ // real reference). `core_only_matches_reference` already
410+ // proved a clean pattern for this exact comparison: stay in
411+ // the CORE's own native rate (DECIMATE the full/reference
412+ // signal down instead of upsampling the core up) and use a
413+ // wide lag search there. `decimate` below is a lowpass
414+ // (well under the core Nyquist) followed by a plain
415+ // every-other-sample drop -- the inverse of the old
416+ // `[s, s]` upsample, at the same information cost but
417+ // without its stairstep artifact.
418+ let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec<f32> {
419+ let cutoff = f64::from(to_rate) * 0.45;
420+ lowpass(s, from_rate, cutoff)
421+ .iter()
422+ .step_by((from_rate / to_rate.max(1)).max(1) as usize)
423+ .copied()
424+ .collect()
425+ };
426+ let core_lag_max = WIDE_LAG_MAX / 2;
427+ let ours_v_core = if kx > 0 {
428+ our_decode_core_only(&path, 0).map(|(core, core_rate)| {
429+ let full_at_core_rate = decimate(o, our_rate, core_rate);
430+ best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max)
431+ })
432+ } else {
433+ None
434+ };
435+ // Coordinator follow-up 2: splits "our core decode of THIS
436+ // fixture is wrong" (core_v_ref ~0) from "the SBR chain
437+ // scrambles a good core" (core_v_ref >= ~0.99 while `below`/
438+ // `above` stays ~0/negative) -- OUR core-only decode, same
439+ // native-core-rate convention `ours_v_core` now uses, against
440+ // the REFERENCE decoder's own decode resampled to that same
441+ // core rate (`ffmpeg_decode_at_rate`, the same helper
442+ // `core_only_matches_reference` already trusts) -- wide lag
443+ // search since this is an independent alignment from
444+ // `full`/`below`'s (core-only carries no SBR delay).
445+ let (core_v_ref, core_rate_str) = if kx > 0 {
446+ match our_decode_core_only(&path, 0) {
447+ Some((core, core_rate)) => {
448+ let ref_at_core_rate =
449+ ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate);
450+ (
451+ Some(best_lag_correlation_wide(
452+ &core[0],
453+ &ref_at_core_rate[0],
454+ core_lag_max,
455+ )),
456+ core_rate.to_string(),
457+ )
458+ }
459+ None => (None, "n/a".into()),
460+ }
461+ } else {
462+ (None, "n/a".into())
463+ };
464+ println!(
465+ "{rate:>5} {br:>6} {profile:>4} {kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
466+ ours_v_core
467+ .map(|(_, c)| format!("{c:.4}"))
468+ .unwrap_or_else(|| "n/a".into()),
469+ ours_v_core
470+ .map(|(l, _)| l.to_string())
471+ .unwrap_or_else(|| "n/a".into()),
472+ core_v_ref
473+ .map(|(_, c)| format!("{c:.4}"))
474+ .unwrap_or_else(|| "n/a".into()),
475+ core_v_ref
476+ .map(|(l, _)| l.to_string())
477+ .unwrap_or_else(|| "n/a".into()),
478+ core_rate_str,
479+ our_rate,
480+ );
481+ // 44.1k-family HE rows: print per-second full-band corr at
482+ // the row's own robust `lag` over 30s, so a content-
483+ // dependent HF-reconstruction dip (real, not an alignment
484+ // artifact -- `sbr441_family_sample_drift_probe` isolated
485+ // one at t=13-27s on heaac_44100_48k.m4a) is visible per
486+ // second instead of averaged away by the single `full`
487+ // column above.
488+ if profile == "HE" && rate == 44_100 {
489+ println!(" per-second full-band corr @ lag {lag} (t, corr):");
490+ let step = our_rate.max(1) as usize;
491+ for sec in 0..30usize {
492+ let oa0 = sec * step;
493+ if oa0 + step > o.len() {
494+ break;
495+ }
496+ let ob0 = oa0 as i64 + lag;
497+ if ob0 < 0 {
498+ continue;
499+ }
500+ let ob0 = ob0 as usize;
501+ if ob0 + step > t.len() {
502+ continue;
503+ }
504+ let c = correlation(&o[oa0..oa0 + step], &t[ob0..ob0 + step]);
505+ println!(" t={sec:>2}s corr={c:.6}");
506+ }
507+ }
508+ // Coordinator follow-up (4): on the two named rows, probe
509+ // candidate total HE-vs-reference delays built from LC's own
510+ // priming lag plus a guessed SBR-chain contribution, to see
511+ // which (if any) actually lands near 1.0 -- and whether that
512+ // offset is constant across the two rows.
513+ if profile == "HE"
514+ && ((rate == 44_100 && br == "48k") || (rate == 48_000 && br == "64k"))
515+ {
516+ let lc = lc_lag.unwrap_or(-2048);
517+ println!(" ch0 delay probe (LC lag {lc}):");
518+ for (label, extra) in [
519+ ("2990", 2990i64),
520+ ("3010", 3010),
521+ ("3020", 3020),
522+ ("1505x2", 1505 * 2),
523+ ("962x2", 962 * 2),
524+ ] {
525+ let candidate = (lc - 2048) + extra;
526+ println!(
527+ " offset={label:>6} -> lag={candidate:>6} corr={:.6}",
528+ correlation_at_lag(o, t, candidate)
529+ );
530+ }
531+ }
532+ if profile == "LC" {
533+ assert!(
534+ full >= 0.999,
535+ "{}: LC control full-band corr {full:.6} < 0.999 -- the \
536+ harness itself (extraction/decode/correlation) is broken, \
537+ not the SBR chain this fixture matrix is meant to isolate",
538+ path.display()
539+ );
540+ }
541+ }
542+ }
543+ }
544+ assert!(
545+ probed >= 16,
546+ "only {probed} of 16 HE-AAC matrix fixtures were present -- rerun \
547+ scripts/aac-tables/make-heaac-fixtures.sh"
548+ );
549+}
550+
551+pub(super) fn candidates() -> Vec<Candidate> {
552+ let home = std::env::var("HOME").unwrap_or_default();
553+ [
554+ (format!("{home}/Music/reeln.mp4"), 0, 0, 5_000.0),
555+ (
556+ format!(
557+ "{home}/Downloads/reelp/reelp.mkv"
558+ ),
559+ 1,
560+ 3,
561+ 5_000.0,
562+ ),
563+ ]
564+ .into_iter()
565+ .map(|(p, aac_stream, ffmpeg_stream, crossover_hz)| Candidate {
566+ path: PathBuf::from(p),
567+ aac_stream,
568+ ffmpeg_stream,
569+ crossover_hz,
570+ })
571+ .filter(|c| c.path.exists())
572+ .collect()
573+}
574+
575+/// The SBR chain against the reference decoder on every real HE-AAC file this
576+/// checkout can find. Skips loudly (never silently) when ffmpeg or the files
577+/// are absent. Per channel: full-band correlation must clear 0.999 and the
578+/// below-crossover (core-decoded) band must clear 0.9999, so a real SBR
579+/// regression cannot hide behind an average across bands the core never
580+/// touches.
581+#[test]
582+pub(super) fn sbr_real_library_matches_reference() {
583+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
584+ if !have_ffmpeg() {
585+ eprintln!("SKIP: ffmpeg not on PATH");
586+ return;
587+ }
588+ let list = candidates();
589+ if list.is_empty() {
590+ eprintln!("SKIP: no HE-AAC files found under ~/Music, ~/Downloads, ~/Videos");
591+ return;
592+ }
593+ let mut checked = 0;
594+ let mut worst_full = 1.0f64;
595+ let mut worst_low = 1.0f64;
596+ let mut any_at_edge: Option<String> = None;
597+ for c in &list {
598+ let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
599+ eprintln!("SKIP {}: could not decode", c.path.display());
600+ continue;
601+ };
602+ if sbr != ec_aac::SbrSupport::V1 {
603+ eprintln!(
604+ "SKIP {}: sbr_support() is {sbr:?}, not a plain-SBR (v1) stream this chain reconstructs",
605+ c.path.display()
606+ );
607+ continue;
608+ }
609+ let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len());
610+ println!("{} ({} ch, {} Hz):", c.path.display(), ours.len(), rate);
611+ // Full cross-channel triangle at one fixed lag/window: both channels
612+ // of one CPE are decoded frame-locked and so share the same
613+ // start-of-stream offset, so ch0's own alignment lag is a valid
614+ // anchor for every pair here, letting all five numbers be compared
615+ // directly instead of each being independently (and, before the
616+ // |corr|-max fix above, unreliably) re-searched.
617+ if ours.len() >= 2 && theirs.len() >= 2 {
618+ let (lag0, _) = best_lag_correlation(&ours[0], &theirs[0]);
619+ println!(
620+ " TRIANGLE @ ch0's lag {lag0}: ours0*ref0={:.6} ours0*ref1={:.6} ours1*ref0={:.6} ours1*ref1={:.6} ours0*ours1={:.6}",
621+ correlation_at_lag(&ours[0], &theirs[0], lag0),
622+ correlation_at_lag(&ours[0], &theirs[1], lag0),
623+ correlation_at_lag(&ours[1], &theirs[0], lag0),
624+ correlation_at_lag(&ours[1], &theirs[1], lag0),
625+ correlation_at_lag(&ours[0], &ours[1], 0),
626+ );
627+ }
628+ for (ch, (o_full, t_full)) in ours.iter().zip(&theirs).enumerate() {
629+ // (Round-22 stability check) EC_AAC_SBR_SWEEP_SEGMENT=1 measures
630+ // the second half of the file instead of the first, so a
631+ // calibration candidate can be checked on two disjoint segments
632+ // rather than just the file's start.
633+ //
634+ // (Round-23) The split point MUST be the same absolute sample
635+ // index on both sides, not each side's own `len() / 2`: `ours`
636+ // is capped at MAX_SAMPLES while `theirs` (the reference) is
637+ // decoded in full, so on a file longer than the cap `o_full` and
638+ // `t_full` have different total lengths and an independent
639+ // `len() / 2` on each picks DIFFERENT seconds of the file --
640+ // reeln is a 30s file capped to ours=22.7s, so the old code
641+ // compared ours' 11.35s-22.7s against theirs' 15.0s-30.0s, a
642+ // 3.6s-misaligned pair of unrelated passages that reads as a
643+ // catastrophic collapse (~-0.01 corr) with no decode defect
644+ // behind it. Splitting both sides at the shorter side's midpoint
645+ // keeps the two halves pointed at the same audio.
646+ let (o, t): (&[f32], &[f32]) =
647+ if std::env::var("EC_AAC_SBR_SWEEP_SEGMENT").as_deref() == Ok("1") {
648+ let half = o_full.len().min(t_full.len()) / 2;
649+ (&o_full[half..], &t_full[half..])
650+ } else {
651+ (&o_full[..], &t_full[..])
652+ };
653+ let rms = |s: &[f32]| {
654+ (s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
655+ / s.len().max(1) as f64)
656+ .sqrt()
657+ };
658+ eprintln!(
659+ " ch{ch} debug: ours len={} rms={:.4} first10={:?}; theirs len={} rms={:.4} first10={:?}",
660+ o.len(),
661+ rms(o),
662+ &o[..10.min(o.len())],
663+ t.len(),
664+ rms(t),
665+ &t[..10.min(t.len())],
666+ );
667+ let (lag, full, full_at_edge) = best_lag_correlation_ex(o, t, SEARCH_LAG_MAX);
668+ if full_at_edge {
669+ any_at_edge.get_or_insert_with(|| {
670+ format!(
671+ "{} ch{ch} full-band: winning lag {lag} at +/-{SEARCH_LAG_MAX} search edge",
672+ c.path.display()
673+ )
674+ });
675+ }
676+ // Re-slice both signals at the winning lag before splitting into
677+ // bands, so the band correlations are aligned too.
678+ let (oa, ob) = if lag >= 0 {
679+ (0usize, lag as usize)
680+ } else {
681+ ((-lag) as usize, 0usize)
682+ };
683+ let n = WINDOW
684+ .min(o.len().saturating_sub(oa))
685+ .min(t.len().saturating_sub(ob));
686+ // The below-crossover band gets its OWN lag search rather than
687+ // reusing the full-band winning lag: a narrowband, slowly-varying
688+ // low-passed signal has a correlation surface that stays broad
689+ // and flat across many nearby lags, so a full-band search (whose
690+ // winner is decided mostly by the higher-energy/higher-bandwidth
691+ // content) can land on a lag that is a genuine local optimum for
692+ // the whole signal yet a bad one for the low band alone -- on
693+ // reeln ch1, full-band lag 65 vs 64 differ by only 0.0015 in
694+ // full-band correlation but by 0.88 in below-crossover
695+ // correlation once the low band is measured at its own winning
696+ // lag instead. Both bands are still re-anchored at the SAME
697+ // `start` offset internally (see `best_lag_correlation`), so
698+ // this is genuinely comparing the low band against itself, not
699+ // drifting to an unrelated part of the file.
700+ let low = {
701+ let ol_full = lowpass(o, rate, c.crossover_hz);
702+ let tl_full = lowpass(t, rate, c.crossover_hz);
703+ let (low_lag, low_corr, low_at_edge) =
704+ best_lag_correlation_ex(&ol_full, &tl_full, SEARCH_LAG_MAX);
705+ if low_at_edge {
706+ any_at_edge.get_or_insert_with(|| {
707+ format!(
708+ "{} ch{ch} below-crossover: winning lag {low_lag} at +/-{SEARCH_LAG_MAX} search edge",
709+ c.path.display()
710+ )
711+ });
712+ }
713+ if low_lag != lag {
714+ eprintln!(
715+ " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}"
716+ );
717+ }
718+ if std::env::var("EC_AAC_SBR_DRIFT").is_ok() {
719+ let ol_sharp = sharp_lowpass(o, rate, c.crossover_hz);
720+ let tl_sharp = sharp_lowpass(t, rate, c.crossover_hz);
721+ let (_, sharp_corr) = best_lag_correlation(&ol_sharp, &tl_sharp);
722+ println!(
723+ " ch{ch} below-crossover SHARP (3x cascaded) filter: {sharp_corr:.6}"
724+ );
725+ }
726+ low_corr
727+ };
728+ let high = if n >= 1024 {
729+ let oh = highpass(&o[oa..oa + n], rate, c.crossover_hz);
730+ let th = highpass(&t[ob..ob + n], rate, c.crossover_hz);
731+ let rms = |v: &[f32]| {
732+ (v.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / v.len().max(1) as f64)
733+ .sqrt()
734+ };
735+ println!(
736+ " ch{ch} above-crossover RMS ours/ref = {:.4}",
737+ rms(&oh) / rms(&th).max(1e-12)
738+ );
739+ correlation(&oh, &th)
740+ } else {
741+ 0.0
742+ };
743+ if ch == 0 && std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok() {
744+ // (Round-17, Task 1) the noise-energy-fraction ceiling
745+ // hypothesis: predicted per-band correlation ceiling
746+ // sqrt(1 - noise_energy/(signal_energy+noise_energy)),
747+ // from OUR OWN transmitted (dequantized) envelope/noise
748+ // split -- printed once per file so it can be eyeballed
749+ // against per_band_lag_search's measured |corr| curve
750+ // below. Real QMF band width in output Hz is
751+ // `rate/128` (64-band synthesis over the output Nyquist).
752+ let band_hz = f64::from(rate) / 128.0;
753+ println!(
754+ " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):"
755+ );
756+ for (band, signal, noise, out) in ec_aac::noise_fraction_table() {
757+ if signal + noise <= 0.0 {
758+ continue;
759+ }
760+ let f = noise / (signal + noise);
761+ println!(
762+ " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4} realised/target {:.4}",
763+ band as f64 * band_hz,
764+ (1.0 - f).max(0.0).sqrt(),
765+ out / (signal + noise)
766+ );
767+ }
768+ }
769+ if std::env::var("EC_AAC_SBR_BANDS").is_ok() && n >= 4_096 {
770+ let spectrum = per_band_correlation(&o[oa..oa + n], &t[ob..ob + n], rate);
771+ println!(" ch{ch} per-QMF-band |corr| (band_hz, |corr|, band_index):");
772+ for (hz, corr, band) in &spectrum {
773+ println!(" {hz:>6.0}Hz band{band:>3.0}: {corr:.4}");
774+ }
775+ let lags = per_band_lag_search(&o[oa..oa + n], &t[ob..ob + n], rate);
776+ println!(" ch{ch} per-HF-band PCM lag search (band_hz, best_lag, |corr|):");
777+ for (hz, lag, corr) in &lags {
778+ println!(" {hz:>6.0}Hz: lag {lag:>5} corr {corr:.4}");
779+ }
780+ let phases = per_band_phase(&o[oa..oa + n], &t[ob..ob + n], rate);
781+ println!(
782+ " ch{ch} per-band cross-spectrum (band_hz, phase_deg, mag_ratio ours/theirs):"
783+ );
784+ for (hz, phase, ratio) in &phases {
785+ println!(
786+ " {hz:>6.0}Hz: phase {:>7.2}deg ratio {ratio:.4}",
787+ phase.to_degrees()
788+ );
789+ }
790+ }
791+ if std::env::var("EC_AAC_SBR_HF_CONVICTION").is_ok() && n >= 4_096 {
792+ let band_hz = f64::from(rate) / 256.0;
793+ let kx = (c.crossover_hz / band_hz).round() as usize;
794+ let win = &o[oa..oa + n];
795+ let twin = &t[ob..ob + n];
796+ println!(
797+ " ch{ch} TASK1 bandpass-selectivity probe (band_hz, same-band corr, +offset corr, -offset corr):"
798+ );
799+ for hf_band in [kx + 5, kx + 15, kx + 25] {
800+ let (same, hi_c, lo_c) = bandpass_offset_probe(win, twin, rate, hf_band, 10);
801+ println!(
802+ " HF band{hf_band:>3} ({:.0}Hz) offset=10: same {same:.4} +10band {hi_c:.4} -10band {lo_c:.4}",
803+ hf_band as f64 * band_hz
804+ );
805+ }
806+ if kx > 6 {
807+ let lf_band = kx.saturating_sub(6);
808+ let (same, hi_c, lo_c) = bandpass_offset_probe(win, twin, rate, lf_band, 3);
809+ println!(
810+ " LF CONTROL band{lf_band:>3} ({:.0}Hz) offset=3: same {same:.4} +3band {hi_c:.4} -3band {lo_c:.4}",
811+ lf_band as f64 * band_hz
812+ );
813+ }
814+ println!(
815+ " ch{ch} TASK2 bin-level conviction (band_hz, ours-energy, direct, mirror, shift+1band, shift-1band):"
816+ );
817+ let min_band = (2_500.0 / band_hz).ceil() as usize;
818+ for (hz, energy, direct, mirror, shift_up, shift_down) in
819+ bin_level_conviction(win, twin, rate, min_band, 6)
820+ {
821+ println!(
822+ " {hz:>6.0}Hz: energy {energy:.3e} direct {direct:.4} mirror {mirror:.4} shift+1 {shift_up:.4} shift-1 {shift_down:.4}"
823+ );
824+ }
825+ }
826+ // (Round-36, Task 2) parity-split coherence: round-35 fixed the
827+ // Synthesis phase-intercept bug only for ODD (target-source)
828+ // patch gaps, at the patch-copy site. On header A (the real
829+ // file's own header) that fix can only be SEEN in the odd-gap
830+ // territory those patches cover (bands 28..42, from patches
831+ // (3,28,11)/(0,39,3)/(13,42,1)); the even-gap patch (0,14,14)
832+ // covers bands 14..27 and was already exact before round-35, so
833+ // it is the control range the fix must NOT move. Reuses
834+ // `bin_level_conviction`'s per-bin direct-coherence measurement
835+ // over every HF band in [14, 43) (min_band=14, top_n wide enough
836+ // to keep every band, not just the top-energy handful), then
837+ // averages `direct` within each region separately.
838+ if std::env::var("EC_AAC_SBR_PARITY_SPLIT").is_ok() && n >= 4_096 {
839+ let band_hz = f64::from(rate) / 256.0;
840+ let win = &o[oa..oa + n];
841+ let twin = &t[ob..ob + n];
842+ let rows = bin_level_conviction(win, twin, rate, 14, 29);
843+ let mean_in = |lo: usize, hi: usize| {
844+ let vals: Vec<f64> = rows
845+ .iter()
846+ .filter(|(hz, ..)| {
847+ let band = (hz / band_hz).round() as usize;
848+ band >= lo && band < hi
849+ })
850+ .map(|(_, _, direct, ..)| *direct)
851+ .collect();
852+ if vals.is_empty() {
853+ (0.0, 0)
854+ } else {
855+ (vals.iter().sum::<f64>() / vals.len() as f64, vals.len())
856+ }
857+ };
858+ let (even_mean, even_n) = mean_in(14, 28);
859+ let (odd_mean, odd_n) = mean_in(28, 43);
860+ println!(
861+ " ch{ch} PARITY-SPLIT direct-coherence mean: even-gap[14,28)={even_mean:.4} (n={even_n}) odd-gap[28,43)={odd_mean:.4} (n={odd_n})"
862+ );
863+ }
864+ // (Round-38, Task 1) HF-only constant-lag sweep: see
865+ // `hf_lag_sweep`'s doc comment. Reuses this window's already
866+ // globally-aligned `oa`/`ob`/`n`; only `o`'s STFT read position is
867+ // shifted, `n_slot`*64 samples at a time.
868+ if std::env::var("EC_AAC_SBR_HF_LAG_SWEEP").is_ok() && n >= 4_096 {
869+ let band_hz = f64::from(rate) / 256.0;
870+ let min_band = (2_500.0 / band_hz).ceil() as usize;
871+ let sweep = hf_lag_sweep(o, t, oa, ob, n, min_band);
872+ println!(
873+ " ch{ch} TASK1 HF-only lag sweep (k = QMF slots of 64 samples, mean direct HF-bin coherence):"
874+ );
875+ for (k, coh) in &sweep {
876+ println!(" k={k:>3}: coherence {coh:.4}");
877+ }
878+ if let Some((peak_k, peak_c)) =
879+ sweep.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
880+ {
881+ println!(" ch{ch} HF lag sweep peak: k={peak_k} coherence {peak_c:.4}");
882+ }
883+ }
884+ // (Round-40, Task 1) fine spectral-bin shift scan -- see
885+ // `hf_bin_shift_sweep`'s doc comment.
886+ if std::env::var("EC_AAC_SBR_BIN_SHIFT").is_ok() && n >= 4_096 {
887+ let win = &o[oa..oa + n];
888+ let twin = &t[ob..ob + n];
889+ for (region_name, lo, hi) in
890+ [("even-gap[14,28)", 14, 28), ("odd-gap[28,43)", 28, 43)]
891+ {
892+ let sweep = hf_bin_shift_sweep(win, twin, rate, lo, hi);
893+ println!(
894+ " ch{ch} TASK1 BIN-SHIFT {region_name} (b = FFT bins, mean direct HF-bin coherence):"
895+ );
896+ for (b, coh) in &sweep {
897+ println!(" b={b:>3}: coherence {coh:.4}");
898+ }
899+ if let Some((peak_b, peak_c)) =
900+ sweep.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
901+ {
902+ println!(
903+ " ch{ch} {region_name} bin-shift peak: b={peak_b} coherence {peak_c:.4}"
904+ );
905+ }
906+ }
907+ }
908+ // (Round-40, Task 2) complex-gain fingerprint -- see
909+ // `hf_complex_ratio_trajectory`'s doc comment.
910+ if std::env::var("EC_AAC_SBR_COMPLEX_GAIN").is_ok() && n >= 4_096 {
911+ let band_hz = f64::from(rate) / 256.0;
912+ let min_band = (2_500.0 / band_hz).ceil() as usize;
913+ let win = &o[oa..oa + n];
914+ let twin = &t[ob..ob + n];
915+ for (hz, traj) in hf_complex_ratio_trajectory(win, twin, rate, min_band, 4) {
916+ println!(
917+ " ch{ch} TASK2 COMPLEX-GAIN {hz:.0}Hz dominant-bin O/T trajectory (frame: mag, phase_deg, dphase_deg):"
918+ );
919+ let mut prev_phase: Option<f64> = None;
920+ for (h, (mag, phase)) in traj.iter().enumerate() {
921+ let dphase = prev_phase.map(|p| {
922+ let mut d = phase.to_degrees() - p;
923+ while d > 180.0 {
924+ d -= 360.0;
925+ }
926+ while d < -180.0 {
927+ d += 360.0;
928+ }
929+ d
930+ });
931+ prev_phase = Some(phase.to_degrees());
932+ match dphase {
933+ Some(d) => println!(
934+ " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase {d:>7.2}deg",
935+ phase.to_degrees()
936+ ),
937+ None => println!(
938+ " frame{h:>3}: mag {mag:.4} phase {:>7.2}deg dphase n/a",
939+ phase.to_degrees()
940+ ),
941+ }
942+ }
943+ }
944+ }
945+ // (Round-45, Task 3) THIRD WITNESS: a reference-free plain
946+ // patch+gain simulator built from the reference's own low band --
947+ // see `hf_patch_simulator`'s doc comment.
948+ if std::env::var("EC_AAC_SBR_SIMULATOR").is_ok() && n >= 4_096 {
949+ let win = &o[oa..oa + n];
950+ let twin = &t[ob..ob + n];
951+ let (vs_ref, vs_ours) = hf_patch_simulator(win, twin, rate);
952+ let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
953+ let vals: Vec<f64> = rows
954+ .iter()
955+ .filter(|(b, _)| *b >= lo && *b < hi)
956+ .map(|(_, c)| *c)
957+ .collect();
958+ if vals.is_empty() {
959+ 0.0
960+ } else {
961+ vals.iter().sum::<f64>() / vals.len() as f64
962+ }
963+ };
964+ println!(" ch{ch} SIMULATOR sim-vs-REFERENCE per-band coherence (band, coh):");
965+ for (b, coh) in &vs_ref {
966+ println!(" band{b:>3}: {coh:.4}");
967+ }
968+ println!(
969+ " ch{ch} SIMULATOR sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
970+ mean_in(&vs_ref, 14, 28),
971+ mean_in(&vs_ref, 28, 43)
972+ );
973+ println!(" ch{ch} SIMULATOR sim-vs-OURS per-band coherence (band, coh):");
974+ for (b, coh) in &vs_ours {
975+ println!(" band{b:>3}: {coh:.4}");
976+ }
977+ println!(
978+ " ch{ch} SIMULATOR sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
979+ mean_in(&vs_ours, 14, 28),
980+ mean_in(&vs_ours, 28, 43)
981+ );
982+ }
983+ // (Round-46, Task 1) QMF-domain exact third witness -- see
984+ // `hf_patch_simulator_qmf`'s doc comment.
985+ if std::env::var("EC_AAC_SBR_QMF_WITNESS").is_ok() && n >= 4_096 {
986+ let win = &o[oa..oa + n];
987+ let twin = &t[ob..ob + n];
988+ let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin);
989+ // Per-QMF-band energy ratio and coherence, ours vs reference
990+ // (the envelope-adjuster instrument: a level offset shows as
991+ // a constant dB ratio, a gain-shape defect as per-band dB).
992+ {
993+ let (o_spec, t_spec, _) = qmf_domain_spec(win, twin);
994+ println!(" ch{ch} QMF-BAND ours-vs-REFERENCE (band, ratio_dB, coherence):");
995+ for band in 0..o_spec.len().min(t_spec.len()).min(48) {
996+ let (mut eo, mut et, mut cr, mut ci) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
997+ for (a, b) in o_spec[band].iter().zip(&t_spec[band]) {
998+ eo += a.norm_sqr();
999+ et += b.norm_sqr();
1000+ let c = *a * b.conj();
1001+ cr += c.re;
1002+ ci += c.im;
1003+ }
1004+ let coh = (cr * cr + ci * ci).sqrt() / (eo * et).sqrt().max(1e-30);
1005+ println!(
1006+ " band{band:>3}: {:>7.2} dB coh {coh:.4}",
1007+ 10.0 * (eo / et.max(1e-30)).log10()
1008+ );
1009+ }
1010+ }
1011+ let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
1012+ let vals: Vec<f64> = rows
1013+ .iter()
1014+ .filter(|(b, _)| *b >= lo && *b < hi)
1015+ .map(|(_, c)| *c)
1016+ .collect();
1017+ if vals.is_empty() {
1018+ 0.0
1019+ } else {
1020+ vals.iter().sum::<f64>() / vals.len() as f64
1021+ }
1022+ };
1023+ println!(" ch{ch} QMF-WITNESS sim-vs-REFERENCE per-band coherence (band, coh):");
1024+ for (b, coh) in &vs_ref {
1025+ println!(" band{b:>3}: {coh:.4}");
1026+ }
1027+ println!(
1028+ " ch{ch} QMF-WITNESS sim-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
1029+ mean_in(&vs_ref, 14, 28),
1030+ mean_in(&vs_ref, 28, 43)
1031+ );
1032+ println!(" ch{ch} QMF-WITNESS sim-vs-OURS per-band coherence (band, coh):");
1033+ for (b, coh) in &vs_ours {
1034+ println!(" band{b:>3}: {coh:.4}");
1035+ }
1036+ println!(
1037+ " ch{ch} QMF-WITNESS sim-vs-OURS mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
1038+ mean_in(&vs_ours, 14, 28),
1039+ mean_in(&vs_ours, 28, 43)
1040+ );
1041+ // (Round-48, Task 4a) the ultimate content-match witness:
1042+ // our HF QMF content directly against the reference's, no
1043+ // simulator step in between.
1044+ println!(" ch{ch} QMF-WITNESS ours-vs-REFERENCE per-band coherence (band, coh):");
1045+ for (b, coh) in &ours_vs_ref {
1046+ println!(" band{b:>3}: {coh:.4}");
1047+ }
1048+ println!(
1049+ " ch{ch} QMF-WITNESS ours-vs-REFERENCE mean: even-gap[14,28)={:.4} odd-gap[28,43)={:.4}",
1050+ mean_in(&ours_vs_ref, 14, 28),
1051+ mean_in(&ours_vs_ref, 28, 43)
1052+ );
1053+ // (Round-46, Task 2) fitted sim-to-reference transfer, one
1054+ // representative band per patch plus a spread across the
1055+ // strong odd-gap patch (3,28,11) where the QMF witness shows
1056+ // sim-vs-reference clearing 0.5.
1057+ let fit_bands = [14, 18, 22, 26, 28, 30, 32, 34, 36, 38, 39, 42];
1058+ let fits_ref = hf_patch_transfer_fit(win, twin, &fit_bands, false);
1059+ println!(" ch{ch} TASK2 FIT ref[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:");
1060+ for (b, a) in &fits_ref {
1061+ println!(
1062+ " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})",
1063+ a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im
1064+ );
1065+ }
1066+ // (Round-48, Task 2) same fit, target = ours: side by side
1067+ // with the above shows exactly what our transform does to
1068+ // the plain copy vs what the reference's does.
1069+ let fits_ours = hf_patch_transfer_fit(win, twin, &fit_bands, true);
1070+ println!(" ch{ch} TASK2 FIT ours[l]~=a0*sim[l]+a1*sim[l-1]+a2*sim[l-2]:");
1071+ for (b, a) in &fits_ours {
1072+ println!(
1073+ " band{b:>3}: a0=({:>7.3},{:>7.3}) a1=({:>7.3},{:>7.3}) a2=({:>7.3},{:>7.3})",
1074+ a[0].re, a[0].im, a[1].re, a[1].im, a[2].re, a[2].im
1075+ );
1076+ }
1077+ }
1078+ println!(
1079+ " ch{ch}: lag {lag}, full {full:.6}, below {:.0}Hz {low:.6}, above {:.0}Hz {high:.6}",
1080+ c.crossover_hz, c.crossover_hz
1081+ );
1082+ if std::env::var("EC_AAC_SBR_DRIFT").is_ok() && n >= 4_096 {
1083+ let windows = (n / 4_096).min(20);
1084+ let drift = windowed_lag_drift(o, t, oa, ob, windows);
1085+ println!(" ch{ch} DRIFT (window_idx, local_lag, |corr|):");
1086+ for (w, (l, cr)) in drift.iter().enumerate() {
1087+ println!(" w{w}: lag {l} corr {cr:.4}");
1088+ }
1089+ }
1090+ // (Round-23, Task 1/3) whole-file corr-vs-time timeline: the
1091+ // DRIFT diagnostic above caps at 20 windows (~1.85s) starting at
1092+ // the full-band lag offset near sample 0, so it never sees a
1093+ // collapse that only appears later in the file. This walks
1094+ // every 4096-sample window from that same start to EOF on BOTH
1095+ // sides, with its own local lag search per window, so a
1096+ // mid-file onset shows up as a specific window index/timestamp
1097+ // instead of being averaged away inside one giant WINDOW-sized
1098+ // correlation. The mean/min across every window is also the
1099+ // TRUE whole-file correlation number (`best_lag_correlation`
1100+ // above only ever measures one WINDOW=200_000-sample slice
1101+ // starting near the file's first quarter): unlike that one
1102+ // fixed-lag figure, this one is immune to a single global lag
1103+ // being slightly wrong for a later part of the file.
1104+ {
1105+ let avail = o.len().saturating_sub(oa).min(t.len().saturating_sub(ob));
1106+ let windows = avail / 4_096;
1107+ // The full per-window LOCAL_LAG=+-2000 search inside
1108+ // `windowed_lag_drift` costs O(windows * 4001 * 4096) and runs
1109+ // ~4min/channel over a whole real-library file -- that walk
1110+ // is only needed when actually hunting for a drifting lag
1111+ // (EC_AAC_SBR_TIMELINE). By default this block instead reuses
1112+ // the already-established global `lag` with NO per-window
1113+ // search (O(windows * 4096)), which is cheap and still gives
1114+ // an honest whole-file windowed mean/min at that fixed lag.
1115+ let timeline: Vec<(i64, f64)> = if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() {
1116+ windowed_lag_drift(o, t, oa, ob, windows)
1117+ } else {
1118+ (0..windows)
1119+ .filter_map(|w| {
1120+ // `oa`/`ob` (computed above from `lag`) already encode the
1121+ // alignment shift via their differing base offsets -- do NOT
1122+ // add `lag` again here, that double-applies it and shifts
1123+ // every window an extra `lag` samples out of alignment
1124+ // (this collapsed the whole-file mean from ~0.96 to ~0.14
1125+ // while leaving the single-WINDOW `full`/`low` numbers,
1126+ // which don't go through this path, unaffected).
1127+ let base_o = oa + w * 4_096;
1128+ let base_t = ob + w * 4_096;
1129+ if base_o + 4_096 > o.len() || base_t + 4_096 > t.len() {
1130+ return None;
1131+ }
1132+ Some((
1133+ lag,
1134+ correlation(&o[base_o..base_o + 4_096], &t[base_t..base_t + 4_096]),
1135+ ))
1136+ })
1137+ .collect()
1138+ };
1139+ if std::env::var("EC_AAC_SBR_TIMELINE").is_ok() {
1140+ println!(
1141+ " ch{ch} TIMELINE ({windows} windows, {rate} Hz, window_idx@sec, local_lag, corr):"
1142+ );
1143+ for (w, (l, cr)) in timeline.iter().enumerate() {
1144+ let t_sec = (oa + w * 4_096) as f64 / f64::from(rate);
1145+ println!(" w{w}@{t_sec:.2}s: lag {l} corr {cr:.4}");
1146+ }
1147+ }
1148+ if !timeline.is_empty() {
1149+ let mean = timeline.iter().map(|(_, c)| c).sum::<f64>() / timeline.len() as f64;
1150+ let min = timeline.iter().map(|(_, c)| *c).fold(f64::MAX, f64::min);
1151+ println!(
1152+ " ch{ch} WHOLE-FILE windowed corr: mean {mean:.6} min {min:.6} over {} windows ({:.2}s)",
1153+ timeline.len(),
1154+ windows as f64 * 4_096.0 / f64::from(rate)
1155+ );
1156+ }
1157+ }
1158+ if std::env::var("EC_AAC_SBR_RESIDUAL_DEBUG").is_ok() {
1159+ residual_sideinfo_analysis(o, t, oa, ob, rate, ch);
1160+ }
1161+ worst_full = worst_full.min(full);
1162+ worst_low = worst_low.min(low);
1163+ }
1164+ checked += 1;
1165+ }
1166+ if checked == 0 {
1167+ eprintln!("SKIP: no plain-SBR real files decoded");
1168+ return;
1169+ }
1170+ assert!(
1171+ any_at_edge.is_none(),
1172+ "lag search hit its bound: {} -- the reported correlations are noise \
1173+ at the search edge, not a measurement",
1174+ any_at_edge.unwrap_or_default()
1175+ );
1176+ assert!(
1177+ worst_full >= 0.999,
1178+ "worst full-band correlation {worst_full:.6} < 0.999 bar"
1179+ );
1180+ assert!(
1181+ worst_low >= 0.9999,
1182+ "worst below-crossover correlation {worst_low:.6} < 0.9999 -- the core decode itself regressed"
1183+ );
1184+}
1185+
1186+/// Writes `aus` (raw access units, no ADTS framing) plus `asc` (their own
1187+/// AudioSpecificConfig bytes, unmodified) into a fresh mp4 at `out_path`, so
1188+/// the reference decoder can be pointed at container-native SBR content that
1189+/// is byte-identical to the original stream's access units -- the same
1190+/// `esds`-carries-an-explicit-SBR-config shape `examples/wrap_sbr.rs` proved
1191+/// on synthetic content in round-31, reused here on a REAL file's own AUs as
1192+/// the round-41 Task 1 remux control.
1193+pub(super) fn write_remux(out_path: &Path, asc: &[u8], aus: &[Vec<u8>]) {
1194+ let cfg = ec_aac::parse_audio_specific_config(asc).expect("real file's own ASC parses");
1195+ let core_rate = cfg.sample_rate;
1196+ let time_base = ec_core::TimeBase::from_rate(core_rate);
1197+ let layout = if cfg.channels == 1 {
1198+ ec_core::ChannelLayout::Mono
1199+ } else {
1200+ ec_core::ChannelLayout::Stereo
1201+ };
1202+ let mut params = ec_core::CodecParameters::new(CodecId::Aac);
1203+ params.extradata = Some(asc.to_vec().into());
1204+ params.media = ec_core::MediaParameters::Audio(ec_core::AudioParameters {
1205+ sample_rate: core_rate,
1206+ layout,
1207+ format: None,
1208+ bits_per_sample: None,
1209+ });
1210+ let mut info = ec_core::StreamInfo::new(0, time_base, params);
1211+ info.default = true;
1212+ let out = File::create(out_path).expect("remux output creatable");
1213+ let mut muxer = ec_mp4::Mp4Muxer::new(out).expect("mp4 muxer opens");
1214+ use ec_core::Muxer as _;
1215+ muxer.add_stream(info).expect("stream declared");
1216+ for (i, au) in aus.iter().enumerate() {
1217+ let pts = i as i64 * 1024;
1218+ let packet = Packet::new(0, time_base, au.as_slice())
1219+ .with_pts(pts)
1220+ .with_duration(1024);
1221+ muxer.write_packet(&packet).expect("packet written");
1222+ }
1223+ muxer.finish().expect("finished");
1224+}
1225+
1226+/// Mean/min of `bin_level_conviction`'s `direct` column, printed as one
1227+/// summary line per control pair.
1228+pub(super) fn report_conviction(label: &str, rows: &[(f64, f64, f64, f64, f64, f64)]) {
1229+ if rows.is_empty() {
1230+ println!(" {label}: no HF bands measured (window too short)");
1231+ return;
1232+ }
1233+ let vals: Vec<f64> = rows.iter().map(|(_, _, direct, ..)| *direct).collect();
1234+ let mean = vals.iter().sum::<f64>() / vals.len() as f64;
1235+ let min = vals.iter().cloned().fold(f64::MAX, f64::min);
1236+ println!(
1237+ " {label}: direct-coherence mean {mean:.4} min {min:.4} over {} HF bands",
1238+ vals.len()
1239+ );
1240+ for (hz, _, direct, ..) in rows {
1241+ println!(" {hz:>6.0}Hz: direct {direct:.4}");
1242+ }
1243+}
crates/ec-aac/tests/sbr_real_library/chunk_b.rsadded+830 -0
@@ -0,0 +1,830 @@
1+//! SBR real-library checks and probes, part B.
2+
3+use super::*;
4+
5+/// (Round-41, Task 1) Instrument anchor: before trusting `bin_level_conviction`'s
6+/// low (~0.15-0.25) HF direct-coherence numbers on reeln as evidence the
7+/// HF content is genuinely different, confirm the measurement itself reads
8+/// near 1.0 on pairs that are KNOWN to carry the same content. Three
9+/// controls:
10+/// A. ours vs ours, decoded independently twice -- a determinism check on
11+/// our own decode AND the coherence arithmetic's floor.
12+/// B. the reference's own PCM from the original file vs from a remux of
13+/// the SAME access units/ASC through a fresh container -- near-1.0
14+/// expected; anything else would implicate the remux path, not SBR.
15+/// C. the reference's own PCM vs itself read 64 samples later (one QMF
16+/// slot) -- sanity that `bin_level_conviction`'s STFT hop/window does
17+/// not itself destroy coherence for equivalent content at a fixed
18+/// sample offset, the same shape of offset the real `oa`/`ob` alignment
19+/// applies above.
20+/// If any control reads below ~0.9 on the HF bands, the instrument -- not
21+/// the SBR chain -- is the story; every prior round's coherence number would
22+/// need to be recalibrated against whatever this control actually measures.
23+#[test]
24+pub(super) fn sbr_instrument_anchor_controls() {
25+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
26+ if std::env::var("EC_AAC_SBR_INSTRUMENT_ANCHOR").is_err() {
27+ eprintln!(
28+ "SKIP (round-41 Task 1): EC_AAC_SBR_INSTRUMENT_ANCHOR=1 cargo test -p ec-aac \
29+ --release --test sbr_real_library sbr_instrument_anchor_controls -- --nocapture"
30+ );
31+ return;
32+ }
33+ if !have_ffmpeg() {
34+ eprintln!("SKIP: ffmpeg not on PATH");
35+ return;
36+ }
37+ let home = std::env::var("HOME").unwrap_or_default();
38+ let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
39+ if !path.exists() {
40+ eprintln!("SKIP: {} not found", path.display());
41+ return;
42+ }
43+ const MIN_BAND: usize = 14;
44+ const TOP_N: usize = 128; // larger than any real band count -- keeps every HF band
45+
46+ // Control A: ours vs ours, decoded independently twice.
47+ let (ours_a, _, rate) = our_decode(&path, 0).expect("our_decode works");
48+ let (ours_b, _, _) = our_decode(&path, 0).expect("our_decode works (2nd pass)");
49+ let n = ours_a[0].len().min(ours_b[0].len()).min(MAX_SAMPLES);
50+ let rows = bin_level_conviction(&ours_a[0][..n], &ours_b[0][..n], rate, MIN_BAND, TOP_N);
51+ report_conviction("A: ours-vs-ours (determinism)", &rows);
52+
53+ // Control B: reference PCM from the original file vs from a remux of the
54+ // SAME access units/ASC.
55+ let (asc, aus) = extract_aac_track(&path, 0).expect("track extracts");
56+ let remux_path = std::env::temp_dir().join("ec_aac_sbr_instrument_anchor_remux.mp4");
57+ write_remux(&remux_path, &asc, &aus);
58+ let theirs_orig = ffmpeg_decode(&path, 0, 2);
59+ let theirs_remux = ffmpeg_decode(&remux_path, 0, 2);
60+ let _ = std::fs::remove_file(&remux_path);
61+ let n = theirs_orig[0]
62+ .len()
63+ .min(theirs_remux[0].len())
64+ .min(MAX_SAMPLES);
65+ let (lag_b, _) = best_lag_correlation(&theirs_orig[0][..n], &theirs_remux[0][..n]);
66+ let (oa, ob) = if lag_b >= 0 {
67+ (0usize, lag_b as usize)
68+ } else {
69+ ((-lag_b) as usize, 0usize)
70+ };
71+ let win = n.saturating_sub(oa.max(ob));
72+ let rows = bin_level_conviction(
73+ &theirs_orig[0][oa..oa + win],
74+ &theirs_remux[0][ob..ob + win],
75+ rate,
76+ MIN_BAND,
77+ TOP_N,
78+ );
79+ report_conviction(
80+ &format!("B: reference-vs-reference-through-remux (lag {lag_b})"),
81+ &rows,
82+ );
83+
84+ // Control C: reference PCM vs itself read 64 samples later (one QMF
85+ // slot) -- both slices are the SAME underlying samples, just offset.
86+ let t = &theirs_orig[0][..MAX_SAMPLES.min(theirs_orig[0].len())];
87+ if t.len() > 64 {
88+ let rows = bin_level_conviction(&t[64..], &t[..t.len() - 64], rate, MIN_BAND, TOP_N);
89+ report_conviction("C: reference vs reference, 64-sample offset", &rows);
90+ }
91+}
92+
93+/// (Round-41, Task 2) Actual injected HF noise energy, measured as OUTPUT
94+/// energy rather than trusted from either side of round-24's contradiction:
95+/// `noise_fraction_table` bookkept a 0.37-0.39 noise share from the
96+/// transmitted envelope/noise split, while separately zeroing the injected
97+/// noise (`EC_AAC_SBR_NOISE_ZERO`, which only skips the PCM addition in
98+/// `sbr_env::adjust`, not the bookkeeping) was found to change full-band
99+/// correlation by <0.001 -- both cannot be true of the same signal. This
100+/// decodes reeln twice (noise on, then off) and reads the per-HF-band
101+/// `bin_level_conviction` energy delta between them as the fraction noise
102+/// ACTUALLY realizes in the output, independent of either prior claim.
103+#[test]
104+pub(super) fn sbr_actual_noise_fraction() {
105+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
106+ if std::env::var("EC_AAC_SBR_NOISE_ANCHOR").is_err() {
107+ eprintln!(
108+ "SKIP (round-41 Task 2): EC_AAC_SBR_NOISE_ANCHOR=1 cargo test -p ec-aac \
109+ --release --test sbr_real_library sbr_actual_noise_fraction -- \
110+ --nocapture --test-threads=1 (env-gated because it sets process \
111+ env vars mid-run, which is unsound alongside parallel tests)"
112+ );
113+ return;
114+ }
115+ if !have_ffmpeg() {
116+ eprintln!("SKIP: ffmpeg not on PATH");
117+ return;
118+ }
119+ let home = std::env::var("HOME").unwrap_or_default();
120+ let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
121+ if !path.exists() {
122+ eprintln!("SKIP: {} not found", path.display());
123+ return;
124+ }
125+ const MIN_BAND: usize = 14;
126+ const TOP_N: usize = 128;
127+
128+ let (ours_on, _, rate) = {
129+ let _zero = ec_aac::knobs::set_sbr_noise_zero(Some(false));
130+ let _fraction = ec_aac::knobs::set_sbr_noise_fraction(Some(true));
131+ our_decode(&path, 0).expect("our_decode works (noise on)")
132+ };
133+ let bookkept = ec_aac::noise_fraction_table();
134+ let (ours_off, _, _) = {
135+ let _zero = ec_aac::knobs::set_sbr_noise_zero(Some(true));
136+ let _fraction = ec_aac::knobs::set_sbr_noise_fraction(Some(false));
137+ our_decode(&path, 0).expect("our_decode works (noise zeroed)")
138+ };
139+
140+ let theirs = ffmpeg_decode(&path, 0, ours_on.len());
141+ let n = ours_on[0].len().min(ours_off[0].len()).min(MAX_SAMPLES);
142+ let on = &ours_on[0][..n];
143+ let off = &ours_off[0][..n];
144+
145+ // Per-band actual energy delta: `energy` in `bin_level_conviction`'s row
146+ // is always the FIRST argument's own band energy, so swap argument order
147+ // between the two calls to read both sides' energies at the SAME band
148+ // set (TOP_N kept above any real band count so both calls select every
149+ // band, not just each side's own top few).
150+ let rows_on = bin_level_conviction(on, off, rate, MIN_BAND, TOP_N);
151+ let rows_off = bin_level_conviction(off, on, rate, MIN_BAND, TOP_N);
152+ // (Round-42, Task 2) This `band_hz` feeds the `band` used below to look
153+ // up `bookkept` (`noise_fraction_table()`'s QMF band index, `tables.kx`
154+ // .. `tables.k2`, width `rate/128` -- 64 QMF bands over the SBR
155+ // Nyquist, per the NOISE-FRACTION-DEBUG dump above). It is NOT
156+ // `bin_level_conviction`'s own internal FFT-band scale (`rate/256`,
157+ // used correctly elsewhere in this file for THAT function's own rows).
158+ // Using `rate/256` here silently doubled every looked-up `band` index,
159+ // so every real band above roughly half of `k2` missed the table and
160+ // read back a false 0.0 bookkept fraction -- a test-side lookup bug,
161+ // not a decoder coverage gap (verified: `noise_fraction_table()` itself
162+ // has nonzero entries for QMF bands up to `k2`).
163+ let band_hz = f64::from(rate) / 128.0;
164+ let kx_band = bookkept.iter().map(|(b, ..)| *b).min().unwrap_or(0);
165+ println!(
166+ " (crossover: QMF band {kx_band}, {:.0} Hz -- rows below it are core-decoded and excluded from the total)",
167+ kx_band as f64 * band_hz
168+ );
169+ println!(
170+ " ACTUAL noise fraction (band_hz, energy_on, energy_off, actual_fraction, bookkept_fraction):"
171+ );
172+ let mut sum_on = 0.0f64;
173+ let mut sum_delta = 0.0f64;
174+ for (hz, e_on, ..) in &rows_on {
175+ let e_off = rows_off
176+ .iter()
177+ .find(|(hz2, ..)| (hz2 - hz).abs() < 1.0)
178+ .map(|(_, e, ..)| *e)
179+ .unwrap_or(0.0);
180+ let actual = if *e_on > 0.0 {
181+ (e_on - e_off) / e_on
182+ } else {
183+ 0.0
184+ };
185+ let band = (hz / band_hz).round() as usize;
186+ let book = bookkept
187+ .iter()
188+ .find(|(b, ..)| *b == band)
189+ .map(|(_, s, n, _)| if s + n > 0.0 { n / (s + n) } else { 0.0 })
190+ .unwrap_or(0.0);
191+ println!(
192+ " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}"
193+ );
194+ // HF ONLY (round-61): `MIN_BAND` (14, ~2412 Hz at 44.1k) sits BELOW
195+ // this stream's crossover (~4500 Hz), so the row list opens with a
196+ // dozen core-decoded bands that carry an order of magnitude more
197+ // energy than the SBR-generated ones (6.4e4 vs ~5e3) and, by
198+ // definition, zero injected noise. Summing them into a "whole-HF"
199+ // ratio dilutes it toward zero -- that is how this metric read
200+ // 0.0397 while every band above the crossover was realizing
201+ // 0.15-0.27. The crossover comes from the bookkeeping table itself
202+ // (its lowest QMF band IS `kx`), so it tracks the stream instead of
203+ // a constant that a QMF-mapping change can invalidate.
204+ if band < kx_band {
205+ continue;
206+ }
207+ sum_on += e_on;
208+ sum_delta += e_on - e_off;
209+ }
210+ let actual_total = if sum_on > 0.0 {
211+ sum_delta / sum_on
212+ } else {
213+ 0.0
214+ };
215+ println!(" ACTUAL whole-HF noise fraction: {actual_total:.4}");
216+
217+ // Corr re-verification: does zeroing the injected noise move full-band
218+ // correlation against the reference, and by how much (round-24 claimed
219+ // <0.001).
220+ let (_, corr_on) = best_lag_correlation(on, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]);
221+ let (_, corr_off) = best_lag_correlation(off, &theirs[0][..theirs[0].len().min(MAX_SAMPLES)]);
222+ println!(
223+ " full-band corr: noise-on {corr_on:.6} noise-off {corr_off:.6} delta {:.6}",
224+ corr_off - corr_on
225+ );
226+
227+ // (Round-42, Task 1/3 acceptance) Two real accounting bugs fixed this
228+ // round pushed the realized whole-HF fraction 0.1325 -> 0.1787 (reeln,
229+ // this same measurement): the boost pass was conserving the cell's FULL
230+ // envelope target against a signal-only realized sum (now conserves
231+ // total-vs-total, matching the reference algorithm's known
232+ // E_orig/E_curr+Q_M boost ratio), and `noise_amps` divided an
233+ // already-per-sample `noise_here` by the cell's QMF-band width a SECOND
234+ // time (removed) -- worse at wide high-frequency sfb cells, which is
235+ // exactly where the pre-fix gap was largest.
236+ //
237+ // The charter's ±0.05-of-bookkept (~0.38) target is NOT met by this
238+ // fix alone (round-43 investigated why, with `EC_AAC_SBR_CELLDUMP` in
239+ // `sbr_env::adjust`): `sbr_env::adjust`'s per-cell signal/noise split
240+ // is NOT the culprit -- corrected-band dumps (the charter's quoted
241+ // "6718/6891/7063Hz" and "8.5-13kHz decaying" bands turned out to be
242+ // mislabeled by a factor of two, this file's true SBR band spacing is
243+ // `rate/128` = 344.5Hz not the 172.3Hz FFT-analysis spacing those Hz
244+ // labels come from) show `adjust` injecting 40-85% noise share in the
245+ // QMF domain, at or ABOVE the ~0.37 bookkept split, not starved.
246+ //
247+ // (Round-44) Round-43's "essentially 0% of injected energy lands back
248+ // in the source subband" reading of
249+ // `synthesis_energy_gain_for_white_noise_excitation` was itself a test
250+ // bug, not a `Synthesis` defect: that harness measured its in-band FFT
251+ // window at `k0/SYNTHESIS_BANDS`, but band k's passband is centred at
252+ // `(k+0.5)*omega_step` with `omega_step = pi/(2*SYNTHESIS_BANDS)` --
253+ // HALF that fraction of Nyquist -- so the window sat on the image
254+ // region, not the signal. Corrected, a raw i.i.d.-per-slot draw already
255+ // lands ~0.49 of its own energy in its home subband's own frequency
256+ // range (not 0%), and a short slot-domain boxcar (`sbr_env::NoiseGen`'s
257+ // new `LOWPASS_TAPS = 2`) raises that to ~0.61 while staying spread
258+ // across the band (not collapsing to a residual tone) -- see the
259+ // harness's `synthesis_energy_gain_for_lowpassed_noise_excitation`.
260+ // That shape fix is real (an i.i.d. draw genuinely was less
261+ // band-faithful than it needed to be, and now is not), but re-measuring
262+ // THIS whole-HF metric after shipping it moved `actual_total` by <0.002
263+ // (0.1787 -> 0.1770, i.e. flat) -- because this metric sums the noise
264+ // energy DELTA across the whole swept HF spectrum, and energy an
265+ // i.i.d. draw aliased to a NEIGHBOURING QMF band still lands somewhere
266+ // inside that same swept HF range, so it was never actually excluded
267+ // from this particular sum. The ~0.38 bookkept vs ~0.18 actual gap is
268+ // therefore NOT a spectral-shape/aliasing defect (refuting round-43's
269+ // framing) -- it is a genuine energy shortfall, and per-band coherence
270+ // sits well below even the ACTUAL-fraction ceiling
271+ // (`sqrt(1 - f)`; ~0.15-0.20 measured vs. ~0.90 predicted at
272+ // `f ~= 0.177`, see `EC_AAC_SBR_PARITY_SPLIT`), meaning most of the
273+ // remaining HF correlation shortfall is a content defect independent of
274+ // noise level. Deferred: locating that energy shortfall and the
275+ // content defect, budget did not reach either this round (open, see
276+ // ledger). Floor tightened from round-42's 0.15 to the level this
277+ // fix's shape change actually lands at (0.177, both before and after),
278+ // with margin for run-to-run FFT/decode jitter.
279+ assert!(
280+ actual_total > 0.17,
281+ "whole-HF realized noise fraction regressed to {actual_total:.4} \
282+ (round-44 fix floor is 0.17; measured 0.1770 post-shape-fix, \
283+ 0.1787 pre-fix -- shape does not move this metric, see doc above)"
284+ );
285+}
286+
287+/// Discriminator instrument: one row per stream of the SBR header/frame
288+/// features actually parsed from its first ~20 `sbr_data()` frames, next to
289+/// that stream's own pass/fail correlation vs the reference decoder --
290+/// looking for which feature(s) separate the two known-PASS streams
291+/// (reeln, synthetic 48k HE) from the two known-FAIL families (FMJ,
292+/// synthetic 44.1k HE). Gated on the real files / fixture directory being
293+/// present, same as the tests it borrows machinery from; skips loudly,
294+/// generates nothing.
295+#[test]
296+pub(super) fn sbr_header_feature_table() {
297+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
298+ if !have_ffmpeg() {
299+ eprintln!("SKIP: ffmpeg not on PATH");
300+ return;
301+ }
302+ struct Row {
303+ label: String,
304+ path: PathBuf,
305+ aac_stream: usize,
306+ ffmpeg_stream: usize,
307+ }
308+ let mut rows: Vec<Row> = candidates()
309+ .into_iter()
310+ .map(|c| Row {
311+ label: c
312+ .path
313+ .file_stem()
314+ .map(|s| s.to_string_lossy().into_owned())
315+ .unwrap_or_default(),
316+ path: c.path,
317+ aac_stream: c.aac_stream,
318+ ffmpeg_stream: c.ffmpeg_stream,
319+ })
320+ .collect();
321+ let fixtures = std::env::var("EC_AAC_HEAAC_FIXTURES")
322+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
323+ let fixtures = PathBuf::from(fixtures);
324+ if require_fixture(&fixtures, "scripts/aac-tables/make-heaac-fixtures.sh") {
325+ for rate in [48_000u32, 44_100] {
326+ for br in ["32k", "48k", "64k", "96k"] {
327+ let p = fixtures.join(format!("heaac_{rate}_{br}.m4a"));
328+ if require_fixture(&p, "scripts/aac-tables/make-heaac-fixtures.sh") {
329+ rows.push(Row {
330+ label: format!("synth-{rate}-{br}"),
331+ path: p,
332+ aac_stream: 0,
333+ ffmpeg_stream: 0,
334+ });
335+ }
336+ }
337+ }
338+ }
339+ if rows.is_empty() {
340+ eprintln!("SKIP: no real HE-AAC files and no synthetic fixtures found");
341+ return;
342+ }
343+ let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
344+ const WIDE_LAG_MAX: i64 = 20_000;
345+ println!(
346+ "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10} {:>6}",
347+ "stream",
348+ "rate",
349+ "kx",
350+ "k2",
351+ "xovr",
352+ "sfrq",
353+ "efrq",
354+ "fscl",
355+ "ascl",
356+ "nbnd",
357+ "lbnd",
358+ "lgn",
359+ "ifrq",
360+ "smooth",
361+ "envs",
362+ "invf",
363+ "harm",
364+ "df%",
365+ "corr"
366+ );
367+ for r in &rows {
368+ let before = ec_aac::sbr_sideinfo_log().len();
369+ let Some((ours, sbr, our_rate)) = our_decode(&r.path, r.aac_stream) else {
370+ eprintln!("SKIP {}: could not decode", r.label);
371+ continue;
372+ };
373+ if sbr != ec_aac::SbrSupport::V1 {
374+ eprintln!("SKIP {}: not SBR v1", r.label);
375+ continue;
376+ }
377+ let log = ec_aac::sbr_sideinfo_log();
378+ let frames: Vec<_> = log[before..]
379+ .iter()
380+ .filter(|row| row.ch == 0)
381+ .take(20)
382+ .collect();
383+ if frames.is_empty() {
384+ eprintln!("SKIP {}: no sideinfo rows captured", r.label);
385+ continue;
386+ }
387+ let f0 = &frames[0];
388+ let mut env_counts: std::collections::BTreeMap<usize, usize> = Default::default();
389+ let mut invf_seen: std::collections::BTreeSet<u8> = Default::default();
390+ let mut any_harmonic = false;
391+ let mut df_total = 0usize;
392+ let mut df_ones = 0usize;
393+ for row in &frames {
394+ *env_counts
395+ .entry(row.t_env.len().saturating_sub(1))
396+ .or_default() += 1;
397+ invf_seen.extend(&row.invf_mode);
398+ if row
399+ .add_harmonic
400+ .as_ref()
401+ .is_some_and(|h| h.iter().any(|&v| v != 0))
402+ {
403+ any_harmonic = true;
404+ }
405+ df_total += row.df_env.len() + row.df_noise.len();
406+ df_ones += row
407+ .df_env
408+ .iter()
409+ .chain(&row.df_noise)
410+ .filter(|&&b| b != 0)
411+ .count();
412+ }
413+ let df_pct = if df_total > 0 {
414+ 100.0 * df_ones as f64 / df_total as f64
415+ } else {
416+ 0.0
417+ };
418+ let envs_hist: String = env_counts
419+ .iter()
420+ .map(|(k, v)| format!("{k}x{v}"))
421+ .collect::<Vec<_>>()
422+ .join(",");
423+ let invf_str: String = invf_seen
424+ .iter()
425+ .map(|v| v.to_string())
426+ .collect::<Vec<_>>()
427+ .join("");
428+ let theirs = ffmpeg_decode(&r.path, r.ffmpeg_stream, ours.len());
429+ let (_, corr) = best_lag_correlation_wide(&ours[0], &theirs[0], WIDE_LAG_MAX);
430+ println!(
431+ "{:<20} {:>6} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>5} {:>10} {:>10} {:>8} {:>8} {:>10.1} {:>6.3}",
432+ r.label,
433+ our_rate,
434+ f0.kx,
435+ f0.k2,
436+ f0.xover_band,
437+ f0.start_freq,
438+ f0.stop_freq,
439+ f0.freq_scale,
440+ f0.alter_scale,
441+ f0.noise_bands,
442+ f0.limiter_bands,
443+ f0.limiter_gains,
444+ f0.interpol_freq,
445+ f0.smoothing_mode,
446+ envs_hist,
447+ invf_str,
448+ any_harmonic,
449+ df_pct,
450+ corr
451+ );
452+ println!(" patches (frame0): {:?}", f0.patch_lengths);
453+ }
454+}
455+
456+/// Round (sbr-per-au): per-AU localization. Decodes the same AU list through
457+/// (a) the core-only decoder and (b) the full SBR chain, tracks each AU's
458+/// sample range in both output streams as it goes (so a per-AU decode
459+/// failure on either side does not desync the mapping), aligns the two
460+/// streams ONCE in the core's own native rate domain (same decimate
461+/// convention `synthetic_heaac_matrix`'s `ours_v_core` row already trusts),
462+/// then re-uses that single lag for every AU's own low-band correlation.
463+/// Prints the first 5 AUs below 0.9 with that AU's SBR side-info (source/
464+/// envelope count/freq_res/kx/k2) so a per-frame trigger (e.g. `hold`
465+/// frames, a specific `freq_res`) shows up directly instead of needing a
466+/// second pass. If the first divergent AU is 0, that is reported explicitly
467+/// -- divergence from the very first AU means a per-stream setup mismatch,
468+/// not a per-frame trigger.
469+pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) {
470+ let Some((asc, aus)) = extract_aac_track(path, aac_stream) else {
471+ eprintln!("SKIP {label}: extract_aac_track failed");
472+ return;
473+ };
474+ let Ok(full_cfg) = parse_audio_specific_config(&asc) else {
475+ eprintln!("SKIP {label}: asc parse failed");
476+ return;
477+ };
478+ if !full_cfg.sbr_present {
479+ eprintln!("SKIP {label}: no SBR");
480+ return;
481+ }
482+ let mut core_cfg = full_cfg.clone();
483+ core_cfg.sbr_present = false;
484+ core_cfg.ps_present = false;
485+ core_cfg.extension_sample_rate = None;
486+ let core_rate = core_cfg.sample_rate;
487+ let mut core_dec = AacDecoder::with_config(core_cfg);
488+ let mut full_dec = AacDecoder::with_config(full_cfg);
489+ let full_rate = full_dec.output_sample_rate().unwrap_or(core_rate * 2);
490+
491+ struct AuInfo {
492+ core_range: (usize, usize),
493+ side: Option<ec_aac::SbrSideInfoRow>,
494+ }
495+ let mut core_ch0: Vec<f32> = Vec::new();
496+ let mut full_ch0: Vec<f32> = Vec::new();
497+ let mut aus_info: Vec<AuInfo> = Vec::new();
498+ for au in aus.iter().take(1_500) {
499+ let side_before = ec_aac::sbr_sideinfo_log().len();
500+ let cs = core_ch0.len();
501+ if let Ok(f) = core_dec.decode(au, None) {
502+ let ch = usize::from(f.channels).max(1);
503+ core_ch0.extend(f.samples.iter().step_by(ch).copied());
504+ }
505+ let ce = core_ch0.len();
506+ if let Ok(f) = full_dec.decode(au, None) {
507+ let ch = usize::from(f.channels).max(1);
508+ full_ch0.extend(f.samples.iter().step_by(ch).copied());
509+ }
510+ let side = ec_aac::sbr_sideinfo_log()[side_before..]
511+ .iter()
512+ .find(|r| r.ch == 0)
513+ .cloned();
514+ aus_info.push(AuInfo {
515+ core_range: (cs, ce),
516+ side,
517+ });
518+ if full_ch0.len() > MAX_SAMPLES {
519+ break;
520+ }
521+ }
522+ if core_ch0.is_empty() || full_ch0.is_empty() {
523+ eprintln!(
524+ "SKIP {label}: empty decode (core {} full {})",
525+ core_ch0.len(),
526+ full_ch0.len()
527+ );
528+ return;
529+ }
530+
531+ // Same convention `full_chain_low_band_matches_own_core` already
532+ // validated (0.9967 on reeln): naive nearest-neighbor 2x-upsample
533+ // the core into the full-rate domain, low-pass both well under the core
534+ // Nyquist. The decimate-into-core-rate convention `synthetic_heaac_matrix`
535+ // uses for its own `ours_v_core` diagnostic column was tried first here
536+ // and reads badly (~-0.19) even on reeln, which is known-good --
537+ // that column is evidently not a reliable self-consistency probe on its
538+ // own, so this per-AU tool anchors on the convention independently
539+ // proven correct instead.
540+ let up: Vec<f32> = core_ch0.iter().flat_map(|&s| [s, s]).collect();
541+ let cutoff = f64::from(core_rate) * 0.4;
542+ let ol = lowpass(&full_ch0, full_rate, cutoff);
543+ let ul = lowpass(&up, full_rate, cutoff);
544+ const WIDE_LAG_MAX: i64 = 20_000;
545+ let (lag, align_corr) = best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX);
546+ println!(
547+ "{label}: core={core_rate}Hz full={full_rate}Hz global align (upsampled full-rate domain) lag={lag} corr={align_corr:.6}"
548+ );
549+
550+ let mut shown = 0usize;
551+ let mut first_divergent: Option<usize> = None;
552+ for (i, info) in aus_info.iter().enumerate() {
553+ let (cs, ce) = info.core_range;
554+ if ce <= cs {
555+ continue;
556+ }
557+ // core_range is in core-domain sample counts; the upsampled/lowpassed
558+ // arrays are at full rate, so the AU's window there is 2x as wide.
559+ let fs = cs * 2;
560+ let fe = ce * 2;
561+ let ds = match usize::try_from(fs as i64 + lag) {
562+ Ok(v) => v,
563+ Err(_) => continue,
564+ };
565+ let de = ds + (fe - fs);
566+ if de > ul.len() || fe > ol.len() {
567+ break;
568+ }
569+ let c = correlation(&ol[fs..fe], &ul[ds..de]);
570+ if c < 0.9 {
571+ if first_divergent.is_none() {
572+ first_divergent = Some(i);
573+ }
574+ if shown < 5 {
575+ println!(" AU {i}: low-band corr={c:.6} side={:?}", info.side);
576+ shown += 1;
577+ }
578+ }
579+ }
580+ match first_divergent {
581+ Some(0) => println!(
582+ "{label}: divergence starts at AU 0 -- per-STREAM setup mismatch, not a per-frame trigger"
583+ ),
584+ Some(i) => println!("{label}: first divergent AU = {i}"),
585+ None => println!("{label}: no AU below 0.9 corr in the probed window"),
586+ }
587+}
588+
589+#[test]
590+pub(super) fn per_au_low_band_divergence() {
591+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
592+ if !have_ffmpeg() {
593+ eprintln!("SKIP: ffmpeg not on PATH");
594+ return;
595+ }
596+ let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
597+ for c in &candidates() {
598+ per_au_low_band_probe(&c.path.display().to_string(), &c.path, c.aac_stream);
599+ }
600+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
601+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
602+ let failing = PathBuf::from(&dir).join("heaac_44100_48k.m4a");
603+ if require_fixture(&failing, "scripts/aac-tables/make-heaac-fixtures.sh") {
604+ per_au_low_band_probe("synthetic 44100 48k (failing)", &failing, 0);
605+ }
606+}
607+
608+/// Coordinator follow-up: prints what `parse_audio_specific_config` actually
609+/// returns for a candidate's real ASC bytes (object/rate/sf_index/
610+/// sbr_present/extension_sample_rate), what `AacDecoder` reports back
611+/// (`SbrSupport`, `output_sample_rate`) from those parsed fields, then
612+/// re-decodes the SAME AU list through a HAND-BUILT explicit
613+/// `AudioSpecificConfig` (object_type=5, known core/ext rates) instead of
614+/// the parsed one -- if that jumps the correlations to ~1, the parsed
615+/// config (or something object_type-conditioned at runtime) is the defect,
616+/// not the SBR DSP chain itself. Also re-runs `full_chain_low_band_matches_
617+/// own_core`'s FMJ probe with `WIDE_LAG_MAX` raised to 100_000.
618+#[test]
619+pub(super) fn probe_explicit_config_and_wide_lag() {
620+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
621+ if !have_ffmpeg() {
622+ eprintln!("SKIP: ffmpeg not on PATH");
623+ return;
624+ }
625+ fn decode_with(cfg: ec_aac::AudioSpecificConfig, aus: &[Vec<u8>]) -> (Vec<Vec<f32>>, u32) {
626+ let rate = match (cfg.sbr_present, cfg.ps_present) {
627+ (true, false) => cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2),
628+ _ => cfg.sample_rate,
629+ };
630+ let mut d = AacDecoder::with_config(cfg);
631+ let mut planes: Vec<Vec<f32>> = Vec::new();
632+ for au in aus {
633+ let Ok(f) = d.decode(au, None) else { continue };
634+ let ch = usize::from(f.channels);
635+ if ch == 0 {
636+ continue;
637+ }
638+ if planes.is_empty() {
639+ planes = vec![Vec::new(); ch];
640+ }
641+ for (i, v) in f.samples.iter().enumerate() {
642+ planes[i % ch].push(*v);
643+ }
644+ if planes[0].len() >= MAX_SAMPLES {
645+ break;
646+ }
647+ }
648+ (planes, rate)
649+ }
650+
651+ // `synthetic` marks the case as coming from the committed fixture library
652+ // (`scripts/aac-tables/make-heaac-fixtures.sh`); the FMJ row is a
653+ // `~/Downloads` host corpus and keeps its plain skip.
654+ for (
655+ label,
656+ path,
657+ aac_stream,
658+ ffmpeg_stream,
659+ core_sf_index,
660+ core_rate,
661+ ext_rate,
662+ channels,
663+ synthetic,
664+ ) in [
665+ (
666+ "FMJ",
667+ format!(
668+ "{}/Downloads/reelp/reelp.mkv",
669+ std::env::var("HOME").unwrap_or_default()
670+ ),
671+ 1usize,
672+ 3usize,
673+ 6u8,
674+ 24_000u32,
675+ 48_000u32,
676+ 2u16,
677+ false,
678+ ),
679+ (
680+ "heaac_44100_48k",
681+ format!(
682+ "{}/heaac_44100_48k.m4a",
683+ std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| format!(
684+ "{}/../../.cache/heaac-fixtures",
685+ env!("CARGO_MANIFEST_DIR")
686+ ))
687+ ),
688+ 0,
689+ 0,
690+ 4,
691+ 44_100,
692+ 0, // filled below from parsed cfg's own extension_sample_rate
693+ 2,
694+ true,
695+ ),
696+ ] {
697+ let path = PathBuf::from(path);
698+ if synthetic {
699+ if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
700+ continue;
701+ }
702+ } else if !path.exists() {
703+ eprintln!("SKIP {label}: {} absent", path.display());
704+ continue;
705+ }
706+ let Some((asc, aus)) = extract_aac_track(&path, aac_stream) else {
707+ eprintln!("SKIP {label}: extract failed");
708+ continue;
709+ };
710+ let parsed = parse_audio_specific_config(&asc);
711+ println!("{label}: asc={asc:02x?} parsed={parsed:?}");
712+ let Ok(parsed_cfg) = parsed else {
713+ eprintln!("SKIP {label}: parse failed");
714+ continue;
715+ };
716+ let d = AacDecoder::with_config(parsed_cfg.clone());
717+ println!(
718+ " runtime: sbr_support={:?} output_sample_rate={:?}",
719+ d.sbr_support(),
720+ d.output_sample_rate()
721+ );
722+
723+ // Hand-built EXPLICIT config: object_type=5 (SBR), known core/ext
724+ // rates, sbr_present forced true regardless of what the real ASC
725+ // parsed to.
726+ let ext = if ext_rate == 0 {
727+ parsed_cfg.extension_sample_rate.unwrap_or(core_rate * 2)
728+ } else {
729+ ext_rate
730+ };
731+ let hand_cfg = ec_aac::AudioSpecificConfig {
732+ object_type: ec_aac::AOT_SBR,
733+ sample_rate: core_rate,
734+ sf_index: core_sf_index,
735+ channels,
736+ channel_config: channels as u8,
737+ sbr_present: true,
738+ ps_present: false,
739+ extension_sample_rate: Some(ext),
740+ pce: Vec::new(),
741+ };
742+ let (hand_planes, hand_rate) = decode_with(hand_cfg.clone(), &aus);
743+ if hand_planes.is_empty() {
744+ eprintln!(" hand-built config: no channels decoded");
745+ continue;
746+ }
747+ // Own-core self-consistency (upsample+lowpass convention).
748+ let core_cfg = ec_aac::AudioSpecificConfig {
749+ sbr_present: false,
750+ ps_present: false,
751+ extension_sample_rate: None,
752+ pce: Vec::new(),
753+ ..hand_cfg.clone()
754+ };
755+ let (core_planes, _) = decode_with(core_cfg, &aus);
756+ if !core_planes.is_empty() {
757+ let up: Vec<f32> = core_planes[0].iter().flat_map(|&s| [s, s]).collect();
758+ let cutoff = f64::from(core_rate) * 0.4;
759+ let ol = lowpass(&hand_planes[0], hand_rate, cutoff);
760+ let ul = lowpass(&up, hand_rate, cutoff);
761+ let (lag, corr) = best_lag_correlation_wide(&ol, &ul, 100_000);
762+ println!(
763+ " hand-built explicit config: low-band vs own core: lag={lag} corr={corr:.6}"
764+ );
765+ }
766+ let theirs = ffmpeg_decode(&path, ffmpeg_stream, hand_planes.len());
767+ if let (Some(o), Some(t)) = (hand_planes.first(), theirs.first()) {
768+ let (lag, corr) = best_lag_correlation_wide(o, t, 100_000);
769+ println!(
770+ " hand-built explicit config: full-band vs reference: lag={lag} corr={corr:.6}"
771+ );
772+ }
773+ }
774+
775+ // Probe B: FMJ's own (parsed) full-chain-vs-own-core lag search, widened
776+ // to 100_000 (5x the existing WIDE_LAG_MAX=20_000 this file's other
777+ // tests use) -- the coarse search in `full_chain_low_band_matches_own_
778+ // core` landed right at that bound's edge (20005), so this checks
779+ // whether FMJ's true delay simply lies further out.
780+ let home = std::env::var("HOME").unwrap_or_default();
781+ let fmj = PathBuf::from(format!(
782+ "{home}/Downloads/reelp/reelp.mkv"
783+ ));
784+ if fmj.exists()
785+ && let (Some((core, core_rate)), Some((full, sbr, full_rate))) =
786+ (our_decode_core_only(&fmj, 1), our_decode(&fmj, 1))
787+ && sbr == ec_aac::SbrSupport::V1
788+ {
789+ let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();
790+ let cutoff = f64::from(core_rate) * 0.4;
791+ let ol = lowpass(&full[0], full_rate, cutoff);
792+ let ul = lowpass(&up, full_rate, cutoff);
793+ let (lag, corr) = best_lag_correlation_wide(&ol, &ul, 100_000);
794+ println!("FMJ WIDE_LAG_MAX=100_000: ch0 best lag={lag} corr={corr:.6}");
795+ }
796+}
797+
798+/// One channel of `path`'s given absolute stream, isolated with an ffmpeg
799+/// `pan` filter rather than raw de-interleaving -- the charter's own witness
800+/// rule (see `ffmpeg_decode`'s doc and the ledger's "never use -ac 1", which
801+/// applies just as much to picking one of N channels as to downmixing).
802+pub(super) fn ffmpeg_decode_pan_channel(path: &Path, absolute_stream: usize, channel: usize) -> Vec<f32> {
803+ let out = Command::new("ffmpeg")
804+ .args(["-v", "error", "-i"])
805+ .arg(path)
806+ .args([
807+ "-map",
808+ &format!("0:{absolute_stream}"),
809+ "-t",
810+ "10",
811+ "-af",
812+ &format!("pan=1c|c0=c{channel}"),
813+ "-f",
814+ "f32le",
815+ "-acodec",
816+ "pcm_f32le",
817+ "-",
818+ ])
819+ .output()
820+ .expect("ffmpeg runs");
821+ assert!(
822+ out.status.success(),
823+ "ffmpeg pan decode failed: {}",
824+ String::from_utf8_lossy(&out.stderr)
825+ );
826+ out.stdout
827+ .as_chunks::<4>().0.iter()
828+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
829+ .collect()
830+}
crates/ec-aac/tests/sbr_real_library/chunk_c.rsadded+772 -0
@@ -0,0 +1,772 @@
1+//! SBR real-library checks and probes, part C.
2+
3+use super::*;
4+
5+/// The user's real 7.1 mp4 whose lone AAC track was once suspected (per the
6+/// ledger) to need AAC Main/LTP (§4.6.6/§4.6.7) prediction support this
7+/// decoder doesn't have. Re-checked here: its AudioSpecificConfig's
8+/// `audioObjectType` is 2 (AAC-LC, confirmed both from the container's ASC
9+/// bytes and from the ADTS `profile` field ffmpeg remuxes it to), and this
10+/// decoder in fact reads its whole ~994s track -- 45000+ access units --
11+/// with zero `Err` returns. No `predictor_data_present` refusal is reachable
12+/// on this file; the capability gap the ledger recorded does not exist for
13+/// it. This test is the standing proof: it decodes 10s of all 8 channels and
14+/// checks each against ffmpeg's own decode, isolated per channel by `pan`
15+/// (never `-ac 1`, which would remix rather than isolate).
16+#[test]
17+pub(super) fn reelq_multichannel_lc_matches_reference() {
18+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
19+ if !have_ffmpeg() {
20+ eprintln!("SKIP: ffmpeg not on PATH");
21+ return;
22+ }
23+ let home = std::env::var("HOME").unwrap_or_default();
24+ let path = PathBuf::from(format!(
25+ "{home}/Downloads/reelq/reelq.mp4"
26+ ));
27+ if !path.exists() {
28+ eprintln!("SKIP: {} not present", path.display());
29+ return;
30+ }
31+ let Some((ours, _sbr, rate)) = our_decode(&path, 0) else {
32+ panic!("ReelQ AAC track failed to decode at all");
33+ };
34+ assert_eq!(ours.len(), 8, "expected 7.1 (8 channels)");
35+ let want = (rate as usize) * 10; // 10s per the charter
36+ for (ch, o) in ours.iter().enumerate() {
37+ let o = &o[..o.len().min(want)];
38+ let t = ffmpeg_decode_pan_channel(&path, 2, ch);
39+ let t = &t[..t.len().min(want)];
40+ let (lag, corr) = best_lag_correlation(o, t);
41+ println!("ReelQ ch{ch}: lag {lag}, corr {corr:.6}");
42+ assert!(corr >= 0.999, "ch{ch} corr {corr:.6} < 0.999 (lag {lag})");
43+ }
44+}
45+
46+/// Coupled-CPE swap probe: the `heaac_44100_48k` fixture's SBR side info
47+/// shows `coupling: true` on nearly every AU (reeln/FMJ, both passing,
48+/// show `coupling: false`) -- checks whether our decoded ch0 actually
49+/// correlates better against the REFERENCE's R channel than its own L.
50+/// RULED OUT (prior rounds): `sbr_env::dequant_pair`'s coupling formula,
51+/// `sbr_hf`, and per-channel plane threading -- none change this probe's
52+/// numbers.
53+///
54+/// ROOT CAUSE (this round): NOT a channel swap. The free lag search
55+/// (`best_lag_correlation_wide`) is provably unreliable on this file's
56+/// periodic content -- it even mis-searches ref L vs ref R against each
57+/// other (lag=-24 corr=0.213, worse than the naive fixed lag=0's
58+/// corr=0.873) -- so ch0-vs-L and ch0-vs-R land on two DIFFERENT,
59+/// independently-searched lags (-4617 and -4674) instead of one true
60+/// lag, faking a "ch0 correlates with R" swap signature. At the single
61+/// fixed lag that actually maximizes the summed (mono) ch0+ch1-vs-refL+R
62+/// correlation (-4674, mono corr 0.778), a per-1-second sub-window
63+/// breakdown of corr(ch0,refL) vs corr(ch0,refR) shows ch0 starts
64+/// NEAR-PERFECT against ref L (0.998 at t=0s) and *drifts* down to 0.68
65+/// by t=9s while its correlation with ref R rises from 0.90 to ~0.99 over
66+/// the same span -- a clean, monotonic crossover, not a step change. That
67+/// is the signature of accumulating CLOCK/SAMPLE-COUNT DRIFT between our
68+/// decode and ffmpeg's reference decode (a single global lag can't track
69+/// a linearly growing offset), not a channel identity swap: ch0 IS L,
70+/// decoded correctly, and a single fixed-lag window increasingly
71+/// misaligns as the file plays, which -- because ref L and ref R are
72+/// themselves correlated (0.873 at lag 0) -- coincidentally starts to
73+/// look R-shaped as drift accumulates. See the fixed-lag matrix and
74+/// per-1s subwindow prints below for the numbers, and the `assert!` for
75+/// the swap-shaped-result gate this round adds.
76+#[test]
77+pub(super) fn coupled_cpe_channel_swap_probe() {
78+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
79+ if !have_ffmpeg() {
80+ eprintln!("SKIP: ffmpeg not on PATH");
81+ return;
82+ }
83+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
84+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
85+ let path = PathBuf::from(&dir).join("heaac_44100_48k.m4a");
86+ if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
87+ return;
88+ }
89+ let Some((ours, sbr, out_rate)) = our_decode(&path, 0) else {
90+ panic!("heaac_44100_48k failed to decode");
91+ };
92+ assert_eq!(sbr, ec_aac::SbrSupport::V1);
93+ assert_eq!(ours.len(), 2, "expect stereo");
94+ let ref_l = ffmpeg_decode_pan_channel(&path, 0, 0);
95+ let ref_r = ffmpeg_decode_pan_channel(&path, 0, 1);
96+ {
97+ let n = ref_l.len().min(ref_r.len()).min(WINDOW);
98+ println!(
99+ "ref L vs ref R (no lag): corr={:.6}",
100+ correlation(&ref_l[..n], &ref_r[..n])
101+ );
102+ let (lag, corr) = best_lag_correlation_wide(&ref_l, &ref_r, SEARCH_LAG_MAX);
103+ println!("ref L vs ref R (best lag search): lag={lag} corr={corr:.6}");
104+ }
105+ for (och, ochan) in ours.iter().enumerate() {
106+ let (lag_l, corr_l) = best_lag_correlation_wide(ochan, &ref_l, SEARCH_LAG_MAX);
107+ let (lag_r, corr_r) = best_lag_correlation_wide(ochan, &ref_r, SEARCH_LAG_MAX);
108+ println!(
109+ "ch{och}: vs ref L lag={lag_l} corr={corr_l:.6}; vs ref R lag={lag_r} corr={corr_r:.6}"
110+ );
111+ }
112+
113+ // Same probe on the CORE-ONLY decode (SBR disabled): if the swap
114+ // already shows here, it's in the AAC-LC core's own CPE/M-S decode,
115+ // not in the SBR coupling math.
116+ let (asc, aus) = extract_aac_track(&path, 0).expect("extract");
117+ let mut core_cfg = parse_audio_specific_config(&asc).expect("asc parses");
118+ core_cfg.sbr_present = false;
119+ core_cfg.ps_present = false;
120+ core_cfg.extension_sample_rate = None;
121+ let mut core_dec = AacDecoder::with_config(core_cfg);
122+ let mut core_planes: Vec<Vec<f32>> = vec![Vec::new(), Vec::new()];
123+ let dump = std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok();
124+ for (au_idx, au) in aus.iter().enumerate() {
125+ if let Ok(f) = core_dec.decode(au, None) {
126+ let ch = usize::from(f.channels);
127+ if ch == 2 {
128+ if dump && au_idx < 20 {
129+ for c in 0..2 {
130+ let plane: Vec<f32> =
131+ f.samples.iter().skip(c).step_by(2).copied().collect();
132+ let rms = (plane
133+ .iter()
134+ .map(|v| f64::from(*v) * f64::from(*v))
135+ .sum::<f64>()
136+ / plane.len().max(1) as f64)
137+ .sqrt();
138+ eprintln!(
139+ "COREAU n={au_idx} ch={c} len={} rms={rms:.6} first8={:?}",
140+ plane.len(),
141+ &plane[..8.min(plane.len())]
142+ );
143+ }
144+ }
145+ for (i, v) in f.samples.iter().enumerate() {
146+ core_planes[i % 2].push(*v);
147+ }
148+ }
149+ }
150+ if core_planes[0].len() >= MAX_SAMPLES {
151+ break;
152+ }
153+ }
154+ let core_rate = core_dec.output_sample_rate().unwrap_or(22050);
155+ let ref_core = ffmpeg_decode_at_rate(&path, 0, 2, core_rate);
156+ for (och, ochan) in core_planes.iter().enumerate() {
157+ for (rch, rplane) in ref_core.iter().enumerate() {
158+ let (lag, corr) = best_lag_correlation_wide(ochan, rplane, SEARCH_LAG_MAX);
159+ let name = if rch == 0 { "L" } else { "R" };
160+ println!("core ch{och} vs ref {name}: lag={lag} corr={corr:.6}");
161+ }
162+ }
163+
164+ // Fixed-lag matrix: is the "swap" a lag-search artifact on periodic
165+ // content, or a real decode defect? A genuine per-channel swap must
166+ // show LOW corr(ch0,refL) and HIGH corr(ch0,refR) at the SAME lag that
167+ // maximizes the mono (ch0+ch1 vs refL+refR) correlation, not just at
168+ // whatever lag each pair's own FREE search happened to land on
169+ // independently (ref L vs ref R themselves correlate 0.87 at lag 0, so
170+ // at any single lag corr(ch0,L) and corr(ch0,R) must already be close).
171+ let (core_lag0, core_corr0) =
172+ best_lag_correlation_wide(&core_planes[0], &ref_core[0], SEARCH_LAG_MAX);
173+ let core_implied_lag = core_lag0 * 2;
174+ println!(
175+ "core ch0 vs ref L best lag={core_lag0} corr={core_corr0:.6} -> implied full-rate lag={core_implied_lag}"
176+ );
177+ let mono_ours: Vec<f32> = ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
178+ let mono_ref: Vec<f32> = {
179+ let n = ref_l.len().min(ref_r.len());
180+ ref_l[..n]
181+ .iter()
182+ .zip(&ref_r[..n])
183+ .map(|(a, b)| a + b)
184+ .collect()
185+ };
186+ let (mono_lag, mono_corr) = best_lag_correlation_wide(&mono_ours, &mono_ref, SEARCH_LAG_MAX);
187+ println!("mono (ch0+ch1) vs ref (L+R) best lag={mono_lag} corr={mono_corr:.6}");
188+ let fixed_lags: [(i64, &str); 4] = [
189+ (-4674, "swap-probe ch0-vs-refR lag"),
190+ (-4617, "swap-probe ch0-vs-refL lag"),
191+ (core_implied_lag, "core-implied lag"),
192+ (mono_lag, "mono-best lag"),
193+ ];
194+ // `best_lag_correlation_wide`'s coarse-then-refine search is proven
195+ // unreliable on this file's periodic content -- it even mis-picks ref L
196+ // vs ref R itself (lag=-24 corr=0.213, worse than the naive lag-0
197+ // corr=0.873 above). So the TRUE best lag among our 4 candidates is
198+ // whichever one actually maximizes the fixed-lag mono correlation, not
199+ // whatever `mono_lag` the free search reported.
200+ let mut true_best = (
201+ mono_lag,
202+ "mono-best lag (free search)",
203+ 0.0f64,
204+ 0.0f64,
205+ 0.0f64,
206+ 0.0f64,
207+ mono_corr,
208+ );
209+ for (lag, label) in fixed_lags {
210+ let c0l = correlation_at_lag(&ours[0], &ref_l, lag);
211+ let c0r = correlation_at_lag(&ours[0], &ref_r, lag);
212+ let c1l = correlation_at_lag(&ours[1], &ref_l, lag);
213+ let c1r = correlation_at_lag(&ours[1], &ref_r, lag);
214+ let mono = correlation_at_lag(&mono_ours, &mono_ref, lag);
215+ println!(
216+ "fixed lag={lag} ({label}): corr(ch0,L)={c0l:.6} corr(ch0,R)={c0r:.6} corr(ch1,L)={c1l:.6} corr(ch1,R)={c1r:.6} mono={mono:.6}"
217+ );
218+ if mono > true_best.6 {
219+ true_best = (lag, label, c0l, c0r, c1l, c1r, mono);
220+ }
221+ }
222+ let (best_lag, best_label, best_c0l, best_c0r, _best_c1l, _best_c1r, best_mono) = true_best;
223+ println!(
224+ "TRUE best-by-fixed-mono lag={best_lag} ({best_label}): corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6} mono={best_mono:.6}"
225+ );
226+ // Assert on the fixed-lag result, not the free search: a genuine
227+ // per-channel swap needs corr(ch0,L) LOW while corr(ch0,R) is HIGH at
228+ // this properly-determined lag. It isn't -- ch0's correlation with L
229+ // (0.78) sits at/below the L-vs-R baseline cross-correlation
230+ // (ref L vs ref R = 0.873 at lag 0), i.e. no more affinity to L than
231+ // any R-channel content already has from L/R being correlated to begin
232+ // with -- so this is a lag-search artifact on periodic content, not a
233+ // channel swap.
234+ assert!(
235+ !(best_c0l < 0.3 && best_c0r > 0.9),
236+ "swap-shaped result at the properly-determined lag {best_lag}: corr(ch0,L)={best_c0l:.6} corr(ch0,R)={best_c0r:.6}"
237+ );
238+ // Per-1-s-window corr(ch0,refL) at the TRUE best lag: uniform vs
239+ // dipping tells apart "genuinely swapped everywhere" from "a
240+ // coarse-search artifact confined to a periodic stretch".
241+ {
242+ let step = out_rate.max(1) as usize;
243+ let (oa0, ob0) = if best_lag >= 0 {
244+ (0usize, mono_lag as usize)
245+ } else {
246+ ((-best_lag) as usize, 0usize)
247+ };
248+ let mut w = 0usize;
249+ loop {
250+ let oa = oa0 + w * step;
251+ let ob = ob0 + w * step;
252+ if oa + step > ours[0].len() || ob + step > ref_l.len().min(ref_r.len()) {
253+ break;
254+ }
255+ let cl = correlation(&ours[0][oa..oa + step], &ref_l[ob..ob + step]);
256+ let cr = correlation(&ours[0][oa..oa + step], &ref_r[ob..ob + step]);
257+ println!(
258+ "subwindow t={w}s ch0 vs ref L/R @ lag {best_lag}: corr(L)={cl:.6} corr(R)={cr:.6}"
259+ );
260+ w += 1;
261+ }
262+ }
263+
264+ // Isolated round trip: run `core_planes` (the CORE-ONLY decode, already
265+ // shown correctly-directed above) through a bare, fresh
266+ // Analysis(32)->zero-stuff-HF->Synthesis(64) pair -- no sbr_chain, no
267+ // per-AU/per-tag HashMap element lookup, no envelope/HF/noise code at
268+ // all -- to see whether the swap reproduces on the QMF math alone in a
269+ // single continuous stream, isolating it from any per-AU state
270+ // threading in `sbr_chain::apply_data`.
271+ use ec_aac::sbr_qmf::{ANALYSIS_BANDS as AB, Analysis, SYNTHESIS_BANDS as SB, Synthesis};
272+ const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
273+ for kx in [6usize, 12, 20] {
274+ let mut iso_out: [Vec<f32>; 2] = [Vec::new(), Vec::new()];
275+ for (c, chan) in core_planes.iter().enumerate() {
276+ let mut analysis = Analysis::new();
277+ let mut synthesis = Synthesis::new();
278+ let n_slots = chan.len() / AB;
279+ for slot in 0..n_slots {
280+ let mut chunk = [0f32; 32];
281+ chunk.copy_from_slice(&chan[slot * AB..(slot + 1) * AB]);
282+ for s in &mut chunk {
283+ *s /= OUTPUT_SCALE;
284+ }
285+ let sub = analysis.process_slot(&chunk);
286+ let mut v = [ec_dsp::Complex::new(0.0, 0.0); 64];
287+ v[0..kx.min(AB)].copy_from_slice(&sub[0..kx.min(AB)]);
288+ let mut pcm = synthesis.process_slot(&v);
289+ for s in &mut pcm {
290+ *s *= OUTPUT_SCALE;
291+ }
292+ iso_out[c].extend_from_slice(&pcm);
293+ }
294+ let _ = SB;
295+ }
296+ for (och, ochan) in iso_out.iter().enumerate() {
297+ for (rch, rplane) in [&ref_l, &ref_r].iter().enumerate() {
298+ let (lag, corr) = best_lag_correlation_wide(ochan, rplane, SEARCH_LAG_MAX);
299+ let name = if rch == 0 { "L" } else { "R" };
300+ println!("iso kx={kx} ch{och} vs ref {name}: lag={lag} corr={corr:.6}");
301+ }
302+ }
303+ }
304+}
305+
306+/// Full decode of one container-native AAC stream, WITHOUT `our_decode`'s
307+/// `MAX_SAMPLES` (~22.7s @44100) cap -- this probe needs the ~30s the
308+/// per-1s lag-drift table walks, and the sample-count comparison below
309+/// needs the true total the decoder produced, not a cap-truncated one.
310+/// Bounded only by `extract_from`'s existing 1_500-AU read cap.
311+pub(super) fn our_decode_uncapped(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32>>, u32, usize)> {
312+ let (asc, aus) = extract_aac_track(path, stream_index)?;
313+ let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?;
314+ let rate = decoder.output_sample_rate().unwrap_or(0);
315+ let mut planes: Vec<Vec<f32>> = Vec::new();
316+ for au in &aus {
317+ if let Ok(f) = decoder.decode(au, None) {
318+ let ch = usize::from(f.channels);
319+ if ch == 0 {
320+ continue;
321+ }
322+ if planes.is_empty() {
323+ planes = vec![Vec::new(); ch];
324+ }
325+ for (i, v) in f.samples.iter().enumerate() {
326+ planes[i % ch].push(*v);
327+ }
328+ }
329+ }
330+ if planes.is_empty() {
331+ return None;
332+ }
333+ Some((planes, rate, aus.len()))
334+}
335+
336+/// Total sample count of an unbounded ffmpeg decode of one container-native
337+/// AAC stream, interleaved-`f32` byte count / 4 -- i.e. `channels *
338+/// per_channel_samples`, not capped at 30s the way `ffmpeg_decode` is.
339+pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usize) -> u64 {
340+ let out = Command::new("ffmpeg")
341+ .args(["-v", "error", "-i"])
342+ .arg(path)
343+ .args([
344+ "-map",
345+ &format!("0:{absolute_stream}"),
346+ "-f",
347+ "f32le",
348+ "-acodec",
349+ "pcm_f32le",
350+ "-",
351+ ])
352+ .output()
353+ .expect("ffmpeg runs");
354+ assert!(
355+ out.status.success(),
356+ "ffmpeg full decode failed: {}",
357+ String::from_utf8_lossy(&out.stderr)
358+ );
359+ out.stdout.len() as u64 / 4
360+}
361+
362+/// `ffprobe -show_entries stream=<entry>` on the file's first audio stream,
363+/// trimmed. Used to cross-check the container's declared `sample_rate` and
364+/// `duration` against what our decoder derives and what ffmpeg actually
365+/// produces.
366+pub(super) fn ffprobe_field(path: &Path, entry: &str) -> String {
367+ let out = Command::new("ffprobe")
368+ .args([
369+ "-v",
370+ "error",
371+ "-select_streams",
372+ "a:0",
373+ "-show_entries",
374+ &format!("stream={entry}"),
375+ "-of",
376+ "default=nw=1:nk=1",
377+ ])
378+ .arg(path)
379+ .output()
380+ .expect("ffprobe runs");
381+ String::from_utf8_lossy(&out.stdout).trim().to_string()
382+}
383+
384+/// Narrow (`center +/- half`) fixed-window lag search anchored at ours-index
385+/// `oa0`, `len` samples long -- immune to the periodic-content aliasing that
386+/// makes `best_lag_correlation_ex`'s free ~100_000-wide coarse search
387+/// unreliable on this file (see the ledger dead-end on ref-L-vs-ref-R
388+/// itself mis-landing at lag=-24). `theirs`-index is `ours_index + lag`,
389+/// the same convention `best_lag_correlation_ex::slice_at` uses.
390+pub(super) fn narrow_lag_at(
391+ ours: &[f32],
392+ theirs: &[f32],
393+ oa0: usize,
394+ len: usize,
395+ center: i64,
396+ half: i64,
397+) -> (i64, f64) {
398+ let mut best = (center, -2.0f64);
399+ for lag in (center - half)..=(center + half) {
400+ let ob_i = oa0 as i64 + lag;
401+ if ob_i < 0 {
402+ continue;
403+ }
404+ let (oa, ob) = (oa0, ob_i as usize);
405+ if oa + len > ours.len() || ob + len > theirs.len() {
406+ continue;
407+ }
408+ let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]);
409+ if c > best.1 {
410+ best = (lag, c);
411+ }
412+ }
413+ best
414+}
415+
416+/// Round-55 charter probe: is the `heaac_44100_48k.m4a` (44.1k-family HE-AAC)
417+/// lag-vs-time drift a sample-count mismatch between our decode and
418+/// ffmpeg's reference (dropped/duplicated AU somewhere in the chain), or a
419+/// rate-label bug (we call it 44100 but produce samples at another rate),
420+/// or per-AU apply_last/hold fallbacks accumulating skew? Runs the same
421+/// three measurements on one 48k-family HE-AAC fixture and on reeln
422+/// (real 44.1k HE-AAC) as controls that are known NOT to show the drift.
423+#[test]
424+pub(super) fn sbr441_family_sample_drift_probe() {
425+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
426+ if !have_ffmpeg() {
427+ eprintln!("SKIP: ffmpeg not on PATH");
428+ return;
429+ }
430+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
431+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
432+ let home = std::env::var("HOME").unwrap_or_default();
433+ // `synthetic` marks the rows served by the committed fixture library
434+ // (`scripts/aac-tables/make-heaac-fixtures.sh`); the reeln control is
435+ // a `~/Music` host corpus and keeps its plain skip.
436+ let cases: [(&str, PathBuf, i64, bool); 3] = [
437+ (
438+ "heaac_44100_48k (FAIL family)",
439+ PathBuf::from(&dir).join("heaac_44100_48k.m4a"),
440+ -4674,
441+ true,
442+ ),
443+ (
444+ "heaac_48000_48k (48k control)",
445+ PathBuf::from(&dir).join("heaac_48000_48k.m4a"),
446+ // corrected via this test's own wide free-search cross-check
447+ // (below) -- 0 was a bad guess, true fixed lag is -4673, same
448+ // as the failing family's.
449+ -4673,
450+ true,
451+ ),
452+ (
453+ "reeln (44.1k control)",
454+ PathBuf::from(format!("{home}/Music/reeln.mp4")),
455+ // corrected via this test's own wide free-search cross-check
456+ // (below) -- -576 was this file's CORE-vs-FULL-chain delay
457+ // from an earlier probe, not its full-chain-vs-ffmpeg-reference
458+ // lag, which is +385.
459+ 385,
460+ false,
461+ ),
462+ ];
463+ for (label, path, seed_lag, synthetic) in cases {
464+ println!("\n=== {label}: {} ===", path.display());
465+ if synthetic {
466+ if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
467+ continue;
468+ }
469+ } else if !path.exists() {
470+ eprintln!("SKIP {label}: {} absent", path.display());
471+ continue;
472+ }
473+ let holds_before = ec_aac::hold_call_count();
474+ let Some((ours, out_rate, au_count)) = our_decode_uncapped(&path, 0) else {
475+ eprintln!("SKIP {label}: our_decode_uncapped failed");
476+ continue;
477+ };
478+ // `ffmpeg_decode_pan_channel` caps at 10s (per its own charter,
479+ // shared with `reelq_multichannel_lc_matches_reference`);
480+ // this probe walks out to t=29s, so it needs `ffmpeg_decode`'s 30s
481+ // cap instead -- planar channel 0 is L for every stereo case here.
482+ let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0);
483+ let ch0 = &ours[0];
484+ // Cross-check the hardcoded `seed_lag` guess with a free wide
485+ // search before trusting the narrow window around it -- a wrong
486+ // seed on a control file reads as near-zero correlation
487+ // everywhere, indistinguishable from "no signal", not "no drift".
488+ {
489+ let (wlag, wcorr) = best_lag_correlation_wide(ch0, &ref_l, SEARCH_LAG_MAX);
490+ println!(" (wide free-search cross-check: lag={wlag} corr={wcorr:.6})");
491+ }
492+
493+ // (1) per-1s narrow lag search, +/-128 around the file's known
494+ // (or, for the controls, assumed-near-zero) fixed lag.
495+ println!("-- lag(t), narrow +/-128 window around seed lag {seed_lag} --");
496+ let mut lag_points: Vec<(f64, f64)> = Vec::new();
497+ let step = out_rate.max(1) as usize;
498+ for t in 0..30usize {
499+ let oa0 = t * step;
500+ if oa0 + step > ch0.len() {
501+ break;
502+ }
503+ let (lag, corr) = narrow_lag_at(ch0, &ref_l, oa0, step, seed_lag, 128);
504+ println!(" t={t:>2}s lag={lag:>7} corr={corr:.6}");
505+ lag_points.push((t as f64, lag as f64));
506+ }
507+ if lag_points.len() >= 2 {
508+ let n = lag_points.len() as f64;
509+ let sx: f64 = lag_points.iter().map(|(x, _)| x).sum();
510+ let sy: f64 = lag_points.iter().map(|(_, y)| y).sum();
511+ let sxy: f64 = lag_points.iter().map(|(x, y)| x * y).sum();
512+ let sxx: f64 = lag_points.iter().map(|(x, _)| x * x).sum();
513+ let slope = (n * sxy - sx * sy) / (n * sxx - sx * sx);
514+ println!(" fitted slope = {slope:.4} samples/second");
515+ }
516+
517+ // (2) total sample count per channel: ours vs ffmpeg vs ffprobe
518+ // duration*rate vs AU-count*2048.
519+ let our_total = ch0.len() as u64;
520+ let ffmpeg_total = ffmpeg_total_interleaved_samples(&path, 0) / 2; // stereo
521+ let ffprobe_duration: f64 = ffprobe_field(&path, "duration").parse().unwrap_or(0.0);
522+ let ffprobe_rate: f64 = ffprobe_field(&path, "sample_rate").parse().unwrap_or(0.0);
523+ let ffprobe_total = (ffprobe_duration * ffprobe_rate).round() as u64;
524+ let au_implied_total = au_count as u64 * 2048;
525+ println!(
526+ "-- sample counts (per channel): ours={our_total} ffmpeg={ffmpeg_total} \
527+ ffprobe(duration*rate)={ffprobe_total} au_count*2048={au_implied_total} \
528+ (au_count={au_count}) our_decode_rate={out_rate} ffprobe_rate={ffprobe_rate} \
529+ ratio(ours/ffmpeg)={:.6}",
530+ our_total as f64 / ffmpeg_total.max(1) as f64
531+ );
532+
533+ // (4) apply_last/hold fallback count for this file's own decode
534+ // (process-wide counter, delta'd against this file's own before/
535+ // after since the test loop shares one process).
536+ let holds = ec_aac::hold_call_count() - holds_before;
537+ println!("-- apply_last (hold) calls during this file's decode: {holds} of {au_count} AUs");
538+ }
539+}
540+
541+/// Round-56 charter probe: at the corr cliff `heaac_48000_64k.m4a` shows
542+/// once the synthetic sweep content reaches the SBR HF register (good
543+/// t=14s, bad t=18s/24s per the ledger lever), print per-band |X| (dB) and
544+/// ours-minus-reference phase for 8 consecutive QMF slots at each of the
545+/// three timestamps, reading both sides through
546+/// [`ec_aac::sbr_qmf::HfAnalysis`] via the existing `qmf_domain_spec` third
547+/// witness (ISO/IEC 14496-3 4.6.18.4 64-band analysis of each side's own
548+/// final PCM, band unit = `rate/128` Hz -- exactly the patch table's own
549+/// unit). Also prints the file's own patch table (ISO/IEC 14496-3
550+/// 4.6.18.6.3 `build_patches`) and an `EC_AAC_SBR_HF_BYPASS` A/B so a
551+/// "our HF actively hurts" vs "our HF is merely incomplete" verdict is
552+/// readable straight from the printed corr numbers.
553+#[test]
554+pub(super) fn sbr_hf_window_band_probe() {
555+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
556+ if !have_ffmpeg() {
557+ eprintln!("SKIP: ffmpeg not on PATH");
558+ return;
559+ }
560+ let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
561+ .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
562+ let path = PathBuf::from(&dir).join("heaac_48000_64k.m4a");
563+ if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
564+ return;
565+ }
566+ const LAG: i64 = -4673;
567+
568+ let Some((ours, out_rate, _au_count)) = our_decode_uncapped(&path, 0) else {
569+ eprintln!("SKIP: our_decode_uncapped failed");
570+ return;
571+ };
572+ let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0);
573+ let ch0 = &ours[0];
574+
575+ for t in [14usize, 18, 24] {
576+ let oa0 = t * out_rate as usize;
577+ if oa0 + out_rate as usize > ch0.len() {
578+ continue;
579+ }
580+ let (lag, corr) = narrow_lag_at(ch0, &ref_l, oa0, out_rate as usize, LAG, 32);
581+ let (wlag, wcorr) = narrow_lag_at(ch0, &ref_l, oa0, out_rate as usize, LAG, 8192);
582+ println!(
583+ "\n=== t={t}s narrow-lag corr={corr:.6} lag={lag} (wide +/-8192 search: lag={wlag} corr={wcorr:.6}) ==="
584+ );
585+ let ob0 = (oa0 as i64 + lag) as usize;
586+ // 8 QMF slots (512 samples) starting at this second's aligned position.
587+ const WIN: usize = 8 * 64;
588+ if oa0 + WIN > ch0.len() || ob0 + WIN > ref_l.len() {
589+ println!(" SKIP: window out of range");
590+ continue;
591+ }
592+ let (o_spec, t_spec, _sim) = qmf_domain_spec(&ch0[oa0..oa0 + WIN], &ref_l[ob0..ob0 + WIN]);
593+ for band in 14..48usize {
594+ let mut mags_o = Vec::new();
595+ let mut mags_t = Vec::new();
596+ let mut dphase_deg = Vec::new();
597+ for slot in 0..8 {
598+ let o = o_spec[band][slot];
599+ let r = t_spec[band][slot];
600+ let mo = (o.re * o.re + o.im * o.im).sqrt();
601+ let mr = (r.re * r.re + r.im * r.im).sqrt();
602+ mags_o.push(20.0 * (mo.max(1e-12)).log10());
603+ mags_t.push(20.0 * (mr.max(1e-12)).log10());
604+ if mo > 1e-6 && mr > 1e-6 {
605+ let d = (o.im.atan2(o.re) - r.im.atan2(r.re)).to_degrees();
606+ let d = ((d + 180.0).rem_euclid(360.0)) - 180.0;
607+ dphase_deg.push(d);
608+ } else {
609+ dphase_deg.push(f64::NAN);
610+ }
611+ }
612+ let mean_o: f64 = mags_o.iter().sum::<f64>() / 8.0;
613+ let mean_t: f64 = mags_t.iter().sum::<f64>() / 8.0;
614+ println!(
615+ " band{band:>3}: |ours|dB mean={mean_o:>7.2} |ref|dB mean={mean_t:>7.2} dphase(deg)={:?}",
616+ dphase_deg
617+ .iter()
618+ .map(|d| format!("{d:.0}"))
619+ .collect::<Vec<_>>()
620+ );
621+ }
622+ }
623+
624+ // HF-bypass A/B on the bad windows: does zeroing our HF raise or lower
625+ // corr against the reference in [18s,19s) and [24s,25s)?
626+ let bypass = {
627+ let _bypass = ec_aac::knobs::set_sbr_hf_bypass(Some(true));
628+ our_decode_uncapped(&path, 0)
629+ };
630+ if let Some((bp, bp_rate, _)) = bypass {
631+ let bch0 = &bp[0];
632+ for t in [14usize, 18, 24] {
633+ let oa0 = t * bp_rate as usize;
634+ if oa0 + bp_rate as usize > bch0.len() {
635+ continue;
636+ }
637+ let (lag, corr) = narrow_lag_at(bch0, &ref_l, oa0, bp_rate as usize, LAG, 32);
638+ println!(" t={t}s HF_BYPASS corr={corr:.6} lag={lag}");
639+ }
640+ } else {
641+ eprintln!("HF_BYPASS decode failed");
642+ }
643+
644+ // Patch table (ISO/IEC 14496-3 4.6.18.6.3), sideinfo-derived.
645+ {
646+ let _sideinfo = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
647+ let _ = our_decode_uncapped(&path, 0);
648+ }
649+ if let Some(row) = ec_aac::sbr_sideinfo_log().first() {
650+ println!(
651+ "\n-- patch table (first frame): kx={} k2={} patch widths={:?}",
652+ row.kx, row.k2, row.patch_lengths
653+ );
654+ }
655+}
656+
657+/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst
658+/// windows, with the output frame index) plus a complex-STFT per-band
659+/// correlation (Parseval: equals the time-domain corr restricted to that
660+/// band, so it needs no calibration) with an ours-vs-ours self-check column.
661+#[test]
662+pub(super) fn sbr_residual_locator() {
663+ let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
664+ if !have_ffmpeg() {
665+ return;
666+ }
667+ // lane-h264reallib: `unwrap_or_default()`, the shape this file's five
668+ // other HOME reads already use (:2710, :3426, :4109, :4182, :4575). A bare
669+ // `unwrap()` panicked on any host with no HOME -- a fleet runner -- which
670+ // is a red with no bearing on the decoder. The `path.exists()` guard below
671+ // already handles the absent-file case, so an empty HOME just makes the
672+ // fallback path relative-and-nonexistent and the test returns.
673+ let home = std::env::var("HOME").unwrap_or_default();
674+ // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other
675+ // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode).
676+ let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE")
677+ .map(PathBuf::from)
678+ .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4")));
679+ if !path.exists() {
680+ return;
681+ }
682+ let Some((ours, _, rate)) = our_decode(&path, 0) else {
683+ return;
684+ };
685+ let theirs = ffmpeg_decode(&path, 0, ours.len());
686+ const W: usize = 2048;
687+ const FFT_LEN: usize = 2048;
688+ const HOP: usize = 1024;
689+ let bins = FFT_LEN / 2 + 1;
690+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
691+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
692+ for ch in 0..ours.len() {
693+ let n = ours[ch].len().min(theirs[ch].len());
694+ let (o, t) = (&ours[ch][..n], &theirs[ch][..n]);
695+ let mut wins: Vec<(f64, usize)> = (0..n / W)
696+ .map(|w| {
697+ (
698+ correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]),
699+ w,
700+ )
701+ })
702+ .collect();
703+ wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
704+ println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]);
705+ let hops = (n - FFT_LEN) / HOP + 1;
706+ let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
707+ let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2
708+ let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
709+ for h in 0..hops {
710+ let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec();
711+ win.apply(&mut b);
712+ rfft.forward(&b, &mut spec);
713+ os.copy_from_slice(&spec);
714+ let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec();
715+ win.apply(&mut b);
716+ rfft.forward(&b, &mut spec);
717+ for k in 0..bins {
718+ let (a, c) = (os[k], spec[k]);
719+ acc[k][0] += f64::from(a.re * c.re + a.im * c.im);
720+ acc[k][1] += f64::from(a.norm_sqr());
721+ acc[k][2] += f64::from(c.norm_sqr());
722+ }
723+ }
724+ let hz = f64::from(rate) / FFT_LEN as f64;
725+ let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum();
726+ // With `EC_AAC_SBR_NOISE_FRACTION` set the decoder bookkeeps the
727+ // dequantized target per QMF band; print it next to the reference's
728+ // measured energy in the same band so a target-side (bitstream ->
729+ // E_orig) tilt separates from an adjust/synthesis-side one.
730+ if ch == 0 {
731+ let band_hz = f64::from(rate) / 128.0;
732+ for (band, sig, noi, out) in ec_aac::noise_fraction_table() {
733+ let (lo, hi) = (
734+ (band as f64 * band_hz / hz) as usize,
735+ ((band + 1) as f64 * band_hz / hz) as usize,
736+ );
737+ let pt: f64 = (lo..hi.min(bins)).map(|k| acc[k][2]).sum();
738+ let po: f64 = (lo..hi.min(bins)).map(|k| acc[k][1]).sum();
739+ println!(
740+ "TARGET band {band:>2} {:>6.0}Hz target {:.3e} realised/target {:.4} ref_pcm {:.3e} ours_pcm {:.3e} target/ref_pcm {:.3e}",
741+ band as f64 * band_hz,
742+ sig + noi,
743+ out / (sig + noi),
744+ pt,
745+ po,
746+ (sig + noi) / pt
747+ );
748+ }
749+ }
750+ // group into 250 Hz bands up to 8 kHz, then 1 kHz
751+ let mut edges: Vec<usize> = (0..=32)
752+ .map(|i| ((i as f64 * 250.0) / hz) as usize)
753+ .collect();
754+ edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize));
755+ for e in edges.windows(2) {
756+ let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0);
757+ for row in acc.iter().take(e[1].min(bins)).skip(e[0]) {
758+ c += row[0];
759+ po += row[1];
760+ pt += row[2];
761+ }
762+ println!(
763+ "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}",
764+ e[0] as f64 * hz,
765+ e[1] as f64 * hz,
766+ c / (po * pt).sqrt(),
767+ (po / pt).sqrt(),
768+ (po + pt) / tot
769+ );
770+ }
771+ }
772+}
crates/ec-aac/tests/sbr_real_library/helpers.rsadded+2185 -0

Diff too large; view file

@@ -0,0 +1,2185 @@
1+//! Shared analysis helpers for the SBR real-library probes.
2+
3+use super::*;
4+
5+pub(super) use crate::common::have_ffmpeg;
6+/// Fixture-presence probe for the generated HE-AAC matrix under
7+/// `<repo>/.cache/heaac-fixtures` (`scripts/aac-tables/make-heaac-fixtures.sh`).
8+/// Returns whether the fixture is present, but never silently: under
9+/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
10+/// and the script that regenerates it, so a host whose fixture library drifted
11+/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
12+/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
13+/// short-circuited because the probe ran first in a compound `if`).
14+///
15+/// Order is load-bearing: probe, assert, return. Never merge the probe into
16+/// the same `if` as the escape. The `~/Music` / `~/Downloads` / `~/Videos`
17+/// scans in this file are host corpora, not the committed fixture library, and
18+/// keep their plain skip.
19+pub(super) fn require_fixture(path: &Path, generator: &str) -> bool {
20+ let present = path.exists();
21+ assert!(
22+ present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
23+ "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
24+ path.display(),
25+ generator
26+ );
27+ if !present {
28+ eprintln!("SKIP: fixture {} absent", path.display());
29+ }
30+ present
31+}
32+
33+/// A film's audio track is hours long; the correlation only needs a bounded
34+/// window near the start, so both sides cap how much they ever decode.
35+pub(super) const MAX_SAMPLES: usize = 1_000_000;
36+
37+/// ffmpeg's decode of a file's given absolute stream index, as
38+/// planar-by-channel `f32`.
39+pub(super) fn ffmpeg_decode(path: &Path, absolute_stream: usize, channels: usize) -> Vec<Vec<f32>> {
40+ let out = Command::new("ffmpeg")
41+ .args(["-v", "error", "-i"])
42+ .arg(path)
43+ .args([
44+ "-map",
45+ &format!("0:{absolute_stream}"),
46+ "-t",
47+ "30",
48+ "-f",
49+ "f32le",
50+ "-acodec",
51+ "pcm_f32le",
52+ "-",
53+ ])
54+ .output()
55+ .expect("ffmpeg runs");
56+ assert!(
57+ out.status.success(),
58+ "ffmpeg decode failed: {}",
59+ String::from_utf8_lossy(&out.stderr)
60+ );
61+ let samples: Vec<f32> = out
62+ .stdout
63+ .as_chunks::<4>().0.iter()
64+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
65+ .collect();
66+ let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
67+ for (i, &v) in samples.iter().enumerate() {
68+ planes[i % channels].push(v);
69+ }
70+ planes
71+}
72+
73+/// One AAC stream pulled out of its container: the AudioSpecificConfig bytes
74+/// exactly as the container carried them, and its access units in decode
75+/// order. Whichever of `ec-mp4`/`ec-matroska` the file's header names does the
76+/// actual box/EBML walk -- this is a thin `Demuxer`-trait harness over them,
77+/// not a parser of its own.
78+pub(super) fn extract_aac_track(path: &Path, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
79+ let mut head = [0u8; 12];
80+ File::open(path).ok()?.read_exact(&mut head).ok()?;
81+ if ec_mp4::is_mp4(&head) {
82+ let f = File::open(path).ok()?;
83+ let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?;
84+ extract_from(&mut d, stream_index)
85+ } else if ec_matroska::is_matroska(&head) {
86+ let f = File::open(path).ok()?;
87+ let mut d = MatroskaDemuxer::new(BufReader::new(f)).ok()?;
88+ extract_from(&mut d, stream_index)
89+ } else {
90+ None
91+ }
92+}
93+
94+/// `stream_index` picks the Nth AAC stream the container lists, in listed
95+/// order -- a file can carry more than one audio track (FMJ's mkv has both an
96+/// LC 5.1 track and an HE-AAC stereo commentary track).
97+pub(super) fn extract_from(d: &mut dyn Demuxer, stream_index: usize) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
98+ let aac = d
99+ .streams()
100+ .iter()
101+ .filter(|s| s.params.codec == CodecId::Aac)
102+ .nth(stream_index)?;
103+ let idx = aac.index;
104+ let asc = aac.params.extradata.as_ref()?.to_vec();
105+ let mut aus = Vec::new();
106+ // A film's audio track is a couple thousand AAC access units for the
107+ // handful of seconds the correlation actually needs; capped here so the
108+ // packet walk does not have to read the whole multi-gigabyte video
109+ // stream past it just to reach `Eof`.
110+ while aus.len() < 1_500 {
111+ match d.next_packet() {
112+ Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()),
113+ Ok(_) => continue,
114+ Err(_) => break,
115+ }
116+ }
117+ Some((asc, aus))
118+}
119+
120+/// Our decode of one container-native AAC stream, through its real
121+/// AudioSpecificConfig, as planar-by-channel `f32`.
122+pub(super) fn our_decode(
123+ path: &Path,
124+ stream_index: usize,
125+) -> Option<(Vec<Vec<f32>>, ec_aac::SbrSupport, u32)> {
126+ let Some((asc, aus)) = extract_aac_track(path, stream_index) else {
127+ eprintln!(" extract_aac_track returned None");
128+ return None;
129+ };
130+ eprintln!(" asc={asc:02x?} aus={}", aus.len());
131+ let mut decoder = match AacDecoder::with_config_bytes(&asc) {
132+ Ok(d) => d,
133+ Err(e) => {
134+ eprintln!(" with_config_bytes failed: {e:?}");
135+ return None;
136+ }
137+ };
138+ let sbr = decoder.sbr_support();
139+ let rate = decoder.output_sample_rate().unwrap_or(0);
140+ let mut planes: Vec<Vec<f32>> = Vec::new();
141+ let mut failed = 0;
142+ let debug_failures = std::env::var("EC_AAC_SBR_AU_FAIL_DEBUG").as_deref() == Ok("1");
143+ for (au_idx, au) in aus.iter().enumerate() {
144+ let frame = match decoder.decode(au, None) {
145+ Ok(f) => f,
146+ Err(e) => {
147+ failed += 1;
148+ if debug_failures {
149+ let head: Vec<u8> = au.iter().take(16).copied().collect();
150+ eprintln!(
151+ " AU {au_idx} FAILED len={} err={e:?} head={head:02x?}",
152+ au.len()
153+ );
154+ }
155+ continue;
156+ }
157+ };
158+ let ch = usize::from(frame.channels);
159+ if ch == 0 {
160+ continue;
161+ }
162+ if planes.is_empty() {
163+ planes = vec![Vec::new(); ch];
164+ }
165+ for (i, v) in frame.samples.iter().enumerate() {
166+ planes[i % ch].push(*v);
167+ }
168+ if planes[0].len() >= MAX_SAMPLES {
169+ break;
170+ }
171+ }
172+ if failed > 0 {
173+ eprintln!(" {failed}/{} access units failed to decode", aus.len());
174+ }
175+ if planes.is_empty() {
176+ eprintln!(" no channels decoded");
177+ return None;
178+ }
179+ Some((planes, sbr, rate))
180+}
181+
182+/// Search window bound: keeps the correlation sum bounded, per the charter
183+/// -- an unbounded version over a whole film's worth of samples was too slow
184+/// to be an every-run test.
185+pub(super) const WINDOW: usize = 200_000;
186+
187+/// Wide lag search bound for the specific gate proven to need it
188+/// (`sbr_real_library_matches_reference`, ours-vs-reference across a real
189+/// container's remux/priming delay). Measured (round-54 wide-lag probe,
190+/// worktree sbr-per-au) FMJ's true full-chain delay vs the reference is
191+/// ~22,913 samples @48kHz -- that gate's old `LAG_MAX=4_000` search clipped
192+/// at its own edge and silently reported the edge's noise as the answer for
193+/// 50+ rounds (class: "an alignment instrument whose result sits at its own
194+/// search edge is invalid"). 100_000 covers that with 4x headroom and is
195+/// already the bound round-53's own `WIDE_LAG_MAX=100_000` probe used to
196+/// find it. NOT used as the default everywhere: a wider bound also widens
197+/// the coarse pass's exposure to spurious short-slice noise peaks, so
198+/// call sites whose true delay is known-small (container/decoder priming,
199+/// ours-vs-own-core self-consistency) keep their original, narrower bound
200+/// -- round-54 first tried blanket-widening every call site to this value
201+/// and it flipped `full_chain_low_band_matches_own_core` and the LC control
202+/// row of `synthetic_heaac_matrix` from a correct small-lag answer to a
203+/// wrong, noise-driven distant one, still comfortably inside the bound
204+/// (not `at_edge`) but wrong regardless.
205+pub(super) const SEARCH_LAG_MAX: i64 = 100_000;
206+/// Original bound for the plain `best_lag_correlation` wrapper, used by the
207+/// file's other (ours-vs-reference small-priming-delay, or ours-vs-ours)
208+/// callers that were never shown to need more.
209+pub(super) const PLAIN_LAG_MAX: i64 = 4_000;
210+/// Odd stride `best_lag_correlation_ex`'s coarse pass steps by, so it
211+/// doesn't alias against frame-length periodicity.
212+pub(super) const SEARCH_STRIDE: i64 = 11;
213+
214+pub(super) fn dot(a: &[f32], b: &[f32]) -> f64 {
215+ a.iter()
216+ .zip(b)
217+ .map(|(x, y)| f64::from(*x) * f64::from(*y))
218+ .sum()
219+}
220+
221+pub(super) fn correlation(a: &[f32], b: &[f32]) -> f64 {
222+ let n = a.len().min(b.len());
223+ if n < 1024 {
224+ return 0.0;
225+ }
226+ let (a, b) = (&a[..n], &b[..n]);
227+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
228+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
229+ let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect();
230+ let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect();
231+ let num = dot(&ac, &bc);
232+ let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt();
233+ if den == 0.0 { 0.0 } else { num / den }
234+}
235+
236+/// Best correlation over a bounded lag search, PLUS whether the winning lag
237+/// sits at the search's own edge -- the single instrument every asserting
238+/// test in this file now routes through (class fix, round-54: a search that
239+/// silently clips at its bound and reports the edge's noise as "the
240+/// answer" is not an instrument, it's a lie). Two passes keep the whole
241+/// search O(reasonable) even at `SEARCH_LAG_MAX`-sized bounds on a
242+/// film-length file: an odd-`SEARCH_STRIDE` coarse pass over a short slice
243+/// finds roughly where the alignment is (the stride, not full 1-by-1
244+/// stepping, is what keeps a `lag_max` in the tens of thousands cheap, and
245+/// also avoids aliasing against frame-length periodicity), then one
246+/// full-`WINDOW` correlation at that lag (and its immediate neighbours, in
247+/// case the coarse slice picked a noisy lag) gives the reported number.
248+pub(super) fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) {
249+ const COARSE: usize = 4_096;
250+ let start = ours
251+ .len()
252+ .min(theirs.len())
253+ .saturating_sub(WINDOW)
254+ .min(ours.len() / 4);
255+ let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
256+ let (oa, ob) = if lag >= 0 {
257+ (start, start + lag as usize)
258+ } else {
259+ (start + (-lag) as usize, start)
260+ };
261+ if oa + len > ours.len() || ob + len > theirs.len() {
262+ None
263+ } else {
264+ Some((oa, ob))
265+ }
266+ };
267+ // The winning lag is the one that maximizes |correlation|, not signed
268+ // correlation: a channel that is a pure phase/sign inversion of the
269+ // reference reads strongly NEGATIVE at its true alignment lag, and a
270+ // signed-max search rejects that lag for whatever unrelated lag gives a
271+ // merely positive value -- reporting a real inversion as near-zero
272+ // noise. `found` (not "best abs value >= 0", which every real
273+ // correlation already satisfies) is what actually distinguishes "no
274+ // in-bounds lag existed" from "the best in-bounds lag was negative" --
275+ // an earlier version used `best.1 < 0.0` for that check, which treats
276+ // every genuinely negative (inverted) result as "not found" and falls
277+ // back to the COARSE, `COARSE`-sample-window-only candidate instead;
278+ // that coarse window is short enough to spuriously correlate at 0.87 on
279+ // real audio, so the fallback was silently replacing an honest,
280+ // correctly-refined negative full-`WINDOW` result with a noise-driven
281+ // positive one from a 20x-shorter slice. Carry the signed value through
282+ // so callers can see the sign, not just |corr|.
283+ // Stride 1, not `SEARCH_STRIDE` (round-61): a real correlation peak
284+ // between two decodes of the same audio is often ONE sample wide (on
285+ // reeln's core-only PCM: 0.9998 at lag 481, 0.94 at 479), so a
286+ // strided grid samples only the noise floor around it and the "best
287+ // coarse lag" it hands the refine pass is arbitrary. That is how a
288+ // 0.9998 match printed as corr 0.408 at lag -52. Stride 1 over the
289+ // narrow bound is ~33M multiply-adds; the wide bound is 25x that and
290+ // only runs on escalation, so this is not worth a resolution trade.
291+ let mut coarse_best = (0i64, -1.0f64, 0.0f64);
292+ for lag in -lag_max..=lag_max {
293+ if let Some((oa, ob)) = slice_at(lag, COARSE) {
294+ let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
295+ if c.abs() > coarse_best.1 {
296+ coarse_best = (lag, c.abs(), c);
297+ }
298+ }
299+ }
300+ let at_edge = coarse_best.0.abs() >= lag_max - SEARCH_STRIDE;
301+ let mut best = (coarse_best.0, -1.0f64, 0.0f64);
302+ let mut found = false;
303+ for lag in (coarse_best.0 - 2 * SEARCH_STRIDE)..=(coarse_best.0 + 2 * SEARCH_STRIDE) {
304+ let Some((oa, ob)) = slice_at(lag, WINDOW) else {
305+ continue;
306+ };
307+ let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
308+ if n < 1024 {
309+ continue;
310+ }
311+ let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]);
312+ if c.abs() > best.1 {
313+ best = (lag, c.abs(), c);
314+ }
315+ found = true;
316+ }
317+ if !found {
318+ best = coarse_best;
319+ }
320+ // A winning lag at the search bound is not a measurement (the true
321+ // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if
322+ // it still sits at the edge fail here rather than hand any caller a
323+ // noise-driven number (instrument-at-bound class).
324+ if at_edge && lag_max < SEARCH_LAG_MAX {
325+ return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX);
326+ }
327+ assert!(
328+ !at_edge,
329+ "winning lag {} sits at the +/-{lag_max} search bound -- the true \
330+ alignment is outside the search, corr {:.6} is noise, not a measurement",
331+ best.0, best.2
332+ );
333+ (best.0, best.2, at_edge)
334+}
335+
336+/// Thin wrapper over `best_lag_correlation_ex` at `PLAIN_LAG_MAX`, for the
337+/// many non-asserting call sites that only want `(lag, corr)` and whose true
338+/// delay was never shown to exceed the original 4_000 bound. The one gate
339+/// proven to need the wide bound (`sbr_real_library_matches_reference`)
340+/// calls `_ex` directly with `SEARCH_LAG_MAX` instead of going through this
341+/// wrapper.
342+pub(super) fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
343+ let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, PLAIN_LAG_MAX);
344+ (lag, corr)
345+}
346+
347+/// Thin wrapper over `best_lag_correlation_ex` at a caller-supplied bound,
348+/// for non-asserting call sites (asserting ones use `_ex` directly).
349+pub(super) fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) {
350+ let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, lag_max);
351+ (lag, corr)
352+}
353+
354+/// The robust two-stage lag search `sbr441_family_sample_drift_probe` proved
355+/// out (round-55/56): a plain coarse-stride search picks the SINGLE best
356+/// `COARSE`-sample-window candidate, which on periodic/tonal real music
357+/// content routinely aliases onto a wrong lag (this file family's ref-L-vs-
358+/// ref-R self-check scored a coarse-search lag=-24 corr=0.213, worse than
359+/// the true fixed-lag comparison's 0.873). Instead of trusting the single
360+/// coarse winner, keep the top `K` coarse candidates and refine EACH with a
361+/// full-resolution, narrow (+/-128) search restricted to the file's first
362+/// 10 seconds (`sample_rate`-derived) -- periodic aliasing needs many
363+/// seconds of a repeating pattern to fool a full-resolution window, so the
364+/// candidate that is genuinely aligned wins there even when it wasn't the
365+/// coarse pass's top pick. Returns `(lag, corr, at_edge)` for the winning
366+/// refined candidate, `at_edge` inherited from that candidate's own coarse
367+/// Stride-1 lag search: correlates a `COARSE`-sized window at EVERY lag in
368+/// `+/-lag_max`, then refines the winner with a full `WINDOW`.
369+///
370+/// `robust_lag_topk`'s coarse pass steps by `SEARCH_STRIDE` (11) and then
371+/// refines only its top-K coarse scorers. That ranking is meaningless when
372+/// the true peak is narrower than the stride: on reeln's core-only PCM
373+/// the correlation is 0.9998 at lag 481 and already 0.94 at 479, so no
374+/// stride-11 grid point (the grid is 4 mod 11; 481 is 8 mod 11) scores
375+/// anything but noise, the top-K is drawn from noise, and the search
376+/// returned lag -52 corr 0.408 for a pair that is actually a 0.9998 match.
377+/// FMJ, same instrument, same true lag 481, happened to land a noise-ranked
378+/// candidate within the +/-128 refine window and read correctly -- the
379+/// failure is luck-dependent, not file-dependent. Stride 1 over a 4_096
380+/// window is ~33M multiply-adds at `PLAIN_LAG_MAX`, cheaper than the top-K
381+/// refinement it replaces, so the resolution is simply not worth trading.
382+pub(super) fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) {
383+ const COARSE: usize = 4_096;
384+ let start = ours
385+ .len()
386+ .min(theirs.len())
387+ .saturating_sub(WINDOW)
388+ .min(ours.len() / 4);
389+ let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
390+ let (oa, ob) = if lag >= 0 {
391+ (start, start + lag as usize)
392+ } else {
393+ (start + (-lag) as usize, start)
394+ };
395+ if oa + len > ours.len() || ob + len > theirs.len() {
396+ None
397+ } else {
398+ Some((oa, ob))
399+ }
400+ };
401+ let mut best = (0i64, -1.0f64);
402+ for lag in -lag_max..=lag_max {
403+ if let Some((oa, ob)) = slice_at(lag, COARSE) {
404+ let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs();
405+ if c > best.1 {
406+ best = (lag, c);
407+ }
408+ }
409+ }
410+ let at_edge = best.0.abs() >= lag_max - 1;
411+ let mut refined = (best.0, -1.0f64);
412+ for lag in (best.0 - 2)..=(best.0 + 2) {
413+ let Some((oa, ob)) = slice_at(lag, WINDOW) else {
414+ continue;
415+ };
416+ let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
417+ if n < 1024 {
418+ continue;
419+ }
420+ let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]).abs();
421+ if c > refined.1 {
422+ refined = (lag, c);
423+ }
424+ }
425+ if refined.1 < 0.0 {
426+ refined = best;
427+ }
428+ (refined.0, refined.1, at_edge)
429+}
430+
431+/// bucket (true if ITS coarse lag sat at the +/-`lag_max` search bound).
432+pub(super) fn robust_lag_topk(
433+ ours: &[f32],
434+ theirs: &[f32],
435+ lag_max: i64,
436+ rate: u32,
437+ k: usize,
438+) -> (i64, f64, bool) {
439+ const COARSE: usize = 4_096;
440+ let start = ours
441+ .len()
442+ .min(theirs.len())
443+ .saturating_sub(WINDOW)
444+ .min(ours.len() / 4);
445+ let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
446+ let (oa, ob) = if lag >= 0 {
447+ (start, start + lag as usize)
448+ } else {
449+ (start + (-lag) as usize, start)
450+ };
451+ if oa + len > ours.len() || ob + len > theirs.len() {
452+ None
453+ } else {
454+ Some((oa, ob))
455+ }
456+ };
457+ // Stride 1 (round-61), for the reason spelled out on
458+ // `exhaustive_lag_correlation`: a strided grid can miss a 1-sample-wide
459+ // peak entirely, and then the top-K is a ranking of noise.
460+ let mut coarse: Vec<(i64, f64)> = Vec::new();
461+ for lag in -lag_max..=lag_max {
462+ if let Some((oa, ob)) = slice_at(lag, COARSE) {
463+ let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
464+ coarse.push((lag, c.abs()));
465+ }
466+ }
467+ coarse.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
468+ let ten_s = 10 * rate.max(1) as usize;
469+ let mut best: (i64, f64, bool) = (0, -2.0, false);
470+ for &(cand_lag, _) in coarse.iter().take(k) {
471+ let at_edge = cand_lag.abs() >= lag_max - SEARCH_STRIDE;
472+ // `narrow_lag_at` computes `ob_i = oa0 + lag` directly (no sign
473+ // split the way `slice_at` above does), so a fixed `oa0 = 0` goes
474+ // negative -- and every lag in the whole +/-128 window skips --
475+ // whenever `cand_lag` is negative enough (this file family's true
476+ // lag is -4674). Shift the window's start so it stays anchored to
477+ // "the first 10s of real content" while guaranteeing `ob_i >= 0`
478+ // even at the most-negative lag in the +/-128 refine range.
479+ let oa0 = (128 - cand_lag).max(0) as usize;
480+ let refine_len = ten_s.min(ours.len().saturating_sub(oa0)).min(
481+ theirs
482+ .len()
483+ .saturating_sub((oa0 as i64 + cand_lag).max(0) as usize),
484+ );
485+ if refine_len < 1024 {
486+ continue;
487+ }
488+ let (rlag, rcorr) = narrow_lag_at(ours, theirs, oa0, refine_len, cand_lag, 128);
489+ if rcorr > best.1 {
490+ best = (rlag, rcorr, at_edge);
491+ }
492+ }
493+ best
494+}
495+
496+/// Signed correlation of `ours` against `theirs` at one fixed `lag`, full
497+/// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation`
498+/// uses internally -- used to test a hypothesized sign inversion by reusing
499+/// a KNOWN-good lag (and window) from a healthy channel instead of trusting
500+/// the (signed, positive-biased) search above to relocate both for a
501+/// channel that may be exactly inverted at that same lag. Anchoring must
502+/// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows
503+/// otherwise cover different seconds of audio and are not comparable.
504+pub(super) fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 {
505+ let start = ours
506+ .len()
507+ .min(theirs.len())
508+ .saturating_sub(WINDOW)
509+ .min(ours.len() / 4);
510+ let (oa, ob) = if lag >= 0 {
511+ (start, start + lag as usize)
512+ } else {
513+ (start + (-lag) as usize, start)
514+ };
515+ let n = WINDOW
516+ .min(ours.len().saturating_sub(oa))
517+ .min(theirs.len().saturating_sub(ob));
518+ if n < 1024 {
519+ return 0.0;
520+ }
521+ correlation(&ours[oa..oa + n], &theirs[ob..ob + n])
522+}
523+
524+/// A first-order RC low-pass, run forward then backward to cancel its own
525+/// phase shift, giving a clean low-band/high-band split without pulling in a
526+/// filter design dependency for a diagnostic.
527+pub(super) fn lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
528+ let dt = 1.0 / f64::from(rate);
529+ let rc = 1.0 / (2.0 * std::f64::consts::PI * cutoff_hz);
530+ let alpha = (dt / (rc + dt)) as f32;
531+ let mut fwd = Vec::with_capacity(samples.len());
532+ let mut y = 0.0f32;
533+ for &x in samples {
534+ y += alpha * (x - y);
535+ fwd.push(y);
536+ }
537+ let mut out = vec![0.0f32; fwd.len()];
538+ y = 0.0;
539+ for i in (0..fwd.len()).rev() {
540+ y += alpha * (fwd[i] - y);
541+ out[i] = y;
542+ }
543+ out
544+}
545+
546+pub(super) fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
547+ let low = lowpass(samples, rate, cutoff_hz);
548+ samples.iter().zip(&low).map(|(a, b)| a - b).collect()
549+}
550+
551+/// DIAGNOSTIC (round-13): cascades `lowpass` three times for a much sharper
552+/// stopband than the single first-order zero-phase filter the real
553+/// assertion uses -- checking whether the below-crossover bar is actually
554+/// being missed because of above-crossover energy leaking through the
555+/// gentle single-pass rolloff, not because the low band itself is wrong.
556+pub(super) fn sharp_lowpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> {
557+ let a = lowpass(samples, rate, cutoff_hz);
558+ let b = lowpass(&a, rate, cutoff_hz);
559+ lowpass(&b, rate, cutoff_hz)
560+}
561+
562+/// Decisive-experiment diagnostic: correlates consecutive short (`WIN`)
563+/// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g.
564+/// the winning full-file lag from `best_lag_correlation`), searching a small
565+/// local lag range per window. A per-frame continuity bug (dropped/duplicated
566+/// samples at access-unit boundaries) shows up as the winning local lag
567+/// DRIFTING linearly window to window; a bug that is not about concatenation
568+/// (wrong band mapping, spectral corruption) shows up as a roughly constant
569+/// lag with low/noisy correlation instead.
570+pub(super) fn windowed_lag_drift(
571+ o: &[f32],
572+ t: &[f32],
573+ oa: usize,
574+ ob: usize,
575+ windows: usize,
576+) -> Vec<(i64, f64)> {
577+ const WIN: usize = 4_096;
578+ const LOCAL_LAG: i64 = 2_000;
579+ let mut out = Vec::with_capacity(windows);
580+ for w in 0..windows {
581+ let base_o = oa + w * WIN;
582+ let base_t = ob + w * WIN;
583+ let mut best = (0i64, -1.0f64, 0.0f64);
584+ for lag in -LOCAL_LAG..=LOCAL_LAG {
585+ let ao = base_o as i64 + lag;
586+ if ao < 0 {
587+ continue;
588+ }
589+ let ao = ao as usize;
590+ if ao + WIN > o.len() || base_t + WIN > t.len() {
591+ continue;
592+ }
593+ let c = correlation(&o[ao..ao + WIN], &t[base_t..base_t + WIN]);
594+ if c.abs() > best.1 {
595+ best = (lag, c.abs(), c);
596+ }
597+ }
598+ out.push((best.0, best.2));
599+ }
600+ out
601+}
602+
603+/// DIAGNOSTIC (round-14, Task 2): per-QMF-band correlation over the
604+/// above-crossover region. No 64-band QMF Analysis exists standalone in this
605+/// crate, so this substitutes an STFT: magnitude-per-bin time series (one
606+/// value per hop) for `ours` and `theirs`, correlated bin by bin, then
607+/// averaged over the bins a QMF band of width `rate/128` Hz covers. A patch
608+/// boundary in `build_patches`' target ranges landing on a low-correlation
609+/// block convicts patch construction; an even spread across all HF bands
610+/// with the map otherwise right points at gain mapping instead.
611+/// Pearson correlation with no minimum-length floor -- `correlation`'s
612+/// 1024-sample floor exists for raw audio windows, not the much shorter
613+/// per-bin magnitude series this diagnostic correlates.
614+pub(super) fn magnitude_series_correlation(a: &[f32], b: &[f32]) -> f64 {
615+ let n = a.len().min(b.len());
616+ if n < 2 {
617+ return 0.0;
618+ }
619+ let (a, b) = (&a[..n], &b[..n]);
620+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
621+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
622+ let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect();
623+ let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect();
624+ let num = dot(&ac, &bc);
625+ let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt();
626+ if den == 0.0 { 0.0 } else { num / den }
627+}
628+
629+pub(super) fn per_band_correlation(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> {
630+ const FFT_LEN: usize = 2048;
631+ const HOP: usize = 1024;
632+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
633+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
634+ let bins = rfft.spectrum_len();
635+ let n = o.len().min(t.len());
636+ let hops = if n >= FFT_LEN {
637+ (n - FFT_LEN) / HOP + 1
638+ } else {
639+ 0
640+ };
641+ let mut o_mag = vec![Vec::with_capacity(hops); bins];
642+ let mut t_mag = vec![Vec::with_capacity(hops); bins];
643+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
644+ for (src, dst) in [(o, &mut o_mag), (t, &mut t_mag)] {
645+ for h in 0..hops {
646+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
647+ win.apply(&mut block);
648+ rfft.forward(&block, &mut spectrum);
649+ for (b, c) in spectrum.iter().enumerate() {
650+ dst[b].push(c.norm_sqr().sqrt());
651+ }
652+ }
653+ }
654+ // QMF band width is `core_rate/128` where `core_rate` is the core
655+ // decoder's own sample rate -- half the SBR extension/output rate for a
656+ // plain (2x) HE-AAC stream -- not `output_rate/128`: measured against
657+ // this file's own kx=14 crossover, the correlation break lands exactly
658+ // at 14*(rate/256) Hz (2412 Hz), not at 14*(rate/128).
659+ let band_hz = f64::from(rate) / 256.0;
660+ let bin_hz = f64::from(rate) / FFT_LEN as f64;
661+ let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
662+ let mut out = Vec::with_capacity(num_bands);
663+ for band in 0..num_bands {
664+ let lo = (band as f64 * band_hz / bin_hz).floor() as usize;
665+ let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins);
666+ if lo >= hi {
667+ continue;
668+ }
669+ // round-16: correlating bin-by-bin then averaging the |corr| values
670+ // was the bug -- a QMF band's bins share one slowly-varying envelope,
671+ // but a tiny (sub-Hz) frequency offset between our filterbank and the
672+ // reference's shifts energy between adjacent bins hop to hop, so each
673+ // bin's OWN magnitude series decorrelates even though the band's
674+ // total energy (what a QMF band's single subband signal actually
675+ // carries) tracks the reference closely. Summing the bins' magnitudes
676+ // into one band-energy series per side FIRST, then correlating that
677+ // single pair, is robust to that intra-band leakage the way the
678+ // per-bin version wasn't.
679+ let hops_here = o_mag[lo].len().min(t_mag[lo].len());
680+ let mut o_band = vec![0.0f32; hops_here];
681+ let mut t_band = vec![0.0f32; hops_here];
682+ for b in lo..hi {
683+ for h in 0..hops_here {
684+ o_band[h] += o_mag[b][h];
685+ t_band[h] += t_mag[b][h];
686+ }
687+ }
688+ let c = magnitude_series_correlation(&o_band, &t_band);
689+ if c.is_finite() {
690+ out.push((band as f64 * band_hz, c.abs(), band as f64));
691+ }
692+ }
693+ out
694+}
695+
696+/// Per-band PCM-domain lag search (round-15 candidate-A discriminator):
697+/// `per_band_correlation`'s magnitude series has one sample per 1024-sample
698+/// STFT `HOP`, far coarser than a single QMF slot (64 samples) -- a stage
699+/// delay of one or a few slots between our HF path and the reference's would
700+/// vanish into that hop bucket instead of showing up as a lag. This instead
701+/// bandpasses `o`/`t` to each HF QMF band (the same zero-phase RC
702+/// `highpass`/`lowpass` primitives the crossover split already uses) and
703+/// searches PCM-sample lag directly, coarse-then-refine like
704+/// `best_lag_correlation`, so a consistent nonzero peak lag (especially a
705+/// multiple of 64 samples) convicts a per-stage time-alignment bug; lags
706+/// clustered at/near zero exonerate it in favour of a patch-map or
707+/// gain-mapping bug instead. Bands below kx (already known clean from
708+/// `per_band_correlation`) are skipped -- only HF bands (14..) are searched.
709+///
710+/// CONVICTED (round-26, Task 1): `bandpass_offset_probe` correlated this same
711+/// `sharp_lowpass`/`sharp_highpass` cascade's band-k output against the
712+/// REFERENCE's band-(k+/-10) output for several HF `k` -- and the DOWNWARD
713+/// offset (band k-10, closer to the strongly-correlated below-crossover
714+/// content) read a HIGHER correlation than the nominal same-band pairing in
715+/// every HF band tried (e.g. band 34: same 0.937 vs -10 0.966). A filter
716+/// with real ~172Hz selectivity cannot produce that; a "sharp" 3x-cascaded
717+/// single-pole RC (~18dB/oct) at a 9kHz center still passes a wide swath
718+/// below its corner, so each "band k" reading here is really "everything up
719+/// to and including band k" -- cumulative correlation, dominated by the
720+/// genuinely-matching low band, which manufactures the smooth monotonic
721+/// decline earlier rounds chased. The reported LAG values are still valid
722+/// (a filter with no stopband selectivity still has a passband delay that
723+/// tracks the true alignment), but the reported per-band |corr| AMPLITUDE
724+/// here is NOT a trustworthy per-band figure -- use `per_band_phase`'s
725+/// cross-spectrum magnitude ratio (or the bin-level `bin_level_conviction`)
726+/// for that instead.
727+pub(super) fn per_band_lag_search(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, i64, f64)> {
728+ const LAG_MAX: i64 = 1_024;
729+ const COARSE_STEP: i64 = 8;
730+ const COARSE: usize = 4_096;
731+ const WIN: usize = 65_536;
732+ let band_hz = f64::from(rate) / 256.0;
733+ let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
734+ let n = o.len().min(t.len());
735+ let start = n.saturating_sub(WIN + LAG_MAX as usize).min(n / 4);
736+ let mut out = Vec::new();
737+ for band in 14..num_bands {
738+ let lo = (band as f64 * band_hz).max(1.0);
739+ let hi = ((band + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0);
740+ // A single-pole RC (the plain `highpass`/`lowpass` used for the
741+ // crossover split) has too gentle a rolloff to isolate a ~172Hz-wide
742+ // QMF band -- it leaks in the much stronger, well-correlated
743+ // below-crossover energy, which was confirmed here as a smooth,
744+ // frequency-monotonic false-high correlation with no matching cliff
745+ // in `per_band_correlation`'s FFT-bin version of the same bands.
746+ // `sharp_lowpass` (3x cascade, already used for the crossover-band
747+ // debug check) plus its highpass complement sharpens the stopband
748+ // enough that leakage from outside this one band stops dominating.
749+ let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> {
750+ s.iter()
751+ .zip(&sharp_lowpass(s, rate, cutoff))
752+ .map(|(a, b)| a - b)
753+ .collect::<Vec<f32>>()
754+ };
755+ let bp = |s: &[f32]| -> Vec<f32> { sharp_lowpass(&sharp_highpass(s, lo), rate, hi) };
756+ let ob = bp(o);
757+ let tb = bp(t);
758+ let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
759+ let (oa, ta) = if lag >= 0 {
760+ (start, start + lag as usize)
761+ } else {
762+ (start + (-lag) as usize, start)
763+ };
764+ if oa + len > ob.len() || ta + len > tb.len() {
765+ None
766+ } else {
767+ Some((oa, ta))
768+ }
769+ };
770+ let mut coarse = (0i64, -1.0f64, 0.0f64);
771+ let mut lag = -LAG_MAX;
772+ while lag <= LAG_MAX {
773+ if let Some((oa, ta)) = slice_at(lag, COARSE) {
774+ let c = correlation(&ob[oa..oa + COARSE], &tb[ta..ta + COARSE]);
775+ if c.abs() > coarse.1 {
776+ coarse = (lag, c.abs(), c);
777+ }
778+ }
779+ lag += COARSE_STEP;
780+ }
781+ let mut best = coarse;
782+ for lag in (coarse.0 - COARSE_STEP)..=(coarse.0 + COARSE_STEP) {
783+ if let Some((oa, ta)) = slice_at(lag, WIN) {
784+ let c = correlation(&ob[oa..oa + WIN], &tb[ta..ta + WIN]);
785+ if c.abs() > best.1 {
786+ best = (lag, c.abs(), c);
787+ }
788+ }
789+ }
790+ out.push((band as f64 * band_hz, best.0, best.2));
791+ }
792+ out
793+}
794+
795+/// DIAGNOSTIC (round-16, Task 2): per-band phase offset and magnitude
796+/// transfer between `o` and `t`, over the SAME aligned window
797+/// `per_band_correlation` uses. Reuses the STFT-and-coherent-band-sum
798+/// machinery `per_band_correlation` was just fixed to use (sum the complex
799+/// spectrum, not just its magnitude, across a band's bins first, so a
800+/// per-bin sub-band redistribution doesn't wash out a genuine per-band
801+/// phase relationship) but keeps the complex value: the cross-spectrum
802+/// `sum_h O_band(h) * conj(T_band(h))` accumulated over every hop gives one
803+/// phasor per band whose angle is the (hop-weighted) phase offset between
804+/// `o` and `t` in that band and whose radius, once normalized by each side's
805+/// own energy, gives the magnitude transfer ratio.
806+pub(super) fn per_band_phase(o: &[f32], t: &[f32], rate: u32) -> Vec<(f64, f64, f64)> {
807+ const FFT_LEN: usize = 2048;
808+ const HOP: usize = 1024;
809+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
810+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
811+ let bins = rfft.spectrum_len();
812+ let n = o.len().min(t.len());
813+ let hops = if n >= FFT_LEN {
814+ (n - FFT_LEN) / HOP + 1
815+ } else {
816+ 0
817+ };
818+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
819+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
820+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
821+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
822+ for h in 0..hops {
823+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
824+ win.apply(&mut block);
825+ rfft.forward(&block, &mut spectrum);
826+ for (b, c) in spectrum.iter().enumerate() {
827+ dst[b].push(*c);
828+ }
829+ }
830+ }
831+ let band_hz = f64::from(rate) / 256.0;
832+ let bin_hz = f64::from(rate) / FFT_LEN as f64;
833+ let num_bands = (f64::from(rate) / 2.0 / band_hz).ceil() as usize;
834+ let mut out = Vec::with_capacity(num_bands);
835+ for band in 0..num_bands {
836+ let lo = (band as f64 * band_hz / bin_hz).floor() as usize;
837+ let hi = (((band + 1) as f64 * band_hz / bin_hz).ceil() as usize).min(bins);
838+ if lo >= hi || hops == 0 {
839+ continue;
840+ }
841+ // Cross-spectrum accumulated PER BIN over hops, THEN summed across
842+ // the band's bins -- not the reverse. Complex-summing the band's
843+ // bins together at each hop first (as an earlier version of this
844+ // function did) mixes in `O_b * conj(T_b')` cross terms for every
845+ // b != b' pair once the per-hop products are formed; two adjacent
846+ // FFT bins carry unrelated instantaneous phase (they are different
847+ // frequencies), so those cross terms are pure noise that swamped the
848+ // real per-bin coherence and produced an incoherent, near-random
849+ // phase reading across exactly the HF bands `per_band_lag_search`'s
850+ // direct PCM correlation shows are highly correlated at lag 0/-1.
851+ let mut cross_re = 0.0f64;
852+ let mut cross_im = 0.0f64;
853+ let mut o_energy = 0.0f64;
854+ let mut t_energy = 0.0f64;
855+ for b in lo..hi {
856+ for h in 0..hops {
857+ let ob = o_spec[b][h];
858+ let tb = t_spec[b][h];
859+ let cross = ob * tb.conj();
860+ cross_re += f64::from(cross.re);
861+ cross_im += f64::from(cross.im);
862+ o_energy +=
863+ f64::from(ob.re) * f64::from(ob.re) + f64::from(ob.im) * f64::from(ob.im);
864+ t_energy +=
865+ f64::from(tb.re) * f64::from(tb.re) + f64::from(tb.im) * f64::from(tb.im);
866+ }
867+ }
868+ let phase = cross_im.atan2(cross_re);
869+ let mag_ratio = if t_energy > 0.0 {
870+ (o_energy / t_energy).sqrt()
871+ } else {
872+ 0.0
873+ };
874+ out.push((band as f64 * band_hz, phase, mag_ratio));
875+ }
876+ out
877+}
878+
879+/// Round-26, Task 1: convicts (or acquits) `per_band_lag_search`'s bandpass.
880+/// Applies the SAME 3x-cascaded RC bandpass that diagnostic uses to `o` at
881+/// band `band` and to `t` at band `band` (same-band control), `band+offset`
882+/// and `band-offset`. A single-pole cascade's stopband is gentle enough that
883+/// "band k" may really pass "everything below f_k" -- if so, `o`-band-k and
884+/// `t`-band-(k+offset) still both carry the same dominant low-band leakage
885+/// and read highly correlated even though their nominal passbands don't
886+/// overlap at all, which convicts the filter, not the content. Below the SBR
887+/// crossover, genuinely narrowband-matching content should decorrelate
888+/// quickly as `offset` grows; a HF band that does NOT decorrelate at
889+/// `offset` bands away is evidence the filter has no real selectivity there.
890+pub(super) fn bandpass_offset_probe(
891+ o: &[f32],
892+ t: &[f32],
893+ rate: u32,
894+ band: usize,
895+ offset: i64,
896+) -> (f64, f64, f64) {
897+ let band_hz = f64::from(rate) / 256.0;
898+ let bp_at = |s: &[f32], b: usize| -> Vec<f32> {
899+ let lo = (b as f64 * band_hz).max(1.0);
900+ let hi = ((b + 1) as f64 * band_hz).min(f64::from(rate) / 2.0 - 1.0);
901+ let sharp_highpass = |s: &[f32], cutoff: f64| -> Vec<f32> {
902+ s.iter()
903+ .zip(&sharp_lowpass(s, rate, cutoff))
904+ .map(|(a, b)| a - b)
905+ .collect::<Vec<f32>>()
906+ };
907+ sharp_lowpass(&sharp_highpass(s, lo), rate, hi)
908+ };
909+ let ob = bp_at(o, band);
910+ let same_corr = correlation(&ob, &bp_at(t, band));
911+ let hi_band = band as i64 + offset;
912+ let hi_corr = if hi_band >= 0 {
913+ correlation(&ob, &bp_at(t, hi_band as usize))
914+ } else {
915+ 0.0
916+ };
917+ let lo_band = band as i64 - offset;
918+ let lo_corr = if lo_band >= 0 {
919+ correlation(&ob, &bp_at(t, lo_band as usize))
920+ } else {
921+ 0.0
922+ };
923+ (same_corr, hi_corr, lo_corr)
924+}
925+
926+/// Round-26, Task 2: bin-level (no filter, no cross-band summing) comparison
927+/// of `o` against `t` in the most energetic HF SBR bands at/above `min_band`,
928+/// three ways: DIRECT (bin i vs bin i), MIRROR (bin i vs the band's bins in
929+/// REVERSED order -- the signature of a QMF band-orientation/parity flip
930+/// between our own-design synthesis and the reference's convention: energies
931+/// right, direct corr ~0, phase random, exactly what round-14/16 observed),
932+/// and SHIFT (the whole `BINS_PER_SBR_BAND`-bin band matched one band up or
933+/// down -- the signature of a `build_patches` source-mapping offset).
934+/// Coherence per bin pair is
935+/// `|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)` (in
936+/// [0,1]; 1 = perfectly phase+magnitude locked, ~0 = unrelated), accumulated
937+/// over the SAME aligned hops `per_band_phase` uses, then averaged over the
938+/// band's 8 bins. Bands are picked by OUR OWN energy (the "real" HF content),
939+/// not the reference's, so a genuinely-silent HF band can't crowd out an
940+/// energetic one just because it happens to sort first.
941+pub(super) fn bin_level_conviction(
942+ o: &[f32],
943+ t: &[f32],
944+ rate: u32,
945+ min_band: usize,
946+ top_n: usize,
947+) -> Vec<(f64, f64, f64, f64, f64, f64)> {
948+ const FFT_LEN: usize = 2048;
949+ const HOP: usize = 1024;
950+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
951+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
952+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
953+ let bins = rfft.spectrum_len();
954+ let n = o.len().min(t.len());
955+ let hops = if n >= FFT_LEN {
956+ (n - FFT_LEN) / HOP + 1
957+ } else {
958+ 0
959+ };
960+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
961+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
962+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
963+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
964+ for h in 0..hops {
965+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
966+ win.apply(&mut block);
967+ rfft.forward(&block, &mut spectrum);
968+ for (b, c) in spectrum.iter().enumerate() {
969+ dst[b].push(*c);
970+ }
971+ }
972+ }
973+ if hops == 0 {
974+ return Vec::new();
975+ }
976+ let band_hz = f64::from(rate) / 256.0;
977+ let num_bands = bins / BINS_PER_SBR_BAND;
978+ let coh = |ob: usize, tb: usize| -> f64 {
979+ if ob >= bins || tb >= bins {
980+ return 0.0;
981+ }
982+ let mut cross_re = 0.0f64;
983+ let mut cross_im = 0.0f64;
984+ let mut o_e = 0.0f64;
985+ let mut t_e = 0.0f64;
986+ for h in 0..hops {
987+ let oc = o_spec[ob][h];
988+ let tc = t_spec[tb][h];
989+ let cross = oc * tc.conj();
990+ cross_re += f64::from(cross.re);
991+ cross_im += f64::from(cross.im);
992+ o_e += f64::from(oc.norm_sqr());
993+ t_e += f64::from(tc.norm_sqr());
994+ }
995+ let den = (o_e * t_e).sqrt();
996+ if den > 0.0 {
997+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
998+ } else {
999+ 0.0
1000+ }
1001+ };
1002+ // Rank HF bands by OUR OWN energy, so the energetic-band handful is
1003+ // chosen by real content, not by whatever the reference happens to carry.
1004+ let mut ranked: Vec<(usize, f64)> = (min_band..num_bands)
1005+ .map(|band| {
1006+ let lo = band * BINS_PER_SBR_BAND;
1007+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1008+ let e: f64 = (lo..hi)
1009+ .flat_map(|b| o_spec[b].iter())
1010+ .map(|c| f64::from(c.norm_sqr()))
1011+ .sum();
1012+ (band, e)
1013+ })
1014+ .collect();
1015+ ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
1016+ let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect();
1017+ selected.sort_unstable();
1018+
1019+ let mut out = Vec::with_capacity(selected.len());
1020+ for band in selected {
1021+ let lo = band * BINS_PER_SBR_BAND;
1022+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1023+ if lo >= hi {
1024+ continue;
1025+ }
1026+ let mut energy = 0.0f64;
1027+ let mut direct = 0.0f64;
1028+ let mut mirror = 0.0f64;
1029+ let mut shift_up = 0.0f64;
1030+ let mut shift_down = 0.0f64;
1031+ let count = (hi - lo) as f64;
1032+ // `i` feeds several derived indices (mirror/shift math below), not a
1033+ // plain element access -- an iterator/enumerate rewrite would be
1034+ // less readable here, not more.
1035+ #[allow(clippy::needless_range_loop)]
1036+ for i in lo..hi {
1037+ energy += o_spec[i]
1038+ .iter()
1039+ .map(|c| f64::from(c.norm_sqr()))
1040+ .sum::<f64>();
1041+ direct += coh(i, i);
1042+ mirror += coh(i, hi + lo - 1 - i);
1043+ shift_up += coh(i, i + BINS_PER_SBR_BAND);
1044+ shift_down += if i >= BINS_PER_SBR_BAND {
1045+ coh(i, i - BINS_PER_SBR_BAND)
1046+ } else {
1047+ 0.0
1048+ };
1049+ }
1050+ out.push((
1051+ band as f64 * band_hz,
1052+ energy,
1053+ direct / count,
1054+ mirror / count,
1055+ shift_up / count,
1056+ shift_down / count,
1057+ ));
1058+ }
1059+ out
1060+}
1061+
1062+/// Round-38, Task 1: sweeps a constant HF-only sample-domain lag `k*64`
1063+/// (`k` in -8..=8; one QMF synthesis slot = 64 output samples) applied ONLY
1064+/// to `o`'s STFT read position, holding `t` fixed at the globally-aligned
1065+/// `ob` offset -- the low band (which drives the global `lag` this window is
1066+/// already re-sliced to via `oa`/`ob`) is never touched by this probe. Per
1067+/// bin, coherence is the SAME "direct" measure `bin_level_conviction` uses
1068+/// (`|sum_h O(h)*conj(T(h))| / sqrt(sum_h|O(h)|^2 * sum_h|T(h)|^2)`), then
1069+/// averaged uniformly over every bin in every HF SBR band from `min_band`
1070+/// upward (both parity regions together, not just the top-energy handful) --
1071+/// a clear peak at k != 0 convicts a constant reference-vs-ours HF alignment
1072+/// offset of that many QMF slots; a flat or zero-peaked curve refutes it.
1073+pub(super) fn hf_lag_sweep(
1074+ o: &[f32],
1075+ t: &[f32],
1076+ oa: usize,
1077+ ob: usize,
1078+ n: usize,
1079+ min_band: usize,
1080+) -> Vec<(i64, f64)> {
1081+ const FFT_LEN: usize = 2048;
1082+ const HOP: usize = 1024;
1083+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1084+ const MAX_K: i64 = 8;
1085+ const SLOT: i64 = 64;
1086+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1087+ let probe_bins = ec_dsp::RealFft::<f32>::new(FFT_LEN).spectrum_len();
1088+ let num_bands = probe_bins / BINS_PER_SBR_BAND;
1089+ let lo_bin = min_band * BINS_PER_SBR_BAND;
1090+ let hi_bin = (num_bands * BINS_PER_SBR_BAND).min(probe_bins);
1091+ if lo_bin >= hi_bin {
1092+ return Vec::new();
1093+ }
1094+ let hops = if n >= FFT_LEN {
1095+ (n - FFT_LEN) / HOP + 1
1096+ } else {
1097+ 0
1098+ };
1099+ if hops == 0 {
1100+ return Vec::new();
1101+ }
1102+ let spec_of = |s: &[f32], start: usize| -> Vec<Vec<ec_dsp::Complex<f32>>> {
1103+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1104+ let mut spec = vec![Vec::with_capacity(hops); probe_bins];
1105+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); probe_bins];
1106+ for h in 0..hops {
1107+ let mut block = s[start + h * HOP..start + h * HOP + FFT_LEN].to_vec();
1108+ win.apply(&mut block);
1109+ rfft.forward(&block, &mut spectrum);
1110+ for (b, c) in spectrum.iter().enumerate() {
1111+ spec[b].push(*c);
1112+ }
1113+ }
1114+ spec
1115+ };
1116+ let mut out = Vec::with_capacity((2 * MAX_K + 1) as usize);
1117+ for k in -MAX_K..=MAX_K {
1118+ let shift = k * SLOT;
1119+ // Prefer shifting `o`'s read start (the literal ask), but `o` has no
1120+ // samples before its own decode origin -- when the global alignment
1121+ // already pins `oa` at (or near) 0, negative `k` has nowhere to read
1122+ // from on that side. `coh(o[x], t[y])` only depends on `x - y`, so
1123+ // shifting `t`'s read start the OPPOSITE direction instead
1124+ // (`ob - shift`) tests the exact same relative offset and `t` (the
1125+ // reference, decoded in full) always has the room. Only actually
1126+ // falls back for `o`-boundary-starved `k`; the un-shifted `t` path
1127+ // above is untouched for every `k` that fits within `o`.
1128+ let (o_start, t_start) = {
1129+ let os = oa as i64 + shift;
1130+ if os >= 0 && os as usize + n <= o.len() {
1131+ (os as usize, ob)
1132+ } else {
1133+ let ts = ob as i64 - shift;
1134+ if ts >= 0 && ts as usize + n <= t.len() {
1135+ (oa, ts as usize)
1136+ } else {
1137+ continue;
1138+ }
1139+ }
1140+ };
1141+ let o_spec = spec_of(o, o_start);
1142+ let t_spec = spec_of(t, t_start);
1143+ let mut sum = 0.0f64;
1144+ let mut count = 0usize;
1145+ for b in lo_bin..hi_bin {
1146+ let mut cross_re = 0.0f64;
1147+ let mut cross_im = 0.0f64;
1148+ let mut o_e = 0.0f64;
1149+ let mut t_e = 0.0f64;
1150+ for h in 0..hops {
1151+ let oc = o_spec[b][h];
1152+ let tc = t_spec[b][h];
1153+ let cross = oc * tc.conj();
1154+ cross_re += f64::from(cross.re);
1155+ cross_im += f64::from(cross.im);
1156+ o_e += f64::from(oc.norm_sqr());
1157+ t_e += f64::from(tc.norm_sqr());
1158+ }
1159+ let den = (o_e * t_e).sqrt();
1160+ if den > 0.0 {
1161+ sum += (cross_re * cross_re + cross_im * cross_im).sqrt() / den;
1162+ count += 1;
1163+ }
1164+ }
1165+ out.push((k, if count > 0 { sum / count as f64 } else { 0.0 }));
1166+ }
1167+ out
1168+}
1169+
1170+/// Round-40, Task 1: fine spectral-BIN shift scan on patched HF content.
1171+/// `hf_lag_sweep` (round-38) only tested whole-QMF-slot SAMPLE-domain lags and
1172+/// round-26's `bin_level_conviction` shift columns only tested whole
1173+/// `BINS_PER_SBR_BAND` (8-bin) band shifts; neither ever tried a FEW-bin
1174+/// spectral offset, which is what a half-QMF-band (~4-bin, ~86Hz at this
1175+/// 2048-window scale) carrier convention mismatch on patched content would
1176+/// look like -- it would leave envelope/magnitude tracking (and therefore
1177+/// `hf_lag_sweep`'s k=0 peak) intact while destroying bin-level phase
1178+/// coherence via linear phase drift across the band. The audio itself is
1179+/// never shifted; only the bin INDEX used to pair `o` against `t` moves, by
1180+/// `b` in -7..=+7 (deliberately short of the 8-bin whole-band-shift case
1181+/// round-26 already ruled out). Reports mean direct coherence
1182+/// (`bin_level_conviction`'s same `|sum_h O(h)*conj(T(h))| /
1183+/// sqrt(sum|O|^2*sum|T|^2)` measure) separately over the even-gap [14,28) and
1184+/// odd-gap [28,43) SBR-band regions -- the offset, if real, could differ by
1185+/// patch parity given round-35/36's convention-fix history. A clear peak at
1186+/// `b != 0` (region-dependent sign allowed) convicts a constant sub-band
1187+/// frequency offset; a flat/0-peaked curve refutes it.
1188+pub(super) fn hf_bin_shift_sweep(
1189+ o: &[f32],
1190+ t: &[f32],
1191+ _rate: u32,
1192+ region_lo_band: usize,
1193+ region_hi_band: usize,
1194+) -> Vec<(i64, f64)> {
1195+ const FFT_LEN: usize = 2048;
1196+ const HOP: usize = 1024;
1197+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1198+ const MAX_B: i64 = 7;
1199+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1200+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1201+ let bins = rfft.spectrum_len();
1202+ let n = o.len().min(t.len());
1203+ let hops = if n >= FFT_LEN {
1204+ (n - FFT_LEN) / HOP + 1
1205+ } else {
1206+ 0
1207+ };
1208+ if hops == 0 {
1209+ return Vec::new();
1210+ }
1211+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
1212+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
1213+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1214+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1215+ for h in 0..hops {
1216+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1217+ win.apply(&mut block);
1218+ rfft.forward(&block, &mut spectrum);
1219+ for (b, c) in spectrum.iter().enumerate() {
1220+ dst[b].push(*c);
1221+ }
1222+ }
1223+ }
1224+ let lo_bin = region_lo_band * BINS_PER_SBR_BAND;
1225+ let hi_bin = (region_hi_band * BINS_PER_SBR_BAND).min(bins);
1226+ let coh = |ob: usize, tb: usize| -> f64 {
1227+ if ob >= bins || tb >= bins {
1228+ return 0.0;
1229+ }
1230+ let mut cross_re = 0.0f64;
1231+ let mut cross_im = 0.0f64;
1232+ let mut o_e = 0.0f64;
1233+ let mut t_e = 0.0f64;
1234+ for h in 0..hops {
1235+ let oc = o_spec[ob][h];
1236+ let tc = t_spec[tb][h];
1237+ let cross = oc * tc.conj();
1238+ cross_re += f64::from(cross.re);
1239+ cross_im += f64::from(cross.im);
1240+ o_e += f64::from(oc.norm_sqr());
1241+ t_e += f64::from(tc.norm_sqr());
1242+ }
1243+ let den = (o_e * t_e).sqrt();
1244+ if den > 0.0 {
1245+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1246+ } else {
1247+ 0.0
1248+ }
1249+ };
1250+ let mut out = Vec::with_capacity((2 * MAX_B + 1) as usize);
1251+ if lo_bin >= hi_bin {
1252+ return out;
1253+ }
1254+ for b in -MAX_B..=MAX_B {
1255+ let mut sum = 0.0f64;
1256+ let mut count = 0usize;
1257+ for i in lo_bin..hi_bin {
1258+ let oi = i as i64 + b;
1259+ if oi < 0 || oi as usize >= bins {
1260+ continue;
1261+ }
1262+ sum += coh(oi as usize, i);
1263+ count += 1;
1264+ }
1265+ out.push((b, if count > 0 { sum / count as f64 } else { 0.0 }));
1266+ }
1267+ out
1268+}
1269+
1270+/// Round-40, Task 2: per-STFT-frame complex-gain fingerprint. For the same
1271+/// top-energy HF bands `bin_level_conviction` picks (ranked by `o`'s own
1272+/// energy), takes each band's single dominant bin (highest total `|O(h)|^2`
1273+/// across hops) and reports the per-hop complex ratio `O(h)/T(h)` trajectory
1274+/// -- `(magnitude, phase_radians)` per STFT frame -- for that bin across
1275+/// every frame. Read afterward, not here: constant magnitude+phase is a pure
1276+/// gain (would predict HIGH coherence, contradicting the low bin-coherence
1277+/// measured elsewhere -- flags a measurement issue, not a real
1278+/// transformation); phase advancing at a roughly fixed per-frame rate is a
1279+/// genuine carrier frequency offset (the rate converts directly to Hz and
1280+/// cross-checks `hf_bin_shift_sweep`'s peak); phase jumping specifically at
1281+/// hop indices lining up with SBR envelope borders is a per-envelope
1282+/// gain/phase re-seed; anything else (magnitude and phase both wandering with
1283+/// no fixed rate) is genuinely uncorrelated content frame to frame.
1284+pub(super) fn hf_complex_ratio_trajectory(
1285+ o: &[f32],
1286+ t: &[f32],
1287+ rate: u32,
1288+ min_band: usize,
1289+ top_n: usize,
1290+) -> Vec<(f64, Vec<(f64, f64)>)> {
1291+ const FFT_LEN: usize = 2048;
1292+ const HOP: usize = 1024;
1293+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1294+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1295+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1296+ let bins = rfft.spectrum_len();
1297+ let n = o.len().min(t.len());
1298+ let hops = if n >= FFT_LEN {
1299+ (n - FFT_LEN) / HOP + 1
1300+ } else {
1301+ 0
1302+ };
1303+ if hops == 0 {
1304+ return Vec::new();
1305+ }
1306+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
1307+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
1308+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1309+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1310+ for h in 0..hops {
1311+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1312+ win.apply(&mut block);
1313+ rfft.forward(&block, &mut spectrum);
1314+ for (b, c) in spectrum.iter().enumerate() {
1315+ dst[b].push(*c);
1316+ }
1317+ }
1318+ }
1319+ let band_hz = f64::from(rate) / 256.0;
1320+ let num_bands = bins / BINS_PER_SBR_BAND;
1321+ if min_band >= num_bands {
1322+ return Vec::new();
1323+ }
1324+ let mut ranked: Vec<(usize, f64)> = (min_band..num_bands)
1325+ .map(|band| {
1326+ let lo = band * BINS_PER_SBR_BAND;
1327+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1328+ let e: f64 = (lo..hi)
1329+ .flat_map(|b| o_spec[b].iter())
1330+ .map(|c| f64::from(c.norm_sqr()))
1331+ .sum();
1332+ (band, e)
1333+ })
1334+ .collect();
1335+ ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
1336+ let mut selected: Vec<usize> = ranked.into_iter().take(top_n).map(|(b, _)| b).collect();
1337+ selected.sort_unstable();
1338+
1339+ let mut out = Vec::with_capacity(selected.len());
1340+ for band in selected {
1341+ let lo = band * BINS_PER_SBR_BAND;
1342+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1343+ if lo >= hi {
1344+ continue;
1345+ }
1346+ let dom = (lo..hi)
1347+ .max_by(|&a, &b| {
1348+ let ea: f64 = o_spec[a].iter().map(|c| f64::from(c.norm_sqr())).sum();
1349+ let eb: f64 = o_spec[b].iter().map(|c| f64::from(c.norm_sqr())).sum();
1350+ ea.partial_cmp(&eb).unwrap()
1351+ })
1352+ .unwrap();
1353+ // Complex division `O/T` done by hand (`ec_dsp::Complex` carries no
1354+ // `Div` impl -- it is a from-scratch minimal type, see fft.rs): `O *
1355+ // conj(T) / |T|^2`.
1356+ let traj: Vec<(f64, f64)> = (0..hops)
1357+ .map(|h| {
1358+ let oc = o_spec[dom][h];
1359+ let tc = t_spec[dom][h];
1360+ let t_e = f64::from(tc.norm_sqr());
1361+ if t_e > 1e-12 {
1362+ let (or, oi) = (f64::from(oc.re), f64::from(oc.im));
1363+ let (tr, ti) = (f64::from(tc.re), f64::from(tc.im));
1364+ let rr = (or * tr + oi * ti) / t_e;
1365+ let ri = (oi * tr - or * ti) / t_e;
1366+ ((rr * rr + ri * ri).sqrt(), ri.atan2(rr))
1367+ } else {
1368+ (0.0, 0.0)
1369+ }
1370+ })
1371+ .collect();
1372+ out.push((band as f64 * band_hz, traj));
1373+ }
1374+ out
1375+}
1376+
1377+/// Round-45, Task 3 THIRD WITNESS. Every prior round compared OURS against
1378+/// the REFERENCE directly -- a pairwise measurement that can never say which
1379+/// side is wrong when they disagree. This builds a reference-free model: a
1380+/// pure "plain patch-copy + per-band energy match" reconstruction of HF
1381+/// content from the REFERENCE's own LOW band (the one piece of ground truth
1382+/// both decoders start from and our own low-band round-trip already measures
1383+/// as near-identity), using the verified patch map
1384+/// `[(0,14,14),(3,28,11),(0,39,3),(13,42,1)]` and this file's own established
1385+/// `band_hz = rate/256`, `BINS_PER_SBR_BAND = FFT_LEN/256 = 8` convention
1386+/// (round-14/16; NOT the `rate/128` scale the naive spec reading suggests --
1387+/// that value indexes the QMF/hybrid analysis grid, not this STFT-bin grid,
1388+/// and using it here would be the "trap" that bit round-42 elsewhere in this
1389+/// file. The patch map's own band numbers (14/28/39/42/43) only make sense
1390+/// under the `/256` convention already used everywhere else in this file that
1391+/// touches the patch map -- confirmed by construction, not re-derived here).
1392+///
1393+/// For each HF band in `[14, 43)` and each STFT hop, the simulated bins are
1394+/// the REFERENCE's low-band bins at the patch-mapped source position, then
1395+/// RESCALED per (band, hop) to match the comparison side's own energy in
1396+/// that band/hop -- two separate rescalings, "sim-normalized-to-ours" and
1397+/// "sim-normalized-to-reference" -- so the only thing left for the
1398+/// coherence measure to see is phase/content structure, not a gain
1399+/// difference (the gain question is already closed by prior rounds). Returns
1400+/// `(band, coherence)` pairs for sim-vs-reference and sim-vs-ours.
1401+type BandCoherenceTable = Vec<(usize, f64)>;
1402+
1403+pub(super) fn hf_patch_simulator(o: &[f32], t: &[f32], rate: u32) -> (BandCoherenceTable, BandCoherenceTable) {
1404+ const FFT_LEN: usize = 2048;
1405+ const HOP: usize = 1024;
1406+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1407+ const PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1408+ let _ = rate; // band Hz not needed here; caller converts band index itself.
1409+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1410+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1411+ let bins = rfft.spectrum_len();
1412+ let n = o.len().min(t.len());
1413+ let hops = if n >= FFT_LEN {
1414+ (n - FFT_LEN) / HOP + 1
1415+ } else {
1416+ 0
1417+ };
1418+ if hops == 0 {
1419+ return (Vec::new(), Vec::new());
1420+ }
1421+ let mut o_spec = vec![Vec::with_capacity(hops); bins];
1422+ let mut t_spec = vec![Vec::with_capacity(hops); bins];
1423+ let mut spectrum = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1424+ for (src, dst) in [(o, &mut o_spec), (t, &mut t_spec)] {
1425+ for h in 0..hops {
1426+ let mut block = src[h * HOP..h * HOP + FFT_LEN].to_vec();
1427+ win.apply(&mut block);
1428+ rfft.forward(&block, &mut spectrum);
1429+ for (b, c) in spectrum.iter().enumerate() {
1430+ dst[b].push(*c);
1431+ }
1432+ }
1433+ }
1434+ // Plain patch copy: sim's target bins, per hop, are the reference's
1435+ // source bins, unmodified (no phase adjustment) -- modelling exactly the
1436+ // "plain patch+gain" hypothesis the charter names.
1437+ let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f32, 0.0); hops]; bins];
1438+ for (src, tgt, width) in PATCHES {
1439+ let src_lo = src * BINS_PER_SBR_BAND;
1440+ let tgt_lo = tgt * BINS_PER_SBR_BAND;
1441+ let len = width * BINS_PER_SBR_BAND;
1442+ for i in 0..len {
1443+ if src_lo + i >= bins || tgt_lo + i >= bins {
1444+ continue;
1445+ }
1446+ for h in 0..hops {
1447+ sim_spec[tgt_lo + i][h] = t_spec[src_lo + i][h];
1448+ }
1449+ }
1450+ }
1451+ let num_bands = bins / BINS_PER_SBR_BAND;
1452+ let top_band = 43.min(num_bands);
1453+ // Per (band, hop) rescale of `sim` to match `target`'s energy in that
1454+ // band/hop, then the same magnitude-of-summed-cross-spectrum coherence
1455+ // measure every prior round's `coh` helper uses (already scale-invariant
1456+ // to a CONSTANT gain across hops; this rescale additionally removes a
1457+ // gain that varies hop-to-hop, isolating phase/content agreement).
1458+ let band_coherence = |target: &[Vec<ec_dsp::Complex<f32>>]| -> Vec<(usize, f64)> {
1459+ (14..top_band)
1460+ .map(|band| {
1461+ let lo = band * BINS_PER_SBR_BAND;
1462+ let hi = (lo + BINS_PER_SBR_BAND).min(bins);
1463+ let mut cross_re = 0.0f64;
1464+ let mut cross_im = 0.0f64;
1465+ let mut sim_e = 0.0f64;
1466+ let mut tgt_e = 0.0f64;
1467+ for h in 0..hops {
1468+ let se: f64 = (lo..hi).map(|b| f64::from(sim_spec[b][h].norm_sqr())).sum();
1469+ let te: f64 = (lo..hi).map(|b| f64::from(target[b][h].norm_sqr())).sum();
1470+ if se <= 1e-20 || te <= 0.0 {
1471+ continue;
1472+ }
1473+ let scale = (te / se).sqrt() as f32;
1474+ for b in lo..hi {
1475+ let sc = sim_spec[b][h].scale(scale);
1476+ let tc = target[b][h];
1477+ let cross = sc * tc.conj();
1478+ cross_re += f64::from(cross.re);
1479+ cross_im += f64::from(cross.im);
1480+ sim_e += f64::from(sc.norm_sqr());
1481+ tgt_e += f64::from(tc.norm_sqr());
1482+ }
1483+ }
1484+ let den = (sim_e * tgt_e).sqrt();
1485+ let coh = if den > 0.0 {
1486+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1487+ } else {
1488+ 0.0
1489+ };
1490+ (band, coh)
1491+ })
1492+ .collect()
1493+ };
1494+ (band_coherence(&t_spec), band_coherence(&o_spec))
1495+}
1496+
1497+/// (Round-46) The QMF-domain exact version of [`hf_patch_simulator`]: same
1498+/// plain-patch+gain model, same verified patch map, but read through the
1499+/// crate's own [`ec_aac::sbr_qmf::HfAnalysis`] (64-band, `rate/128`-wide
1500+/// bands -- exactly the patch map's own band unit) instead of an 8-bin-wide
1501+/// STFT approximation, closing the "too crude to reach a verdict" gap
1502+/// round-45's STFT simulator hit. Validated by
1503+/// `hf_analysis_self_consistency_control` in `sbr_qmf.rs` before use here
1504+/// (own-band plurality + self-coherence + round-trip control). Same
1505+/// per-(band, window) energy-rescale-then-coherence method as the STFT
1506+/// version, windowed over `WIN` consecutive QMF slots (`WIN * SYNTHESIS_BANDS
1507+/// = 1024` samples, matching the STFT version's hop) so the rescale has
1508+/// enough samples to estimate energy from, not so many that within-window
1509+/// phase drift is averaged away.
1510+pub(super) const QMF_PATCHES: [(usize, usize, usize); 4] = [(0, 14, 14), (3, 28, 11), (0, 39, 3), (13, 42, 1)];
1511+
1512+/// Shared build step for the QMF-domain third-witness instruments: both
1513+/// PCMs read through [`ec_aac::sbr_qmf::HfAnalysis`], plus the plain
1514+/// patch-copy simulation of the reference's own low band, all in the
1515+/// `(band, slot)` domain. Returns `(ours, reference, sim)`.
1516+/// `[band][slot]` complex QMF-domain series.
1517+type QmfBandSlots = Vec<Vec<ec_dsp::Complex<f64>>>;
1518+
1519+pub(super) fn qmf_domain_spec(o: &[f32], t: &[f32]) -> (QmfBandSlots, QmfBandSlots, QmfBandSlots) {
1520+ use ec_aac::sbr_qmf::{HfAnalysis, SYNTHESIS_BANDS};
1521+ let n = o.len().min(t.len());
1522+ let slots = n / SYNTHESIS_BANDS;
1523+ let analyze = |pcm: &[f32]| -> QmfBandSlots {
1524+ let mut ana = HfAnalysis::new();
1525+ let mut out: QmfBandSlots = (0..SYNTHESIS_BANDS)
1526+ .map(|_| Vec::with_capacity(slots))
1527+ .collect();
1528+ for s in 0..slots {
1529+ let mut chunk = [0.0f32; SYNTHESIS_BANDS];
1530+ chunk.copy_from_slice(&pcm[s * SYNTHESIS_BANDS..(s + 1) * SYNTHESIS_BANDS]);
1531+ let sub = ana.process_slot(&chunk);
1532+ for (b, c) in sub.iter().enumerate() {
1533+ out[b].push(*c);
1534+ }
1535+ }
1536+ out
1537+ };
1538+ let o_spec = analyze(o);
1539+ let t_spec = analyze(t);
1540+ // Plain patch copy: sim's target-band slot series is the reference's
1541+ // source-band slot series, unmodified.
1542+ let mut sim_spec = vec![vec![ec_dsp::Complex::new(0.0f64, 0.0); slots]; SYNTHESIS_BANDS];
1543+ for (src, tgt, width) in QMF_PATCHES {
1544+ for i in 0..width {
1545+ if src + i >= SYNTHESIS_BANDS || tgt + i >= SYNTHESIS_BANDS {
1546+ continue;
1547+ }
1548+ sim_spec[tgt + i] = t_spec[src + i].clone();
1549+ }
1550+ }
1551+ (o_spec, t_spec, sim_spec)
1552+}
1553+
1554+/// Returns `(sim-vs-reference, sim-vs-ours, ours-vs-reference)` -- the last
1555+/// pairing (round-48, Task 4a) is the ultimate content-match witness: how
1556+/// well our actual HF QMF content agrees with the reference's, with no
1557+/// simulator in between.
1558+pub(super) fn hf_patch_simulator_qmf(
1559+ o: &[f32],
1560+ t: &[f32],
1561+) -> (BandCoherenceTable, BandCoherenceTable, BandCoherenceTable) {
1562+ use ec_aac::sbr_qmf::SYNTHESIS_BANDS;
1563+ const WIN: usize = 16;
1564+ let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1565+ let slots = sim_spec.first().map(Vec::len).unwrap_or(0);
1566+ if slots < WIN {
1567+ return (Vec::new(), Vec::new(), Vec::new());
1568+ }
1569+ let top_band = 43.min(SYNTHESIS_BANDS);
1570+ let windows = slots / WIN;
1571+ let band_coherence = |source: &[Vec<ec_dsp::Complex<f64>>],
1572+ target: &[Vec<ec_dsp::Complex<f64>>]|
1573+ -> Vec<(usize, f64)> {
1574+ (14..top_band)
1575+ .map(|band| {
1576+ let mut cross_re = 0.0f64;
1577+ let mut cross_im = 0.0f64;
1578+ let mut sim_e = 0.0f64;
1579+ let mut tgt_e = 0.0f64;
1580+ for w in 0..windows {
1581+ let lo = w * WIN;
1582+ let hi = lo + WIN;
1583+ let se: f64 = source[band][lo..hi]
1584+ .iter()
1585+ .map(|c| c.re * c.re + c.im * c.im)
1586+ .sum();
1587+ let te: f64 = target[band][lo..hi]
1588+ .iter()
1589+ .map(|c| c.re * c.re + c.im * c.im)
1590+ .sum();
1591+ if se <= 1e-20 || te <= 0.0 {
1592+ continue;
1593+ }
1594+ let scale = (te / se).sqrt();
1595+ for i in lo..hi {
1596+ let sc = source[band][i].scale(scale);
1597+ let tc = target[band][i];
1598+ let cross = sc * tc.conj();
1599+ cross_re += cross.re;
1600+ cross_im += cross.im;
1601+ sim_e += sc.re * sc.re + sc.im * sc.im;
1602+ tgt_e += tc.re * tc.re + tc.im * tc.im;
1603+ }
1604+ }
1605+ let den = (sim_e * tgt_e).sqrt();
1606+ let coh = if den > 0.0 {
1607+ (cross_re * cross_re + cross_im * cross_im).sqrt() / den
1608+ } else {
1609+ 0.0
1610+ };
1611+ (band, coh)
1612+ })
1613+ .collect()
1614+ };
1615+ (
1616+ band_coherence(&sim_spec, &t_spec),
1617+ band_coherence(&sim_spec, &o_spec),
1618+ band_coherence(&o_spec, &t_spec),
1619+ )
1620+}
1621+
1622+/// (Round-46, Task 2) Per-band 2nd-order complex prediction transfer fit
1623+/// between the plain-copy sim series and the REFERENCE's own HF series for
1624+/// that band: `ref[l] ~= a0*sim[l] + a1*sim[l-1] + a2*sim[l-2]`, least
1625+/// squares over the whole file -- the same shape `sbr_hf::generate`'s own
1626+/// chirp filter has (`y = residual + ca1*y[n-1] + ca2*y[n-2]`, an IIR rather
1627+/// than this FIR, but both are order-2 linear reshapings of the same copied
1628+/// content), so the fitted taps are directly comparable in spirit to our own
1629+/// bandwidth-expanded LPC coefficients: near `(1,0,0)` means "reference is
1630+/// also just a plain copy here", taps with real weight on lag 1/2 mean a
1631+/// genuine order-2 transformation is present.
1632+/// `target_is_ours`: fit against our own decode (`o_spec`) instead of the
1633+/// reference's (`t_spec`) -- same `sim` (built from the reference's own low
1634+/// band either way), so the two calls' fitted taps are directly comparable:
1635+/// what transform sim would need to become ours vs. to become the reference.
1636+#[allow(clippy::needless_range_loop)] // fixed 3x3 complex Gaussian elimination, index math throughout
1637+pub(super) fn hf_patch_transfer_fit(
1638+ o: &[f32],
1639+ t: &[f32],
1640+ bands: &[usize],
1641+ target_is_ours: bool,
1642+) -> Vec<(usize, [ec_dsp::Complex<f64>; 3])> {
1643+ let (o_spec, t_spec, sim_spec) = qmf_domain_spec(o, t);
1644+ let target_spec = if target_is_ours { &o_spec } else { &t_spec };
1645+ let mut results = Vec::new();
1646+ for &band in bands {
1647+ if band >= sim_spec.len() {
1648+ continue;
1649+ }
1650+ let sim_raw = &sim_spec[band];
1651+ let ref_raw = &target_spec[band];
1652+ let len = sim_raw.len().min(ref_raw.len());
1653+ if len < 8 {
1654+ continue;
1655+ }
1656+ // Normalize each series to unit RMS first: the raw QMF-domain
1657+ // amplitudes differ by orders of magnitude (sim carries no envelope
1658+ // gain, `ref` does), which would otherwise make every fitted
1659+ // coefficient collapse toward the gain ratio rather than the
1660+ // fraction-of-`ref`-explained-by-which-lag this fit is meant to
1661+ // read off.
1662+ let rms = |s: &[ec_dsp::Complex<f64>]| -> f64 {
1663+ (s[..len]
1664+ .iter()
1665+ .map(|c| c.re * c.re + c.im * c.im)
1666+ .sum::<f64>()
1667+ / len as f64)
1668+ .sqrt()
1669+ .max(1e-300)
1670+ };
1671+ let sim_scale = 1.0 / rms(sim_raw);
1672+ let ref_scale = 1.0 / rms(ref_raw);
1673+ let sim: Vec<ec_dsp::Complex<f64>> =
1674+ sim_raw[..len].iter().map(|c| c.scale(sim_scale)).collect();
1675+ let refb: Vec<ec_dsp::Complex<f64>> =
1676+ ref_raw[..len].iter().map(|c| c.scale(ref_scale)).collect();
1677+ let sim = &sim[..];
1678+ let refb = &refb[..];
1679+ // Complex 3x3 Hermitian normal equations: r[i][j] = sum sim[l-i] conj(sim[l-j]),
1680+ // p[i] = sum sim[l-i] conj(ref[l])... solved as R^T a = p with R real basis in
1681+ // complex arithmetic (Gaussian elimination with partial pivoting by magnitude).
1682+ let mut r = [[ec_dsp::Complex::new(0.0f64, 0.0); 3]; 3];
1683+ let mut p = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1684+ for l in 2..len {
1685+ let s = [sim[l], sim[l - 1], sim[l - 2]];
1686+ let y = refb[l];
1687+ for i in 0..3 {
1688+ p[i] = p[i] + s[i].conj() * y;
1689+ for j in 0..3 {
1690+ r[i][j] = r[i][j] + s[i].conj() * s[j];
1691+ }
1692+ }
1693+ }
1694+ // Gaussian elimination on the augmented [r | p] system.
1695+ let mut aug = r;
1696+ let mut rhs = p;
1697+ for col in 0..3 {
1698+ let mut piv = col;
1699+ let mut best = aug[col][col].norm_sqr();
1700+ for row in (col + 1)..3 {
1701+ let m = aug[row][col].norm_sqr();
1702+ if m > best {
1703+ best = m;
1704+ piv = row;
1705+ }
1706+ }
1707+ if best < 1e-24 {
1708+ continue;
1709+ }
1710+ aug.swap(col, piv);
1711+ rhs.swap(col, piv);
1712+ let inv = aug[col][col].conj().scale(1.0 / best);
1713+ for row in (col + 1)..3 {
1714+ let f = aug[row][col] * inv;
1715+ for k in 0..3 {
1716+ aug[row][k] = aug[row][k] - f * aug[col][k];
1717+ }
1718+ rhs[row] = rhs[row] - f * rhs[col];
1719+ }
1720+ }
1721+ let mut a = [ec_dsp::Complex::new(0.0f64, 0.0); 3];
1722+ for row in (0..3).rev() {
1723+ let mut acc = rhs[row];
1724+ for k in (row + 1)..3 {
1725+ acc = acc - aug[row][k] * a[k];
1726+ }
1727+ let d = aug[row][row];
1728+ a[row] = if d.norm_sqr() > 1e-24 {
1729+ acc * d.conj().scale(1.0 / d.norm_sqr())
1730+ } else {
1731+ ec_dsp::Complex::new(0.0, 0.0)
1732+ };
1733+ }
1734+ results.push((band, a));
1735+ }
1736+ results
1737+}
1738+
1739+/// A file discovered under the user's own media directories: its path, which
1740+/// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the
1741+/// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used
1742+/// only to draw the below/above-crossover line for localization, not as a
1743+/// spec-exact `kx` band edge.
1744+pub(super) struct Candidate {
1745+ pub(super) path: PathBuf,
1746+ /// Which AAC stream, 0-based among AAC streams only -- what
1747+ /// `extract_from` selects out of the demuxer's stream list.
1748+ pub(super) aac_stream: usize,
1749+ /// The same stream's absolute ffprobe/ffmpeg index -- what `-map`
1750+ /// selects, and not the same number when the container also carries a
1751+ /// non-AAC audio track before it (FMJ's mkv has an AC-3 track between its
1752+ /// two AAC ones).
1753+ pub(super) ffmpeg_stream: usize,
1754+ pub(super) crossover_hz: f64,
1755+}
1756+
1757+/// Round-20 residual/side-info correlation. Builds a (frame x band) residual
1758+/// ENERGY grid at AU-aligned 2048-output-sample blocks -- a plain (2x) SBR
1759+/// stream reconstructs exactly one 2048-sample block per core access unit,
1760+/// so `n`-th block lines up 1:1 with `ec_aac::sbr_sideinfo_log()`'s `frame`
1761+/// counter -- then cross-tabulates that grid against every side-info feature
1762+/// the log carries. FFT is linear, so `FFT(o_block) - FFT(t_block) ==
1763+/// FFT(o_block - t_block)`: the residual's own per-bin energy is obtained
1764+/// directly from each side's spectrum without ever materializing a
1765+/// time-domain residual array. `band` is the same `rate/256`-wide index
1766+/// domain `per_band_correlation`/`tables.kx`/`f_high`/`f_noise` all already
1767+/// share (measured in round-14/round-16), so a side-info row's `f_high`/
1768+/// `f_noise` boundaries index straight into this grid's bins with no
1769+/// rescaling.
1770+pub(super) fn residual_sideinfo_analysis(o: &[f32], t: &[f32], oa: usize, ob: usize, rate: u32, ch: usize) {
1771+ let rows: Vec<_> = ec_aac::sbr_sideinfo_log()
1772+ .into_iter()
1773+ .filter(|r| r.ch == ch)
1774+ .collect();
1775+ if rows.is_empty() {
1776+ eprintln!(" ch{ch} SIDEINFO: no rows logged (set EC_AAC_SBR_SIDEINFO_DEBUG too)");
1777+ return;
1778+ }
1779+ const FFT_LEN: usize = 2048;
1780+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
1781+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
1782+ let bins = rfft.spectrum_len();
1783+ let mut o_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1784+ let mut t_spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
1785+
1786+ // Per-frame residual bin-energy vector (index = `band`, per-bin, not yet
1787+ // grouped) and, alongside it, a per-bin peakiness ratio (own-bin energy
1788+ // vs its 3-bin neighbourhood mean) used by the whiteness check.
1789+ let mut energy: std::collections::HashMap<usize, Vec<f64>> = std::collections::HashMap::new();
1790+ for row in &rows {
1791+ if energy.contains_key(&row.frame) {
1792+ continue;
1793+ }
1794+ let base_o = oa + row.frame * FFT_LEN;
1795+ let base_t = ob + row.frame * FFT_LEN;
1796+ if base_o + FFT_LEN > o.len() || base_t + FFT_LEN > t.len() {
1797+ continue;
1798+ }
1799+ let mut ob_win = o[base_o..base_o + FFT_LEN].to_vec();
1800+ let mut tb_win = t[base_t..base_t + FFT_LEN].to_vec();
1801+ win.apply(&mut ob_win);
1802+ win.apply(&mut tb_win);
1803+ rfft.forward(&ob_win, &mut o_spec);
1804+ rfft.forward(&tb_win, &mut t_spec);
1805+ let e: Vec<f64> = o_spec
1806+ .iter()
1807+ .zip(&t_spec)
1808+ .map(|(a, b)| f64::from((*a - *b).norm_sqr()))
1809+ .collect();
1810+ energy.insert(row.frame, e);
1811+ }
1812+ if energy.is_empty() {
1813+ eprintln!(" ch{ch} SIDEINFO: no frame overlapped the aligned window");
1814+ return;
1815+ }
1816+ // SBR-band-index units (`kx`/`k2`/`f_high`/`f_noise`) are `band_hz =
1817+ // rate/256` wide; FFT bins here are `bin_hz = rate/FFT_LEN` wide. The
1818+ // ratio `band_hz/bin_hz = FFT_LEN/256 = 8` is rate-independent, matching
1819+ // `per_band_correlation`'s own `lo = band*band_hz/bin_hz` conversion --
1820+ // one SBR band is exactly 8 of these FFT bins, never 1.
1821+ const BINS_PER_SBR_BAND: usize = FFT_LEN / 256;
1822+ let band_range = |lo: i64, hi: i64| -> (usize, usize) {
1823+ let lo = ((lo.max(0) as usize) * BINS_PER_SBR_BAND).min(bins);
1824+ let hi = (((hi.max(0) as usize) * BINS_PER_SBR_BAND).max(lo + 1)).min(bins);
1825+ (lo, hi)
1826+ };
1827+ let sum_range = |e: &[f64], lo: usize, hi: usize| -> f64 { e[lo..hi].iter().sum() };
1828+
1829+ // --- predictor 1: add_harmonic bands (and their immediate neighbours) ---
1830+ let (mut harm_sum, mut harm_n) = (0.0f64, 0usize);
1831+ let (mut noharm_sum, mut noharm_n) = (0.0f64, 0usize);
1832+ let (mut adj_sum, mut adj_n) = (0.0f64, 0usize);
1833+ for row in &rows {
1834+ let Some(e) = energy.get(&row.frame) else {
1835+ continue;
1836+ };
1837+ let Some(harm) = &row.add_harmonic else {
1838+ continue;
1839+ };
1840+ for (i, &flag) in harm.iter().enumerate() {
1841+ let (lo, hi) = match (row.f_high.get(i), row.f_high.get(i + 1)) {
1842+ (Some(&a), Some(&b)) => band_range(a, b),
1843+ _ => continue,
1844+ };
1845+ let s = sum_range(e, lo, hi);
1846+ let cells = (hi - lo).max(1);
1847+ if flag != 0 {
1848+ harm_sum += s / cells as f64;
1849+ harm_n += 1;
1850+ } else {
1851+ noharm_sum += s / cells as f64;
1852+ noharm_n += 1;
1853+ }
1854+ // adjacent band (off-by-one probe): the band one slot up.
1855+ if flag != 0
1856+ && let (Some(&a2), Some(&b2)) = (row.f_high.get(i + 1), row.f_high.get(i + 2))
1857+ {
1858+ let (lo2, hi2) = band_range(a2, b2);
1859+ adj_sum += sum_range(e, lo2, hi2) / (hi2 - lo2).max(1) as f64;
1860+ adj_n += 1;
1861+ }
1862+ }
1863+ }
1864+
1865+ // --- predictor 2: envelope time borders vs envelope interior ---
1866+ // Envelope borders are in `t_env` (pre-`RATE`-scale envelope time-slot
1867+ // units); one unit is `RATE(2) * SYNTHESIS_BANDS(64) = 128` output
1868+ // samples. Time-domain residual energy (broadband, not per-band) near
1869+ // (+/-64 samples) each INTERIOR border vs the envelope's own midpoint.
1870+ let (mut border_sum, mut border_n) = (0.0f64, 0usize);
1871+ let (mut mid_sum, mut mid_n) = (0.0f64, 0usize);
1872+ let sample_energy = |global: usize| -> Option<f64> {
1873+ let oi = oa + global;
1874+ let ti = ob + global;
1875+ if oi >= o.len() || ti >= t.len() {
1876+ return None;
1877+ }
1878+ let d = f64::from(o[oi]) - f64::from(t[ti]);
1879+ Some(d * d)
1880+ };
1881+ for row in &rows {
1882+ let frame_base = row.frame * FFT_LEN;
1883+ for w in row.t_env.windows(2) {
1884+ let (b0, b1) = (w[0] * 128, w[1] * 128);
1885+ if b1 <= b0 {
1886+ continue;
1887+ }
1888+ let mid = (b0 + b1) / 2;
1889+ for d in -64i64..=64 {
1890+ let s0 = b0 + d;
1891+ if s0 >= 0
1892+ && let Some(v) = sample_energy(frame_base + s0 as usize)
1893+ {
1894+ border_sum += v;
1895+ border_n += 1;
1896+ }
1897+ }
1898+ for off in 0..(b1 - b0).min(256) {
1899+ let s = mid - (b1 - b0).min(256) / 2 + off;
1900+ if s >= 0
1901+ && (s - mid).abs() > 64
1902+ && let Some(v) = sample_energy(frame_base + s as usize)
1903+ {
1904+ mid_sum += v;
1905+ mid_n += 1;
1906+ }
1907+ }
1908+ }
1909+ }
1910+
1911+ // --- predictor 3: hold-state (apply_last) vs fresh-payload frames ---
1912+ let (mut hold_sum, mut hold_n) = (0.0f64, 0usize);
1913+ let (mut fresh_sum, mut fresh_n) = (0.0f64, 0usize);
1914+ for row in &rows {
1915+ let Some(e) = energy.get(&row.frame) else {
1916+ continue;
1917+ };
1918+ let total: f64 = e.iter().sum();
1919+ if row.source == "hold" {
1920+ hold_sum += total;
1921+ hold_n += 1;
1922+ } else {
1923+ fresh_sum += total;
1924+ fresh_n += 1;
1925+ }
1926+ }
1927+
1928+ // --- predictor 4: frame immediately after a coupling flip ---
1929+ let (mut flip_sum, mut flip_n) = (0.0f64, 0usize);
1930+ let (mut noflip_sum, mut noflip_n) = (0.0f64, 0usize);
1931+ let mut sorted = rows.clone();
1932+ sorted.sort_by_key(|r| r.frame);
1933+ for pair in sorted.windows(2) {
1934+ let (prev, cur) = (&pair[0], &pair[1]);
1935+ let Some(e) = energy.get(&cur.frame) else {
1936+ continue;
1937+ };
1938+ let total: f64 = e.iter().sum();
1939+ if cur.coupling != prev.coupling {
1940+ flip_sum += total;
1941+ flip_n += 1;
1942+ } else {
1943+ noflip_sum += total;
1944+ noflip_n += 1;
1945+ }
1946+ }
1947+
1948+ // --- predictor 5: residual scaling per invf_mode level, per noise band ---
1949+ let mut per_level = [(0.0f64, 0usize); 4];
1950+ for row in &rows {
1951+ let Some(e) = energy.get(&row.frame) else {
1952+ continue;
1953+ };
1954+ for (i, &mode) in row.invf_mode.iter().enumerate() {
1955+ let (lo, hi) = match (row.f_noise.get(i), row.f_noise.get(i + 1)) {
1956+ (Some(&a), Some(&b)) => band_range(a, b),
1957+ _ => continue,
1958+ };
1959+ let cells = (hi - lo).max(1);
1960+ let level = (mode as usize).min(3);
1961+ per_level[level].0 += sum_range(e, lo, hi) / cells as f64;
1962+ per_level[level].1 += 1;
1963+ }
1964+ }
1965+
1966+ // --- predictor 6: residual whiteness within HF bands (peakiness) ---
1967+ // mean(max-bin / mean-bin) over each HF band each frame -- near 1 reads
1968+ // noise-like, large reads tonal (one bin dominating the band).
1969+ let (mut peak_sum, mut peak_n) = (0.0f64, 0usize);
1970+ for row in &rows {
1971+ let Some(e) = energy.get(&row.frame) else {
1972+ continue;
1973+ };
1974+ let (lo, hi) = band_range(row.kx, row.k2);
1975+ for group_lo in (lo..hi.min(e.len())).step_by(4) {
1976+ let group_hi = (group_lo + 4).min(hi).min(e.len());
1977+ if group_hi <= group_lo {
1978+ continue;
1979+ }
1980+ let slice = &e[group_lo..group_hi];
1981+ let mean = slice.iter().sum::<f64>() / slice.len() as f64;
1982+ let max = slice.iter().cloned().fold(0.0f64, f64::max);
1983+ if mean > 0.0 {
1984+ peak_sum += max / mean;
1985+ peak_n += 1;
1986+ }
1987+ }
1988+ }
1989+
1990+ // Heat summary: the full (frame x band) grid collapsed to two profiles
1991+ // (mean over bands per 50-frame group; mean over frames per 8-band
1992+ // group) -- the full grid itself is `energy`, ~489 x ~90 cells, too
1993+ // large to print usefully every run.
1994+ let mut frame_keys: Vec<usize> = energy.keys().cloned().collect();
1995+ frame_keys.sort_unstable();
1996+ println!(
1997+ " ch{ch} RESIDUAL HEAT temporal profile (50-frame groups, mean energy over all bands):"
1998+ );
1999+ for chunk in frame_keys.chunks(50) {
2000+ let (mut s, mut n) = (0.0f64, 0usize);
crates/ec-aac/tests/sbr_real_library/main.rsadded+41 -0
@@ -0,0 +1,41 @@
1+//! The SBR chain, against real HE-AAC files pulled from the user's own media
2+//! directories, decoded through their real container (mp4 `esds` / Matroska
3+//! `CodecPrivate`) so `AacDecoder::with_config_bytes` actually arms the SBR
4+//! path -- `tests/oracle.rs` remuxes everything to bare ADTS first, and an
5+//! ADTS stream carries no AudioSpecificConfig, so its SBR chain never sees a
6+//! frame. Every file here is a live discovery over `~/Music`, `~/Downloads`,
7+//! `~/Videos`: absent files skip loudly, nothing is generated or bundled.
8+
9+use std::fs::File;
10+use std::io::{BufReader, Read};
11+use std::path::{Path, PathBuf};
12+use std::process::Command;
13+
14+use ec_aac::{AacDecoder, parse_audio_specific_config};
15+use ec_core::{CodecId, Demuxer, Packet};
16+use ec_matroska::MatroskaDemuxer;
17+use ec_mp4::Mp4Demuxer;
18+
19+/// Every `#[test]` in this file decodes real SBR content through
20+/// `our_decode`/`our_decode_uncapped`, and a handful of them steer that
21+/// decode with debug switches (`EC_AAC_SBR_HF_BYPASS`,
22+/// `EC_AAC_SBR_SIDEINFO_DEBUG`, `EC_AAC_SBR_NOISE_ZERO`,
23+/// `EC_AAC_SBR_NOISE_FRACTION`). They are set through
24+/// `ec_aac::knobs` guards, which override the switch on this test's thread
25+/// only and restore it on drop, so no test can flip another test's decode.
26+/// The lock below still serialises the tests because the decoder's
27+/// sideinfo and noise-fraction logs are process-global and read back by
28+/// each test.
29+static DECODE_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
30+
31+#[path = "../common/mod.rs"]
32+mod common;
33+mod helpers;
34+mod chunk_a;
35+mod chunk_b;
36+mod chunk_c;
37+
38+use helpers::*;
39+use chunk_a::*;
40+use chunk_b::*;
41+use chunk_c::*;
crates/ec-ac3/fuzz/.gitignoreadded+4 -0
@@ -0,0 +1,4 @@
1+target
2+corpus
3+artifacts
4+coverage
crates/ec-ac3/fuzz/Cargo.tomladded+32 -0
@@ -0,0 +1,32 @@
1+[package]
2+name = "ec-ac3-fuzz"
3+version = "0.0.0"
4+publish = false
5+edition = "2024"
6+
7+[package.metadata]
8+cargo-fuzz = true
9+
10+[dependencies]
11+libfuzzer-sys = "0.4"
12+
13+[dependencies.ec-ac3]
14+path = ".."
15+
16+# Keeps this crate out of the main workspace.
17+[workspace]
18+members = ["."]
19+
20+[[bin]]
21+name = "decode_stream"
22+path = "fuzz_targets/decode_stream.rs"
23+test = false
24+doc = false
25+bench = false
26+
27+[[bin]]
28+name = "parse_header"
29+path = "fuzz_targets/parse_header.rs"
30+test = false
31+doc = false
32+bench = false
crates/ec-ac3/fuzz/fuzz_targets/decode_stream.rsadded+43 -0
@@ -0,0 +1,43 @@
1+#![no_main]
2+
3+use ec_ac3::{Ac3Decoder, eac3, frame_size};
4+use libfuzzer_sys::fuzz_target;
5+
6+// The whole input is an elementary stream: walk it syncframe by syncframe, the way a
7+// container would hand frames over, and decode each one. Bytes that do not start a
8+// syncframe are skipped one at a time. A dependent substream is handed over with the
9+// independent substream it extends, as a container packet carries them.
10+fuzz_target!(|data: &[u8]| {
11+ let mut dec = Ac3Decoder::new();
12+ let mut pos = 0;
13+ while pos + 2 <= data.len() {
14+ let rest = &data[pos..];
15+ if rest[0] != 0x0B || rest[1] != 0x77 {
16+ pos += 1;
17+ continue;
18+ }
19+ let size = match frame_size(rest) {
20+ Ok(size) => size,
21+ Err(ec_ac3::Error::NeedMore) => break,
22+ Err(_) => {
23+ pos += 1;
24+ continue;
25+ }
26+ };
27+ if size == 0 || size > rest.len() {
28+ break;
29+ }
30+ let mut end = pos + size;
31+ while let Some(tail) = data.get(end..) {
32+ let dependent = tail
33+ .get(2..)
34+ .is_some_and(|b| eac3::bsi::parse(b).is_ok_and(|h| h.strmtyp == eac3::StreamType::Dependent));
35+ match frame_size(tail) {
36+ Ok(next) if dependent && next <= tail.len() => end += next,
37+ _ => break,
38+ }
39+ }
40+ let _ = dec.decode_frame(&data[pos..end]);
41+ pos = end;
42+ }
43+});
crates/ec-ac3/fuzz/fuzz_targets/parse_header.rsadded+14 -0
@@ -0,0 +1,14 @@
1+#![no_main]
2+
3+use ec_ac3::{bsi, eac3, syncinfo};
4+use libfuzzer_sys::fuzz_target;
5+
6+// Header-only paths: syncinfo + BSI for AC-3, and the E-AC-3 BSI, plus the frame-length probe.
7+fuzz_target!(|data: &[u8]| {
8+ let _ = syncinfo::parse(data);
9+ if data.len() > 5 {
10+ let _ = bsi::parse(&data[5..]);
11+ }
12+ let _ = eac3::bsi::parse(data);
13+ let _ = ec_ac3::frame_size(data);
14+});
crates/ec-ac3/fuzz/seed.shadded+49 -0

Diff too large; view file

@@ -0,0 +1,49 @@
1+#!/usr/bin/env bash
2+# seed.sh: fill fuzz/corpus/<target>/ from the repo's AC-3 and E-AC-3 fixtures (root fixtures/audio).
3+#
4+# decode_stream gets each fixture truncated to its first few syncframes (5 frames).
crates/ec-ac3/src/decode.rsmodified+15 -5

Diff too large; view file

crates/ec-ac3/src/decoder.rsmodified+201 -64

Diff too large; view file

crates/ec-ac3/src/dependent.rsadded+247 -0

Diff too large; view file

crates/ec-ac3/src/encode.rsmodified+4 -2

Diff too large; view file

crates/ec-ac3/src/lib.rsmodified+12 -8

Diff too large; view file

crates/ec-ac3/src/mantissa.rsmodified+60 -14

Diff too large; view file

crates/ec-ac3/src/stack_budget.rsmodified+32 -14

Diff too large; view file

crates/ec-ac3/tests/it/common.rsadded+9 -0

Diff too large; view file

crates/ec-ac3/tests/decode_matrix.rs → crates/ec-ac3/tests/it/decode_matrix.rsrenamed+3 -9

Diff too large; view file

crates/ec-ac3/tests/it/dependent.rsadded+317 -0

Diff too large; view file

crates/ec-ac3/tests/encode_matrix.rs → crates/ec-ac3/tests/it/encode_matrix.rsrenamed+5 -11

Diff too large; view file

crates/ec-ac3/tests/it/ffmpeg_parity.rsadded+184 -0

Diff too large; view file

crates/ec-ac3/tests/it/main.rsadded+10 -0

Diff too large; view file

crates/ec-ac3/tests/it/packet_walk.rsadded+203 -0

Diff too large; view file

crates/ec-ac3/tests/it/real_library.rsadded+242 -0

Diff too large; view file

crates/ec-alac/src/encode.rsmodified+2 -2

Diff too large; view file

crates/ec-alac/tests/encode.rsmodified+1 -1

Diff too large; view file

crates/ec-amr/Cargo.tomladded+14 -0

Diff too large; view file

crates/ec-amr/fuzz/.gitignoreadded+4 -0

Diff too large; view file

crates/ec-amr/fuzz/Cargo.lockadded+102 -0

Diff too large; view file

crates/ec-amr/fuzz/Cargo.tomladded+42 -0

Diff too large; view file

crates/ec-amr/fuzz/fuzz_targets/fuzz_container.rsadded+29 -0

Diff too large; view file

crates/ec-amr/fuzz/fuzz_targets/fuzz_nb_decode.rsadded+22 -0

Diff too large; view file

crates/ec-amr/fuzz/fuzz_targets/wb.rsadded+19 -0

Diff too large; view file

crates/ec-amr/fuzz/seed.shadded+24 -0

Diff too large; view file

crates/ec-amr/src/container.rsadded+319 -0

Diff too large; view file

crates/ec-amr/src/lib.rsadded+7 -0

Diff too large; view file

crates/ec-amr/src/nb/basic.rsadded+627 -0

Diff too large; view file

crates/ec-amr/src/nb/bitstream.rsadded+198 -0

Diff too large; view file

crates/ec-amr/src/nb/decoder.rsadded+794 -0

Diff too large; view file

crates/ec-amr/src/nb/dtx.rsadded+934 -0

Diff too large; view file

crates/ec-amr/src/nb/excitation.rsadded+824 -0

Diff too large; view file

crates/ec-amr/src/nb/lpc.rsadded+346 -0

Diff too large; view file

crates/ec-amr/src/nb/mod.rsadded+11 -0

Diff too large; view file

crates/ec-amr/src/nb/post.rsadded+370 -0

Diff too large; view file

crates/ec-amr/src/nb/tables.rsadded+1441 -0

Diff too large; view file

crates/ec-amr/src/wb/bits.rsadded+477 -0

Diff too large; view file

crates/ec-amr/src/wb/core.rsadded+670 -0

Diff too large; view file

crates/ec-amr/src/wb/dtx.rsadded+562 -0

Diff too large; view file

crates/ec-amr/src/wb/exc.rsadded+844 -0

Diff too large; view file

crates/ec-amr/src/wb/exc_tab.rsadded+69 -0

Diff too large; view file

crates/ec-amr/src/wb/isf.rsadded+325 -0

Diff too large; view file

crates/ec-amr/src/wb/isf_tab.rsadded+500 -0

Diff too large; view file

crates/ec-amr/src/wb/math.rsadded+199 -0

Diff too large; view file

crates/ec-amr/src/wb/mod.rsadded+222 -0

Diff too large; view file

crates/ec-amr/src/wb/ops.rsadded+205 -0

Diff too large; view file

crates/ec-amr/src/wb/synth.rsadded+581 -0

Diff too large; view file

crates/ec-amr/tests/container_roundtrip.rsadded+123 -0

Diff too large; view file

crates/ec-amr/tests/oracle.rsadded+238 -0

Diff too large; view file

crates/ec-amr/tests/wb_oracle.rsadded+283 -0

Diff too large; view file

crates/ec-ass/examples/benchp1.rsadded+44 -0

Diff too large; view file

crates/ec-ass/fuzz/.gitignoreadded+4 -0

Diff too large; view file

crates/ec-ass/fuzz/Cargo.tomladded+49 -0

Diff too large; view file

crates/ec-ass/fuzz/fuzz_targets/events.rsadded+18 -0

Diff too large; view file

crates/ec-ass/fuzz/fuzz_targets/overrides.rsadded+24 -0

Diff too large; view file

crates/ec-ass/fuzz/fuzz_targets/script.rsadded+28 -0

Diff too large; view file

crates/ec-ass/fuzz/fuzz_targets/styles.rsadded+26 -0

Diff too large; view file

crates/ec-ass/fuzz/seed.shadded+37 -0

Diff too large; view file

crates/ec-ass/src/lib.rsmodified+218 -23

Diff too large; view file

crates/ec-ass/tests/data/karaoke_colours.assadded+19 -0

Diff too large; view file

crates/ec-ass/tests/data/layers_overlap.assadded+23 -0

Diff too large; view file

crates/ec-ass/tests/data/multiline_wrap0.assadded+19 -0

Diff too large; view file

crates/ec-ass/tests/data/multiline_wrap2.assadded+16 -0

Diff too large; view file

crates/ec-ass/tests/data/reordered_format.assadded+18 -0

Diff too large; view file

crates/ec-ass/tests/data/styles_tags.assadded+22 -0

Diff too large; view file

crates/ec-ass/tests/data/timing_edges.assadded+22 -0

Diff too large; view file

crates/ec-ass/tests/data/unicode_sections.assadded+34 -0

Diff too large; view file

crates/ec-ass/tests/ffmpeg_parity.rsadded+347 -0

Diff too large; view file

crates/ec-ass/tests/fuzz_regressions.rsadded+76 -0

Diff too large; view file

crates/ec-av1-syntax/src/frame.rsmodified+14 -0

Diff too large; view file

crates/ec-av1-syntax/src/lib.rsmodified+8 -0

Diff too large; view file

crates/ec-av1/Cargo.tomlmodified+7 -0

Diff too large; view file

crates/ec-av1/examples/alloc_probe.rsmodified+51 -42

Diff too large; view file

crates/ec-av1/examples/decode_bench.rsadded+87 -0

Diff too large; view file

crates/ec-av1/examples/decode_probe.rsmodified+1 -1

Diff too large; view file

crates/ec-av1/examples/dump_yuv.rsmodified+3 -6

Diff too large; view file

crates/ec-av1/fixtures/s422_lr_10bit_200x120.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/.gitignoreadded+4 -0

Diff too large; view file

crates/ec-av1/fuzz/Cargo.tomladded+32 -0

Diff too large; view file

crates/ec-av1/fuzz/fuzz_targets/decode_stream.rsadded+62 -0

Diff too large; view file

crates/ec-av1/fuzz/fuzz_targets/parse_obu.rsadded+32 -0

Diff too large; view file

crates/ec-av1/fuzz/seed.shadded+13 -0

Diff too large; view file

crates/ec-av1/fuzz/seeds/420_intrabc_rect4_witness.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/420_odd65x65_key.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/422_allskip_2f.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/422_key_64x64.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/422_muchunk_intra_in_inter_128x256.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/444_intra_in_inter_128root_mu_chroma.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/444_lossy_rect4_inter_witness.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_10_32_grain.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_10_64_cdef_lr.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_16.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_32_intrabc.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_48x40_denoise.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_48x40_grain.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_64_lossless.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t420_8_64x48_cdef_lr.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t422_10_32_intrabc.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t422_10_64.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t422_8_48x40.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t444_10_16.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t444_8_32.obuadded+0 -0

Binary file changed

crates/ec-av1/fuzz/seeds/t444_8_64_intrabc_screen.obuadded+0 -0

Binary file changed

crates/ec-av1/src/autothreads.rsadded+110 -0

Diff too large; view file

crates/ec-av1/src/cdf.rs → crates/ec-av1/src/cdf/mod.rsrenamed+3 -1793

Diff too large; view file

crates/ec-av1/src/cdf/tables_tail.rsadded+1669 -0

Diff too large; view file

crates/ec-av1/src/cdf/tests.rsadded+122 -0

Diff too large; view file

crates/ec-av1/src/cdf_state.rsmodified+4 -4

Diff too large; view file

crates/ec-av1/src/census.rsmodified+3 -3

Diff too large; view file

crates/ec-av1/src/decode.rsdeleted+0 -61691

Diff too large; view file

crates/ec-av1/src/decode/block.rsadded+3459 -0

Diff too large; view file

crates/ec-av1/src/decode/cdef.rsadded+393 -0

Diff too large; view file

crates/ec-av1/src/decode/cdef_simd.rsadded+250 -0

Diff too large; view file

crates/ec-av1/src/decode/coeffs.rsadded+4498 -0

Diff too large; view file

crates/ec-av1/src/decode/counters.rsadded+4459 -0

Diff too large; view file

crates/ec-av1/src/decode/deblock.rsadded+1044 -0

Diff too large; view file

crates/ec-av1/src/decode/deblock_simd.rsadded+459 -0

Diff too large; view file

crates/ec-av1/src/decode/frame_tile.rsadded+3506 -0

Diff too large; view file

crates/ec-av1/src/decode/inter_block.rsadded+4457 -0

Diff too large; view file

crates/ec-av1/src/decode/inter_block8.rsadded+3024 -0

Diff too large; view file

crates/ec-av1/src/decode/inter_ctx.rsadded+3047 -0

Diff too large; view file

crates/ec-av1/src/decode/inter_intra_arm.rsadded+1409 -0

Diff too large; view file

crates/ec-av1/src/decode/inter_shapes.rsadded+1721 -0

Diff too large; view file

crates/ec-av1/src/decode/key_tile.rsadded+3059 -0

Diff too large; view file

crates/ec-av1/src/decode/leaf8.rsadded+2155 -0

Diff too large; view file

crates/ec-av1/src/decode/leaf_sub8.rsadded+3176 -0

Diff too large; view file

crates/ec-av1/src/decode/mod.rsadded+3797 -0

Diff too large; view file

crates/ec-av1/src/decode/obmc_skip_chroma_tests.rsadded+27 -0

Diff too large; view file

crates/ec-av1/src/decode/post_filter.rsadded+353 -0

Diff too large; view file

crates/ec-av1/src/decode/rect.rsadded+4956 -0

Diff too large; view file

crates/ec-av1/src/decode/rect4.rsadded+3994 -0

Diff too large; view file

crates/ec-av1/src/decode/replay.rsadded+613 -0

Diff too large; view file

crates/ec-av1/src/decode/sub8_inter.rsadded+3147 -0

Diff too large; view file

crates/ec-av1/src/decode/tests.rsadded+3855 -0

Diff too large; view file

crates/ec-av1/src/decode/tx4x8_table_tests.rsadded+89 -0

Diff too large; view file

crates/ec-av1/src/decode/wave.rsadded+712 -0

Diff too large; view file

crates/ec-av1/src/dumpio.rsmodified+3 -2

Diff too large; view file

crates/ec-av1/src/encode.rsdeleted+0 -23785

Diff too large; view file

crates/ec-av1/src/encode/coef.rsadded+2445 -0

Diff too large; view file

crates/ec-av1/src/encode/frame.rsadded+2871 -0

Diff too large; view file

crates/ec-av1/src/encode/inter_search.rsadded+4687 -0

Diff too large; view file

crates/ec-av1/src/encode/mod.rsadded+2572 -0

Diff too large; view file

crates/ec-av1/src/encode/more_tests.rsadded+3929 -0

Diff too large; view file

crates/ec-av1/src/encode/split.rsadded+3334 -0

Diff too large; view file

crates/ec-av1/src/encode/tests.rsadded+4022 -0

Diff too large; view file

crates/ec-av1/src/encoder/mod.rsadded+2559 -0

Diff too large; view file

crates/ec-av1/src/encoder.rs → crates/ec-av1/src/encoder/tests.rsrenamed+26 -2599

Diff too large; view file

crates/ec-av1/src/fault.rsadded+61 -0

Diff too large; view file

crates/ec-av1/src/film_grain.rsmodified+302 -144

Diff too large; view file

crates/ec-av1/src/filter_search.rsmodified+12 -8

Diff too large; view file

crates/ec-av1/src/gate_coverage.rsmodified+38 -40

Diff too large; view file

crates/ec-av1/src/intra.rsmodified+42 -34

Diff too large; view file

crates/ec-av1/src/lib.rsmodified+13 -9

Diff too large; view file

crates/ec-av1/src/mc.rsmodified+826 -291

Diff too large; view file

crates/ec-av1/src/motion_field.rsmodified+2 -0

Diff too large; view file

crates/ec-av1/src/msac.rsmodified+2 -4

Diff too large; view file

crates/ec-av1/src/mvstack.rsmodified+11 -4

Diff too large; view file

crates/ec-av1/src/par.rsmodified+282 -122

Diff too large; view file

crates/ec-av1/src/probe.rsmodified+6 -1

Diff too large; view file

crates/ec-av1/src/qm.rsdeleted+0 -7046

Diff too large; view file

crates/ec-av1/src/qm/iwt_a.rsadded+2278 -0

Diff too large; view file

crates/ec-av1/src/qm/iwt_b.rsadded+2278 -0

Diff too large; view file

crates/ec-av1/src/qm/iwt_c.rsadded+2278 -0

Diff too large; view file

crates/ec-av1/src/qm/mod.rsadded+165 -0

Diff too large; view file

crates/ec-av1/src/qm/tests.rsadded+106 -0

Diff too large; view file

crates/ec-av1/src/quant.rsmodified+1 -1

Diff too large; view file

crates/ec-av1/src/refusal_inventory.rsmodified+40 -41

Diff too large; view file

crates/ec-av1/src/restoration.rsmodified+46 -50

Diff too large; view file

crates/ec-av1/src/speed.rsmodified+34 -36

Diff too large; view file

crates/ec-av1/src/stack_budget.rsmodified+50 -31

Diff too large; view file

crates/ec-av1/src/stream.rsdeleted+0 -57178

Diff too large; view file

crates/ec-av1/src/stream/mod.rsadded+2598 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/gates_a.rsadded+2841 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/gates_b.rsadded+2804 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/layers.rsadded+78 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/mod.rsadded+21 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/support.rsadded+4172 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t01.rsadded+4538 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t02.rsadded+4341 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t03.rsadded+4567 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t04.rsadded+4516 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t05.rsadded+4488 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t06.rsadded+4444 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t07.rsadded+4479 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t08.rsadded+4540 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t09.rsadded+4486 -0

Diff too large; view file

crates/ec-av1/src/stream/tests/t10.rsadded+4293 -0

Diff too large; view file

crates/ec-av1/src/test_source.rsadded+103 -0

Diff too large; view file

crates/ec-av1/src/tile.rsdeleted+0 -11516

Diff too large; view file

crates/ec-av1/src/tile/blocks.rsadded+3381 -0

Diff too large; view file

crates/ec-av1/src/tile/leaf.rsadded+575 -0

Diff too large; view file

crates/ec-av1/src/tile/mod.rsadded+2503 -0

Diff too large; view file

crates/ec-av1/src/tile/syntax.rsadded+2521 -0

Diff too large; view file

crates/ec-av1/src/tile/tests.rsadded+2557 -0

Diff too large; view file

crates/ec-av1/src/timeline.rsmodified+0 -12

Diff too large; view file

crates/ec-av1/src/tool_cache.rsadded+326 -0

Diff too large; view file

crates/ec-av1/src/transform.rsmodified+244 -169

Diff too large; view file

crates/ec-av1/src/warp.rsmodified+3 -3

Diff too large; view file

crates/ec-av1/src/wedge.rsmodified+8 -0

Diff too large; view file

crates/ec-av1/tests/aom_conformance.rsadded+452 -0

Diff too large; view file

crates/ec-av1/tests/data/fuzz/decode_stream-cfl-ac-size.binadded+0 -0

Binary file changed

crates/ec-av1/tests/data/fuzz/decode_stream-film-grain-points.binadded+0 -0

Binary file changed

crates/ec-av1/tests/data/fuzz/decode_stream-mv-i16-range.binadded+0 -0

Binary file changed

crates/ec-av1/tests/data/fuzz/decode_stream-obu-frame-show-existing.binadded+0 -0

Binary file changed

crates/ec-av1/tests/data/fuzz/decode_stream-palette-pred-size.binadded+0 -0

Binary file changed

crates/ec-av1/tests/fuzz_regressions.rsadded+60 -0

Diff too large; view file

crates/ec-av1/tests/real_library.rsadded+339 -0

Diff too large; view file

crates/ec-av1/tests/worker_panic.rsadded+87 -0

Diff too large; view file

crates/ec-av1/tests/yuv422_dav1d.rsadded+239 -0

Diff too large; view file

crates/ec-cc/Cargo.tomladded+13 -0

Diff too large; view file

crates/ec-cc/src/ccdata.rsadded+171 -0

Diff too large; view file

crates/ec-cc/src/cea608.rsadded+457 -0

Diff too large; view file

crates/ec-cc/src/cea708.rsadded+446 -0

Diff too large; view file

crates/ec-cc/src/extract.rsadded+606 -0

Diff too large; view file

crates/ec-cc/src/lib.rsadded+63 -0

Diff too large; view file

crates/ec-cc/src/synth.rsadded+297 -0

Diff too large; view file

crates/ec-cc/tests/captions.rsadded+233 -0

Diff too large; view file

crates/ec-cc/tests/streams.rsadded+338 -0

Diff too large; view file

crates/ec-core/src/color.rsmodified+77 -2

Diff too large; view file

crates/ec-core/src/frame.rsmodified+33 -3

Diff too large; view file

crates/ec-core/src/lib.rsmodified+2 -2

Diff too large; view file

crates/ec-core/src/registry.rsmodified+105 -5

Diff too large; view file

crates/ec-core/src/timebase.rsmodified+5 -1

Diff too large; view file

crates/ec-dnxhd/Cargo.tomladded+15 -0

Diff too large; view file

crates/ec-dnxhd/examples/bench.rsadded+30 -0

Diff too large; view file