Skip to content

feat(audio): DTS:X keeps its heights, rendered to APAC - #755

Merged
superuser404notfound merged 6 commits into
superuser404notfound:mainfrom
kristofferR:feat/dtsx-object-audio
Oct 13, 2026
Merged

superuser404notfound merged 6 commits into
superuser404notfound:mainfrom
kristofferR:feat/dtsx-object-audio

Conversation

@kristofferR

Copy link
Copy Markdown
Contributor

Hi! This is the DTS:X patch asked for on the activator PR. It adds DTS:X to the objectAudioRendering route you built for TrueHD Atmos.

The problem

Apple TV can't bitstream DTS-HD either, so a DTS:X track goes through the channel bridge as its compatible 7.1. In DTS:X that 7.1 is a downmix: the encoder folds the four height channels, and any objects, into the floor channels. The heights are still audible, but from the wrong speakers.

How

Same shape as TrueHD Atmos, with the DTS-specific work kept out of the engine:

  • LibDTSX (kristofferR/LibDTSX, Apache-2.0) is modelled on LibTrueHD. It's harletty's dca crate behind a C API, shipped as a static DTSX.xcframework with the same slices, the same prelink step, a C harness and a Swift package, product DTSX.
    • Its API has LibTrueHD's shape and speaker codes: planar float channels, one speaker code or "object" per channel, and metadata updates with positions in LibTrueHD's room coordinates.
    • Inside it, every height and object fold the frame states is subtracted from the bed, so the bed, the four fixed heights and any objects can be rendered side by side without playing twice.
    • DTS:X object positions are physical angles. LibDTSX projects them onto the room's walls through the speaker angles, so AllocentricPanner needs no change.
  • In the engine, DTSXObjectAudioDecoder is a speaker mapping next to TrueHDObjectAudioDecoder. SpatialAudioBridge, the renderer, the limiter, the APAC encoder and the Atmos activator are unchanged.
  • Which tracks: FFmpeg recognises only two of DTS:X's markers. It labels some DTS:X plain "DTS-HD MA", for example a D4 trailer with five moving objects. So every 48 kHz DTS-HD MA track is offered.
    • LibDTSX decides on the track's first three frames. The engine reads them through Demuxer.peekPackets, so the check costs no extra read and no seek.
    • A track without DTS:X keeps audioBridgeMode exactly as today.
    • With rendering on, the automatic pick prefers a DTS:X-labelled track within its language, as it does for TrueHD Atmos. prefersTrueHDAtmos became prefersObjectAudio.
  • Seeks: a DTS-HD MA frame is lossless only against the core decoder's history, so the first frame after a seek decodes distorted.
    • Across 120 seeks into five streams, its error was a median 2.7 dB below the signal.
    • LibDTSX decodes the first two frames after a start or seek without output. The bridge fills those 21 ms with silence, and the output then converges to bit-identical within about ten frames.

Tested

  • Against SpatialAudioBridge's DTS:X renderer, 7.1.4:
    • 8 Mile, The Bourne Identity and the DTS:X Object Emulator demo (bed plus four heights) land every channel on its own speaker, bit for bit the same as SpatialAudioBridge.
    • Independence Day, labelled "DTS:X IMAX", carries two static front objects at ±34.5° and 12° up. Its render points the sound the same way within 0.07° (median of energy-weighted 200 ms windows; 90th percentile 0.39°).
    • The D4 trailer's five moving objects: within 0.23° (90th percentile 2.3°).
    • The floor channels correlate at 1.0000. The ceiling's share of the energy is 0.1–0.2 points lower, because the panner's top speakers sit at the room's corners.
  • Apple TV 4K (2nd gen), tvOS 27.2, Jellyfin direct play, through a small test host built from Examples/MinimalPlayer:
    • 8 Mile, The Bourne Identity and Independence Day played as APAC with the soundbar showing Atmos, from mid-film and across seeks (back to playing in 0.7–2.2 s).
    • Independence Day flags no audio track as default. The automatic pick chose its DTS:X track over the two AC-3 commentaries.
    • Arrival, plain DTS-HD MA, was refused on its first frame and played through the channel bridge, showing PCM.
  • New tests: DTSXObjectMetadataMappingTests, and DTSXSampleTests behind AE_DTSX_SAMPLE, AE_DTSX_ALTERNATE_SAMPLE and AE_DTS_HD_MA_SAMPLE (FATE's dts/master_audio_7.1_24bit.dts), like TrueHDAtmosSampleTests. The routing and track-preference tests got DTS cases.
  • Not tested: iOS and AirPods, 96 kHz DTS:X (never offered), and DTS:X on a lossy DTS-HD carrier (refused).

Happy to change anything, split it up or answer questions!

First stage of DTS:X with heights. LibDTSX (the `dca` crate behind a C
API, prebuilt like LibTrueHD) decodes DTS:X on lossless DTS-HD Master
Audio and does the DTS-specific work itself: it subtracts every height
and object the encoder folded into the compatible 7.1 bed, and places
DTS:X's angular object positions in LibTrueHD's room coordinates. Its
API has LibTrueHD's shape and speaker codes, so
DTSXObjectAudioDecoder is a speaker mapping next to
TrueHDObjectAudioDecoder and the renderer is unchanged. Nothing is wired
into playback yet.

`verdict(feeding:)` answers on a stream's head whether it is DTS:X the
library renders: FFmpeg names only two of DTS:X's markers, so its label
cannot decide.
With LoadOptions.objectAudioRendering = .apac(layout), a 48 kHz DTS-HD
Master Audio track now goes through SpatialAudioBridge on
DTSXObjectAudioDecoder, the same renderer, limiter and APAC encoder
TrueHD Atmos uses, instead of the channel bridge, which carried DTS:X's
compatible 7.1 with the heights folded into the floor.

FFmpeg labels some DTS:X plain DTS-HD MA (a D4 trailer with five moving
objects), so every DTS-HD MA track is a candidate, and LibDTSX decides
on its first three frames before the bridge is built. They are read
through Demuxer.peekPackets, which holds them for the producer: no extra
read, no seek. A refusal keeps audioBridgeMode with its lossless 7.1;
lossy DTS is never offered. The decoder handle that gave the verdict is
reset and handed to the bridge.

Verified on macOS 27 with the sample tests: the DTS:X Object Emulator
renders every bed and height channel bit for bit onto its own speaker
and bridges to contiguous APAC; the D4 trailer's objects ramp across
1002 updates; FATE's plain master_audio_7.1_24bit.dts is refused. On an
Apple TV 4K (tvOS 27.2) over Jellyfin, 8 Mile, The Bourne Identity and
Independence Day (7.1.4+2) played as APAC with the receiver showing
Atmos, through seeks; Arrival (plain DTS-HD MA) was refused on its first
frame and showed PCM.
With objectAudioRendering on, a track FFmpeg labels DTS:X (or DTS:X
IMAX) keeps its heights the way TrueHD Atmos does, so the automatic
audio pick prefers it the same way: within the preferred language, or
in place of the default track within that track's language, never a
commentary, never over an override. `prefersTrueHDAtmos` becomes
`prefersObjectAudio`.

TrackInfo.codec is the decoder's name, which for DTS is `dca`, not
`dts`. Independence Day flags no audio track as default and the probe's
best stream is an AC-3 commentary; matching on `dts` left that
commentary playing on the Apple TV. The test now builds its tracks the
way the probe reports them.
README names DTS:X next to TrueHD Atmos in the Atmos row and the
comparison table, and the license section gets a LibDTSX paragraph:
Apache-2.0 for the wrapper and for the dca crate it compiles in.
formats.md describes the route: what LibDTSX does to the bed and to
object positions, which tracks are offered and why FFmpeg's label is
not enough, the frames that prime the decoder after a seek, the
placement against SpatialAudioBridge's renderer, and the receiver.
The automatic pick ranked TrueHD Atmos, and now DTS:X, ahead of the
default track whenever objectAudioRendering was on, but the route
itself refuses below OS 26, where the APAC encoder API is missing.
There a host that sets the option on every OS it supports had its
default track replaced for a channel bridge it would have got anyway.
The preference now also needs ObjectAudioRendering.isAvailable.
Now that kristofferR/LibDTSX is public, Package.resolved carries its
1.0.0 pin and a clean checkout resolves. The DTS:X sample, mapping,
routing and preference tests pass against the published xcframework.
@kristofferR

Copy link
Copy Markdown
Contributor Author

Btw, I'll gladly transfer LibDTSX to you like with LibTrueHD!

I don't need to manage two different libs that does the same thing 😛

@superuser404notfound

Copy link
Copy Markdown
Owner

Thanks a lot, this is great work, and the measurements against SpatialAudioBridge make it easy to trust.

Yes please on the transfer, same as LibTrueHD: transfer kristofferR/LibDTSX to superuser404notfound and I'll rebuild the xcframework from source there and cut the release the engine pins.

One thing I'll fix on that side before merging: build.sh keeps rust_eh_personality local in the prelinked object. That is the #752 trap. LibTrueHD 2.2.1 exports it weak (weaken in its build.sh, plus _rust_eh_personality in the exported symbols list) so it coalesces with LibDovi's copy. A third, local copy would be another personality routine in the image, and a host with its own Objective-C and C++ fails to link again with "Too many personality routines". I'll port that step into LibDTSX after the transfer.

On the engine side I'll rebase this onto main (the conflicts are only CHANGELOG / Package.swift / Package.resolved, but #741 renamed finishInput to releaseHeldBlocks on the decoder protocol), switch the pin to the transferred repo and then merge.

@andreencar

Copy link
Copy Markdown
Contributor

I reviewed this at c53cf053d3b34423b86dd7d8c9419a8c8a83938a, including the pinned LibDTSX 1.0.0 (d459e44e634b5b98884959017141309b381650dd). I found a new recovery/timing bug, and independently reproduced the linker issue already noted above. Both fixes belong in LibDTSX; below are suggested changes and reproductions.

New: repeated damaged sections inflate the input timeline

In Framer::take, the average AU size is framed_bytes / frames, but frames includes estimated missing AUs while framed_bytes only counts successfully framed bytes. After the first gap, the average is biased downward; subsequent gaps are converted into too many missing AUs.

The resulting input_frame_offset is too large. The engine uses this offset for gap filling and APAC timing, so subsequent audio is delayed until the decoder is reset. This is additional delay beyond the actual damaged interval.

Deterministic reproduction: take the first complete AU of the DTS Sound Unbound Callout 11.1 sample (2184 bytes, 512 samples at 48 kHz), repeat it 500 times, replace AUs 100..<150 and 250..<300 with equal-length 0xA5 bytes, and feed 4096-byte chunks. All AUs have the same size, so variable-size estimation uncertainty cannot explain this result.

Result Expected Actual
Discontinuity resumption AU indices, including the two priming AUs [2, 152, 302] [2, 152, 315]
End of input timeline, sample frames 256000 262656
Additional delay 0 6656 / 48000 = 138.67 ms

Reproduced against the published macOS binary through its C API, the PR's Swift adapter, and the Rust source. Suggested fix: keep an independent count of successfully framed AUs for the average, leaving frames as the source timeline ordinal. Reset the new counter alongside framed_bytes.

Suggested LibDTSX timing patch
diff --git a/src/framer.rs b/src/framer.rs
index b35faa0..20cc659 100644
--- a/src/framer.rs
+++ b/src/framer.rs
@@ -50,6 +50,8 @@ pub struct Framer {
     consumed: u64,
     pushed: u64,
     frames: u64,
+    /// Successfully framed AUs; unlike `frames`, this excludes estimates for damaged bytes.
+    framed_count: u64,
     framed_bytes: u64,
     skipped: u64,
     /// Bytes skipped since create() before the first frame was found (survives reset).
@@ -70,6 +72,7 @@ impl Framer {
         self.consumed = 0;
         self.pushed = 0;
         self.frames = 0;
+        self.framed_count = 0;
         self.framed_bytes = 0;
         self.skipped = 0;
         self.estimated = false;
@@ -215,9 +218,9 @@ impl Framer {
     fn take(&mut self, len: usize, core_samples: u32) -> AuInfo {
         let mut estimated_before = 0;
         let skipped_before = std::mem::take(&mut self.skipped);
-        if skipped_before > 0 && self.frames > 0 {
+        if skipped_before > 0 && self.framed_count > 0 {
             // Damage between frames: estimate the frames it held from the average frame size.
-            let average = self.framed_bytes as f64 / self.frames as f64;
+            let average = self.framed_bytes as f64 / self.framed_count as f64;
             estimated_before = (skipped_before as f64 / average).round() as u64;
             self.estimated |= estimated_before > 0;
         }
@@ -230,6 +233,7 @@ impl Framer {
             skipped_before,
         };
         self.frames += 1;
+        self.framed_count += 1;
         self.framed_bytes += len as u64;
         self.start += len;
         self.consumed += len as u64;
Runnable regression test

Save as tests/timeline_regressions.rs in LibDTSX:

//! Local PR review: recovery must not manufacture extra time after repeated damage.
//! Run with DTSX_SAMPLE pointing at a standard DTS:X elementary stream.
use dtsx::{*, types::*};
use std::ptr;

#[test]
#[ignore = "requires a local DTSX_SAMPLE; repeats one complete AU to make gap duration exact"]
fn repeated_equal_sized_gaps_do_not_inflate_the_input_timeline() {
    let data = std::fs::read(std::env::var_os("DTSX_SAMPLE").expect("set DTSX_SAMPLE")).unwrap();
    let header = dca::parse_header(&data).unwrap();
    let size = header.frame_size + dca::exss_substream_size(&data[header.frame_size..]).unwrap();
    let mut stream = data[..size].repeat(500);
    // Every AU is the same size: the decoder can infer exactly 50 lost AUs at each gap.
    for (start, end) in [(100, 150), (250, 300)] {
        stream[start * size..end * size].fill(0xA5);
    }
    let decoder = dtsx_decoder_create();
    assert!(!decoder.is_null());
    let mut end = 0;
    let mut resumed = Vec::new();
    for chunk in stream.chunks(4096) {
        assert_eq!(unsafe { dtsx_decoder_push(decoder, chunk.as_ptr(), chunk.len(), NO_PTS) }, OK);
        loop {
            let mut b = Block {
                sample_rate: 0, frame_count: 0, channel_count: 0, presentation: 0, flags: 0,
                access_unit_frames: 0, pts: 0, pts_au_index: 0, layout_serial: 0,
                sample_position: 0, input_access_unit: 0, input_frame_offset: 0,
                channels: ptr::null(), speakers: ptr::null(), metadata: ptr::null(),
            };
            let status = unsafe { dtsx_decoder_pull(decoder, &mut b) };
            if status == NEED_MORE_DATA { break; }
            assert_eq!(status, OK);
            end = b.input_frame_offset + u64::from(b.frame_count);
            if b.flags & BLOCK_DISCONTINUITY != 0 { resumed.push(b.input_access_unit); }
        }
    }
    unsafe { dtsx_decoder_destroy(decoder); }
    assert_eq!(resumed, vec![2, 152, 302], "each gap should be followed by two priming AUs");
    assert_eq!(end, 500 * 512, "recovering damage must not create additional source time");
}

Sample: Demolandia DTS demos, Sound Unbound Callout 11.1, download entry. Extract the audio without transcoding, for example:

ffmpeg -i /path/to/callout.mkv -map 0:a:0 -c:a copy -f dts /path/to/dtsx-callout.dts
DTSX_SAMPLE=/path/to/dtsx-callout.dts cargo +1.98.1 test --release --locked --test timeline_regressions -- --ignored

My extracted stream's SHA-256: 0fea804f92c4bebbaf490e2e5e32db5555c096eb157417634f6f3d2ea7330e11.

The test fails before the patch ([2, 152, 315] versus [2, 152, 302]) and passes after it, including the final timeline assertion. Five existing unit tests and seven existing API tests also passed with the patch. I excluded the existing test that hardcodes AU 4451 because this different sample has only 3977 AUs; it is not counted as passing. Source tests used Rust 1.98.1 rather than changing the repository's toolchain pin; the published binary independently exhibits the same bug.

Already identified: mixed Objective-C/C++ host link failure

This confirms the maintainer's existing finding, rather than reporting a second new discovery. A host exercising both Objective-C and C++ exceptions links and runs with LibDovi 2.1.0 + already-fixed LibTrueHD 2.3.0. Adding the published DTSX binary fails with:

ld: Too many personality routines for compact unwind to encode. Found routines:
  '_rust_eh_personality'
  '_rust_eh_personality'
  '___objc_personality_v0'
  '___gxx_personality_v0'

Using fixed TrueHD isolates the additional DTSX personality from the PR's older TrueHD dependency.

Suggested fix: port the weaken() helper from LibTrueHD, preserving its MIT attribution/license, then make these changes in LibDTSX build.sh:

-echo '_dtsx_*' >"$STAGE_DIR/exported_symbols"
+printf '%s\n' '_dtsx_*' '_rust_eh_personality' >"$STAGE_DIR/exported_symbols"

     strip -S "$work/DTSX.o"
+    weaken "$work/DTSX.o" _rust_eh_personality
     libtool -static -o "$work/$LIB" "$work/DTSX.o" 2>/dev/null

Both steps are needed: merely exporting a strong definition risks duplicate symbols; keeping it local prevents coalescing. Rebuild all slices, verify a weak external _rust_eh_personality in each architecture, then publish/re-pin the corrected dependency. I validated a local arm64 macOS rebuild with this change: the previously failing mixed host now links and executes successfully. This fix validation used Rust 1.98.1 and covers macOS arm64, not a fresh validation of all Apple slices.

Minimal mixed-host regression reproduction

Save these three files together:

mixed-host.c:

#include "truehd_atmos.h"
#include "dovi.h"
#ifdef WITH_DTSX
#include "dtsx.h"
#endif
int objc_exceptions(void);
int cpp_exceptions(void);
int main(void) {
    TrueHDAtmosDecoder *t=truehd_atmos_decoder_create(0);
    truehd_atmos_decoder_destroy(t);
    dovi_rpu_free(0);
#ifdef WITH_DTSX
    DTSXDecoder *d=dtsx_decoder_create();
    dtsx_decoder_destroy(d);
#endif
    return objc_exceptions() + cpp_exceptions() == 2 ? 0 : 1;
}

objc-exceptions.m:

#import <Foundation/Foundation.h>
int objc_exceptions(void) {
    @try { @throw [NSException exceptionWithName:@"Review" reason:@"test" userInfo:nil]; }
    @catch (NSException *e) { return e != nil; }
}

cpp-exceptions.cpp:

extern "C" int cpp_exceptions(void) {
    try { throw 1; } catch (int value) { return value; }
}

Set the three paths to the macOS slice directories (TrueHD 2.3.0, Dovi 2.1.0, and DTSX 1.0.0 respectively):

TRUEHD=/path/to/TrueHD.xcframework/macos-arm64_x86_64
DOVI=/path/to/Dovi.xcframework/macos-arm64_x86_64
DTSX=/path/to/DTSX.xcframework/macos-arm64_x86_64

link_host() {
    clang -arch arm64 -O0 -fexceptions -fobjc-exceptions -mmacosx-version-min=15.0 \
        -I"$TRUEHD/Headers/TrueHD" -I"$DOVI/Headers" -I"$DTSX/Headers/DTSX" \
        mixed-host.c objc-exceptions.m cpp-exceptions.cpp \
        -framework Foundation -lc++ "$TRUEHD/libtruehd_atmos.a" "$DOVI/libdovi.a" "$@"
}
link_host -o baseline && ./baseline
link_host -DWITH_DTSX "$DTSX/libdtsx.a" -o with-dtsx && ./with-dtsx

Baseline exits 0; the published DTSX archive fails to link. Pointing DTSX at the corrected archive makes the second command link and exit 0 as well. This is useful as a packaging regression test alongside ordinary Swift tests, which do not necessarily exercise all four personalities.

For context, the normal sample path looked good: 44 selected engine tests passed, including our adapted independent 7.1.4 PCM comparison (maximum error 0), chunking/reset, APAC cadence, and native MKV load/reload checks. The damaged-stream regression is an additional failing case, separate from those passing tests. No physical-device playback validation is claimed here.

@kristofferR

Copy link
Copy Markdown
Contributor Author

I'll leave the fixes up to you @superuser404notfound , I've initiated the transfer now. 🙂

superuser404notfound pushed a commit that referenced this pull request Oct 13, 2026
Review follow-ups on #755:

- On a resume the verdict peeked the file head, and step 8's seek then
  dropped those packets: one wasted range read per start onto any 48 kHz
  DTS-HD MA track. The demuxer is now put at the first producer's start
  before the peek (`seekToInitialProducerStart`, step 8's seek moved into
  a helper), and step 8 skips its seek when that already happened, so
  the peeked packets are the producer's first ones. LibDTSX decides
  mid-stream as well (aetherctl serve --start-position 40: verdict 1 ms,
  audio gate gapMs=0.0; plain DTS-HD MA refused at 8 s, channel bridge
  opens on target).
- The peek holds every stream's packets until the producer reads them,
  so it is capped at 24 MiB as well as 512 packets.
- A stream that decodes at a rate other than 48 kHz is refused on its
  first block instead of failing every block in the bridge.
- TFC sits on the front-top row (0.5, 0.25, 1) as in the TrueHD map
  since #742; LSD/RSD map to the side speakers like TrueHD's.
- Docs: the angular figures were measured before #742, the 21 ms after
  a start or seek are skipped rather than filled with silence, the
  1200-packet silence report is 12.8 s of DTS, and the OS < 26 pick
  change for TrueHD Atmos gets a Changed line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound
superuser404notfound merged commit 5fe5ee9 into superuser404notfound:main Oct 13, 2026
4 checks passed
superuser404notfound pushed a commit that referenced this pull request Oct 13, 2026
The repository moved from kristofferR to superuser404notfound. 1.0.1
exports rust_eh_personality weak, so a host with Objective-C and C++
links next to LibDovi and LibTrueHD again (#752), and stops repeated
damaged sections from pushing the input timeline ahead of the source,
which delayed the audio after a second gap until a reset (found by
@andreencar). Package URL, docs and changelog follow the move.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged in b84557c, pinned to LibDTSX 1.0.1 from its new home. Thanks @kristofferR for the library and the transfer.

@andreencar, thank you for the review, the timeline bug was real and your diagnosis was exact:

  • Repeated gaps: fixed in LibDTSX 3b851cf as suggested, with a separate count of framed AUs carrying the average. The regression test (repeated_gaps_do_not_add_time_to_the_timeline) builds the stream from one repeated AU of the Object Emulator with gaps at 100..<150 and 250..<300, so it runs with the sample verify.sh already uses. It failed with your numbers ([2, 152, 315]) before the fix and passes after it, ending at 500 × 512. An undamaged stream renders bit-identical to 1.0.0.
  • Personality routine: 08b57ee exports rust_eh_personality weak and checks it in every slice and arch; harness/verify.sh links against a second Rust library in an Objective-C and C++ host in both orders and runs a catch in all four runtimes, which the 1.0.0 binary fails with the error you quoted.
  • The test that hard-coded AU 4451 now searches the sample for the first AU that is pending on entry (ab123c1), so it no longer depends on one encode.

brandomoore added a commit to tresby/Plozz that referenced this pull request Oct 17, 2026
Integrate AetherEngine 7.36.0 while preserving the existing playback corrections. Use the shared TrueHD Atmos and DTS:X setting, retain saved profile preferences, and bundle the decoder notices and independently reviewed translations.

Refs superuser404notfound/AetherEngine#744
Refs superuser404notfound/AetherEngine#755

Copilot-Session: 1f0d34d4-4cfc-49cc-85b9-bf4111955fa1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants