• Debugging Widevine L3 at the C++ CDM ABI level, disproving a dead-end rewrite, and pivoting to hardware-backed Apple FairPlay Streaming on Apple Silicon.

A few days ago, I hit one of those deceptively simple bugs that pulls you straight down the systems-programming rabbit hole: protected VOD streams in Kodi on my Apple M4 Mac were playing crisp video with completely dead silence.

No crash. No error dialog. Just silent video—while other titles in the exact same catalog played with full audio.

What started as a quick log check turned into a deep dive across HTTP/2 proxy headers, Widevine L3 security robustness tiers, C++ Content Decryption Module (CDM) ABI probing, and macOS native Apple FairPlay Streaming (AVFoundation + AVContentKeySession). Here is the full engineering breakdown of what actually went wrong, how a 60-line C++ probe saved days of wasted effort, and how I engineered a 160 KB native Swift player that brought back 1080p HD video, multi-language audio, and embedded subtitles seamlessly inside my Kodi workflow.

1. The Clue Hidden in kodi.log

Opening Kodi's debug log immediately ruled out macOS CoreAudio or speaker routing. inputstream.adaptive wasn't failing to output sound—it wasn't even opening an audio stream.

GetStreamIds() returned a single stream ID (1001, H.264 video). Scrolling up a few lines into the Widevine CDM initialization told the whole story:

[WV-CDM-Library] OnSessionKeysChange: KID <AUDIO_KID>, Status: 0, System code: 0 [WV-CDM-Library] OnSessionKeysChange: KID <VIDEO_KID>, Status: 0, System code: 0 License update successful ... Initializing stream with KID: <AUDIO_KID> [WV-CDM-Library] OnSessionKeysChange: KID <AUDIO_KID>, Status: 1, System code: 5 LogDecryptError: Decrypt failed with error code: 2 and KID: <AUDIO_KID> GetCapabilities: Single decrypt failed, secure path only 

Look closely at what Widevine is telling inputstream.adaptive:

  • Error code 2 in cdm::Status is kNoKey, paired with KeyStatus::kInternalError (1) and System code: 5.
  • That combination happens when the license server marks a content key as SW_SECURE_DECODE (requiring decryption and decoding inside the CDM's secure path) rather than SW_SECURE_CRYPTO (allowing the host to call cdm->Decrypt() and decode decrypted frames externally via FFmpeg).
  • On titles that did have audio, the Widevine license granted SW_SECURE_DECODE for video and SW_SECURE_CRYPTO for audio (GetCapabilities: Single decrypt possible).
  • On the silent titles, the license locked both video and audio to SW_SECURE_DECODE.

Kodi's inputstream.adaptive bridges SW_SECURE_DECODE for video via DecryptAndDecodeVideo(), which lets the Widevine CDM decode H.264 internally and hand back YUV frames. For audio, however, inputstream.adaptive has no secure audio decoder path (xbmc/inputstream.adaptive#2013)—so it silently drops every audio track in the manifest.

(Side discovery while debugging the local add-on HTTP proxy along the way: modern CDNs like Fastly return lowercase HTTP/2 headers like content-length and content-encoding, which can silently slip past case-sensitive header-stripping filters and trigger curl error 56 when rewriting DASH manifests on the fly.)

2. The 5-Minute C++ Probe That Saved Days of Wasted Work

My first instinct was: "Why wait for Kodi 22/23? content_decryption_module.h defines InitializeAudioDecoder() and DecryptAndDecodeSamples() right alongside the video methods. I can patch inputstream.adaptive on macOS to decode SW_SECURE_DECODE audio inside Widevine CDM and feed raw PCM packets to Kodi's demuxer."

Before touching cmake or compiling a single line of inputstream.adaptive, I decided to verify the core assumption directly against the installed desktop Widevine CDM binary (libwidevinecdm.dylib, ContentDecryptionModule_10).

I wrote a minimal 60-line C++ probe using dlopen + CreateCdmInstance to test both decoders directly:

// Baseline: verify H.264 video decoder works inside the desktop CDM cdm::VideoDecoderConfig_2 vcfg{}; vcfg.codec = cdm::kCodecH264; vcfg.profile = cdm::kH264ProfileMain; vcfg.format = cdm::kI420; vcfg.coded_size = {960, 540}; vcfg.encryption_scheme = cdm::EncryptionScheme::kCenc; printf("VideoDecoder(H264): %d\n", (int)cdm->InitializeVideoDecoder(vcfg)); // Probe every audio codec enum (AAC, Vorbis, etc.), bit depth, and encryption scheme uint8_t aac_asc[] = {0x11, 0x90}; // AAC-LC, 48kHz, Stereo for (int codec = 0; codec <= 5; codec++) { for (int bits : {16, 32, 0}) { for (auto enc : {cdm::EncryptionScheme::kCenc, cdm::EncryptionScheme::kUnencrypted}) { cdm::AudioDecoderConfig_2 acfg{}; acfg.codec = static_cast<cdm::AudioCodec>(codec); acfg.channel_count = 2; acfg.bits_per_channel = bits; acfg.samples_per_second = 48000; acfg.extra_data = aac_asc; acfg.extra_data_size = sizeof(aac_asc); acfg.encryption_scheme = enc; auto st = cdm->InitializeAudioDecoder(acfg); if (st != cdm::kInitializationError) { printf("AudioDecoder codec=%d -> %d\n", codec, (int)st); } } } } 

The output was immediate and decisive:

VideoDecoder(H264): 0 (kSuccess) Audio probe done. (Every AudioDecoder config returned 3 = kInitializationError) 

Checking the CDM's manifest.json confirmed why:

"x-cdm-codecs": "vp8,vp09,avc1,av01" 

Google's closed-source desktop Widevine CDM binary on macOS does not ship an audio decoder at all. Desktop browsers always rely on SW_SECURE_CRYPTO for audio and decode externally. Even if you compiled Kodi 23's experimental secure-audio pull requests today, libwidevinecdm.dylib itself refuses InitializeAudioDecoder() with kInitializationError.

That 5-minute probe saved an entire weekend of building a doomed C++ patch.

3. The Architectural Pivot: Embracing Native Apple FairPlay Streaming

Stepping back from DASH + Widevine L3 forced a better question: Why fight a software-only Widevine L3 stack on an Apple Silicon Mac when macOS ships a full hardware-backed DRM stack natively?

Every modern Apple Silicon Mac includes Apple FairPlay Streaming (FPS) wired directly into AVFoundation, AVKit, and the Secure Enclave / hardware media engines. When a streaming service supports HLS + FairPlay:

  • Decryption and decoding of both video and audio happen natively in hardware (zero software L3 audio limitations).
  • Multi-language audio tracks (#EXT-X-MEDIA:TYPE=AUDIO) and subtitles (#EXT-X-MEDIA:TYPE=SUBTITLES) work out of the box inside AVPlayerView.
  • Video resolution isn't restricted to desktop Widevine L3's 540p cap—full 1080p HD streams play natively.

How AVContentKeySession Handles FairPlay in Swift

Using Apple's AVContentKeySessionDelegate, the entire hardware FairPlay handshake takes fewer than 60 lines of Swift:

final class FairPlayKeyDelegate: NSObject, AVContentKeySessionDelegate, @unchecked Sendable { private let certData: Data private let licenseURL: URL private let headers: [String: String] func contentKeySession(_ session: AVContentKeySession, didProvide keyRequest: AVContentKeyRequest) { handleKeyRequest(keyRequest) } func contentKeySession(_ session: AVContentKeySession, didProvideRenewingContentKeyRequest keyRequest: AVContentKeyRequest) { handleKeyRequest(keyRequest) } private func handleKeyRequest(_ keyRequest: AVContentKeyRequest) { guard let skd = keyRequest.identifier as? String else { return } let contentId = Data(skd.utf8) // Ask macOS FairPlay to generate a hardware-signed SPC (Server Playback Context) keyRequest.makeStreamingContentKeyRequestData( forApp: certData, contentIdentifier: contentId, options: nil ) { [weak self] spcData, error in guard let self = self, let spcData = spcData, error == nil else { keyRequest.processContentKeyResponseError(error ?? NSError(domain: "FPS", code: 1)) return } self.fetchCKC(spcData: spcData, keyRequest: keyRequest) } } private func fetchCKC(spcData: Data, keyRequest: AVContentKeyRequest) { // POST base64-encoded SPC to the streaming service's FairPlay license endpoint, // decode the returned Content Key Context (CKC), and feed it back to AVFoundation: // let response = AVContentKeyResponse(fairPlayStreamingKeyResponseData: ckcData) // keyRequest.processContentKeyResponse(response) } } 

Compiled directly with swiftc -O -framework Cocoa -framework AVFoundation -framework AVKit -framework IOKit, the standalone ARM64 binary weighs 160 KB with zero third-party dependencies.

4. Seamless Hybrid Integration with Kodi

Instead of replacing Kodi's built-in player across the board, I wired the Swift helper into the add-on's playback layer as a clean macOS-only fallback:

Hybrid Kodi + Native macOS FairPlay Playback Architecture

A few subtle systems details make the handoff between Python (Kodi) and Swift (native player) feel completely seamless:

  • Secure ephemeral IPC (0600): Auth headers and session tokens are never passed via CLI arguments (where ps aux could expose them). Python writes a temporary JSON file with mode 0600, spawns the Swift binary with the path, and the Swift process immediately unlinks the file upon reading it.
  • Dismissing Kodi's busy dialog cleanly: Before launching the native window, the plugin resolves Kodi's setResolvedUrl with a silent 1-frame dummy audio file (dummy.wav). That stops Kodi's loading spinner immediately and avoids Kodi's "One or more items failed to play" modal while the native player runs.
  • Cooperative monitoring & focus handoff: The Python plugin polls proc.poll() alongside Kodi's monitor.abortRequested(). When the user closes the player (Esc or Q), Swift prints POSITION=<sec> DURATION=<sec> to stdout and explicitly reactivates org.xbmc.kodi via NSWorkspace.

5. The Real-World Polish: 3 macOS Edge Cases I Had to Fix

Getting the first frame on screen is only 70% of building a usable media player. Watching full-length movies immediately surfaced three classic macOS systems bugs:

1. The Display Dimmed Mid-Movie (IOKit Power Assertions)

A standalone Swift NSApplication hosting AVPlayerView does not automatically inhibit macOS's idle display dimmer the way Safari or QuickTime does. The fix is to observe AVPlayer.timeControlStatus and hold an IOKit power assertion only while actively playing:

private func setDisplaySleepPrevented(_ prevent: Bool) { if prevent, sleepAssertionID == 0 { var id: IOPMAssertionID = 0 let res = IOPMAssertionCreateWithName( kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), "FairPlay Video Playback" as CFString, &id ) if res == kIOReturnSuccess { sleepAssertionID = id } } else if !prevent, sleepAssertionID != 0 { IOPMAssertionRelease(sleepAssertionID) sleepAssertionID = 0 } } 

2. AVPlayerView Swallowed Arrow Keys and Double-Toggled Space

Overriding NSWindow.keyDown didn't work for ← / → seeks because AVPlayerView acts as first responder and consumes key events before they bubble up. Switching to NSEvent.addLocalMonitorForEvents(matching: .keyDown) fixed seeking—but introduced a subtle conflict where pressing Space triggered both my monitor and AVPlayerView's built-in toggle (pausing and immediately unpausing), and strict event.window === win checks broke in macOS fullscreen spaces.

Two fixes solved it cleanly:

  • Subclass AVPlayerView with empty keyDown, keyUp, and performKeyEquivalent overrides so the local NSEvent monitor has single ownership of keyboard shortcuts.
  • Add a 1.5-second accumulative pendingSeekTarget window so rapid taps (→, →, →) stack smoothly (+10s → +20s → +30s) instead of racing asynchronous HLS keyframe seeks, paired with AVPlayerView.speeds (0.5x–4x using .spectral pitch preservation) and a translucent HUD overlay pill.

3. Bidirectional Resume Persistence

Because the native player runs outside Kodi's internal VideoPlayer, Kodi doesn't automatically track watch progress. Reading the add-on's local resume.db before launch, seeking to start_time on AVPlayerItem.status == .readyToPlay (with a Resumed MM:SS HUD toast), and writing the stopped timestamp back on exit—automatically clearing it once ≥95% watched—closed the loop completely.

6. Takeaways

  1. Test the binary before writing the patch. A 60-line C++ ABI probe against libwidevinecdm.dylib proved in five minutes that desktop Widevine has no audio decoder—preventing days of futile work trying to backport upstream secure-audio PRs.
  2. Lean into native platform stacks. Trying to force desktop software Widevine L3 on Apple Silicon fights the hardware. Pivoting to AVFoundation + Apple FairPlay unlocked hardware 1080p decoding, native multi-track audio, embedded subtitles, and lower battery drain in a 160 KB binary.
  3. Polish is systems engineering. Power assertions (IOKit), responder-chain input conflicts (AVPlayerView vs. NSEvent), async HLS seek accumulation, and ephemeral 0600 IPC are what turn a working prototype into something you actually enjoy using every day.