audio: implement the AJM Opus decoder #858

Manually merged
github merged 2 commits from gh-pr/858/head into gh-pr/858/base 2026-11-26 09:35:18 +00:00
Owner

@⁠joaodiaslobo on GitHub · 2026-09-26 23:06 UTC · original
joaodiaslobo:feat/ajm-opus → main · +218 −141 · 2 files · 2 commits · merged 2026-09-27 11:53 UTC

The AJM Opus decoder was a placeholder: it produced silence instead of decoding. Titles whose audio goes through it have no sound.

Gris (PPSA09804, #823) is affected: a Unity title whose audio decodes Opus through AJM, so all menu and gameplay audio is silent. Its cutscenes have sound because AvPlayer decodes through FFmpeg and never reaches AJM.

src/libs/ajm/opus_decoder.h implements the decoder over the vendored FFmpeg, following aac_decoder.h and reusing AjmConvertFfmpegFrame.

Gris now has correct audio in menus and throughout gameplay. Tested on Windows with clang-cl:

https://github.com/user-attachments/assets/9cac0dad-4741-451f-98fc-f1948f156099

**@⁠joaodiaslobo** on GitHub · 2026-09-26 23:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858) `joaodiaslobo:feat/ajm-opus` → `main` · +218 −141 · 2 files · 2 commits · merged 2026-09-27 11:53 UTC The AJM Opus decoder was a placeholder: it produced silence instead of decoding. Titles whose audio goes through it have no sound. Gris (PPSA09804, #823) is affected: a Unity title whose audio decodes Opus through AJM, so all menu and gameplay audio is silent. Its cutscenes have sound because AvPlayer decodes through FFmpeg and never reaches AJM. `src/libs/ajm/opus_decoder.h` implements the decoder over the vendored FFmpeg, following `aac_decoder.h` and reusing `AjmConvertFfmpegFrame`. Gris now has correct audio in menus and throughout gameplay. Tested on Windows with clang-cl: https://github.com/user-attachments/assets/9cac0dad-4741-451f-98fc-f1948f156099
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:35:17 +00:00
github manually merged commit 05e2d672bb into gh-pr/858/base 2026-11-26 09:35:18 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 23:15 UTC · original · edited 2026-09-27 00:28 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 1309eec6-a6a6-4c79-a9d8-cfeb6897bafb

📥 Commits

Reviewing files that changed from the base of the PR and between a14dc7787100388e5f651f541101f9b45ea4111d and 3eedb40721.

📒 Files selected for processing (1)
  • src/libs/ajm/opus_decoder.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The AJM Opus decoder now uses FFmpeg instead of emitting silent frames. It validates initialization parameters, decodes length-prefixed Opus packets, handles gapless limits, and buffers decoded samples that do not fit in the output.

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 3eedb

No outstanding defect is established for the Opus decoder change; it is ready to merge after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 3eedb

The new decoder handles compressed audio that previously produced silence. Its packet processing can leave reported input consumption out of sync with decoder state after a partial failure, making recovery from malformed streams uncertain. The observed effect is confined to the existing audio-decoding path; broader attacker reach is not established.

Retained concerns

  • Medium · reliability · inferred: A packet can alter decoder or gapless state before a later decoding failure, while the externally reported consumed count still excludes that packet. Repetition from the reported offset can therefore replay input against changed state, undermining malformed-stream recovery.
Security review details

Security Blast Radius

  • inferred — The demonstrated attackable scope is an existing AJM Opus instance and its supplied bitstream, not a newly exposed service. Reachability from an upstream network or other untrusted-media entrypoint has not been established.

Security Findings and Attack Paths

  • inferred — A malformed packet that fails after partial processing can leave state advanced despite an unadvanced consumed count. The source supports a recovery inconsistency, not a verified remote exploit or cross-instance compromise.

Trust Boundaries and Controls

  • observed — AJM selects the codec centrally and locks instance decoding; Opus checks initialization, input bounds, and packet framing before native codec submission.

Resilience and Maintainability Implications

  • observed — With a fresh packet and zero output capacity, Opus reports partial input without consuming it; its pending-output path instead reports insufficient room. This limits the clarity of capacity-related recovery for callers.

Hardening Proposals

  • proposed — Define a packet commit point so reported consumption and codec, pending-output, and gapless state agree on every error path; distinguish output exhaustion from incomplete input.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: implementing the AJM Opus decoder.
Description check ✅ Passed The description directly explains the placeholder behavior, the FFmpeg-based implementation, the affected game, and the reported test result.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 23:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#issuecomment-5850809943) · edited 2026-09-27 00:28 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/858"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `1309eec6-a6a6-4c79-a9d8-cfeb6897bafb` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between a14dc7787100388e5f651f541101f9b45ea4111d and 3eedb40721b4218d09d6c2fd83e3c9d9651e5b66. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/ajm/opus_decoder.h` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The AJM Opus decoder now uses FFmpeg instead of emitting silent frames. It validates initialization parameters, decodes length-prefixed Opus packets, handles gapless limits, and buffers decoded samples that do not fit in the output. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"3eedb40721b4218d09d6c2fd83e3c9d9651e5b66" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `3eedb` <!-- final_review_risk_coverage:{"sourceCommitId":"3eedb40721b4218d09d6c2fd83e3c9d9651e5b66","coveredCommitId":"3eedb40721b4218d09d6c2fd83e3c9d9651e5b66","kind":"reviewed"} --> No outstanding defect is established for the Opus decoder change; it is ready to merge after normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `3eedb` The new decoder handles compressed audio that previously produced silence. Its packet processing can leave reported input consumption out of sync with decoder state after a partial failure, making recovery from malformed streams uncertain. The observed effect is confined to the existing audio-decoding path; broader attacker reach is not established. **Retained concerns** - **Medium · reliability · inferred:** A packet can alter decoder or gapless state before a later decoding failure, while the externally reported consumed count still excludes that packet. Repetition from the reported offset can therefore replay input against changed state, undermining malformed-stream recovery. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated attackable scope is an existing AJM Opus instance and its supplied bitstream, not a newly exposed service. Reachability from an upstream network or other untrusted-media entrypoint has not been established. **Security Findings and Attack Paths** - _inferred_ — A malformed packet that fails after partial processing can leave state advanced despite an unadvanced consumed count. The source supports a recovery inconsistency, not a verified remote exploit or cross-instance compromise. **Trust Boundaries and Controls** - _observed_ — AJM selects the codec centrally and locks instance decoding; Opus checks initialization, input bounds, and packet framing before native codec submission. **Resilience and Maintainability Implications** - _observed_ — With a fresh packet and zero output capacity, Opus reports partial input without consuming it; its pending-output path instead reports insufficient room. This limits the clarity of capacity-related recovery for callers. **Hardening Proposals** - _proposed_ — Define a packet commit point so reported consumption and codec, pending-output, and gapless state agree on every error path; distinguish output exhaustion from incomplete input. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 2 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: implementing the AJM Opus decoder. | | Description check | ✅ Passed | The description directly explains the placeholder behavior, the FFmpeg-based implementation, the affected game, and the reported test result. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 23:16 UTC · original
On src/libs/ajm/opus_decoder.h line 194 (outdated):

@@ -0,0 +1,409 @@
+#pragma once
+
+#include "common/logging/log.h"
+#include "libs/ajm/decoder.h"
+#include "libs/ajm/ffmpeg_decoder_common.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <vector>
+
+namespace Libs::Audio::Ajm {
+
+struct AjmDecOpusInitializeParameters {
+	uint32_t channel_num;
+	uint32_t sample_rate;
+	uint32_t mapping_family;
+};
+
+struct AjmSidebandDecOpusCodecInfo {
+	uint32_t frames_per_packet;
+};
+
+static_assert(sizeof(AjmDecOpusInitializeParameters) == 12);
+static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4);
+
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10;
+static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP    = 0;
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP      = 2;
+static constexpr size_t   AJM_DEC_OPUS_OPUS_HEAD_SIZE        = 19;
+// Each access unit is a little-endian 16-bit length followed by that many packet bytes.
+static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2;
+
+class AjmOpusDecoder final: public AjmDecoder {
+public:
+	AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding,
+	               uint64_t flags)
+	    : AjmDecoder(channels, sample_rate, encoding) {
+		(void)flags;
+		m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
+		if (m_codec == nullptr) {
+			LOGF("AJM Opus: avcodec_find_decoder failed\n");
+		}
+	}
+
+	~AjmOpusDecoder() override { Release(); }
+
+	AjmDecodeResult Initialize(const void* codec_parameters,
+	                           size_t      codec_parameters_size) override {
+		auto result = MakeResult();
+
+		if (codec_parameters == nullptr ||
+		    codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters);
+		if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH ||
+		    params->sample_rate == 0) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) {
+			LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n",
+			     params->mapping_family);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) {
+			LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n",
+			     params->channel_num);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		Release();
+		SetFormat(params->channel_num, params->sample_rate, m_sample_encoding);
+		m_mapping_family        = params->mapping_family;
+		m_total_decoded_samples = 0;
+		m_frames_per_packet     = 1;
+		m_is_initialized        = false;
+
+		if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+
+		m_is_initialized = true;
+
+		LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n",
+		     params->sample_rate, params->channel_num, params->mapping_family);
+
+		return MakeResult();
+	}
+
+	void Reset() override {
+		m_total_decoded_samples = 0;
+		m_pending.clear();
+		m_pending_offset = 0;
+		if (m_codec_context != nullptr) {
+			avcodec_flush_buffers(m_codec_context);
+		}
+	}
+
+	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
+	                       bool multiple_frames, AjmGaplessState* gapless) override {
+		auto result = MakeResult();
+
+		if (!m_is_initialized) {
+			result.result = AJM_RESULT_NOT_INITIALIZED;
+			return result;
+		}
+		if (m_codec_context == nullptr) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+		if (input == nullptr || input_size == 0) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+			return result;
+		}
+		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		if (output != nullptr && output_size != 0) {
+			std::memset(output, 0, output_size);
+		}
+
+		const auto* data          = static_cast<const uint8_t*>(input);
+		size_t      input_offset  = 0;
+		size_t      output_offset = 0;
+		bool        produced      = DrainPending(output, output_size, &output_offset, &result);
+
+		while (m_pending_offset >= m_pending.size() &&
+		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
+		       output_offset < output_size) {
+			const size_t length = static_cast<size_t>(data[input_offset]) |
+			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
+			if (length == 0 ||
+			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
+				result.result |= AJM_RESULT_INVALID_DATA;
+				break;
+			}
+
+			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
+			                  static_cast<int>(length), gapless, &result)) {
+				break;
+			}
+
+			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
+			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
+			if (!multiple_frames) {
+				break;
+			}
+		}
+
+		if (m_pending_offset < m_pending.size()) {
+			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
+		}
+		if (!produced && result.result == OK) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+		}
+
+		result.input_consumed        = input_offset;
+		result.output_written        = output_offset;
+		result.frames_per_packet     = m_frames_per_packet;
+		result.total_decoded_samples = m_total_decoded_samples;
+		result.format                = GetFormat();
+		return result;
+	}
+
+	void WriteCodecInfo(void* output, size_t output_size,
+	                    const AjmDecodeResult& result) const override {
+		(void)result;
+		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
+			return;
+		}
+
+		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
+		info->frames_per_packet = m_frames_per_packet;
+	}
+
+	[[nodiscard]] size_t CodecInfoSize() const override {
+		return sizeof(AjmSidebandDecOpusCodecInfo);
+	}
+
+	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
+		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
+	}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '109,194p' src/libs/ajm/opus_decoder.h
sed -n '251,286p' src/libs/ajm/opus_decoder.h
sed -n '420,465p' src/libs/ajm.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5964


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- tracked AJM files ---'
git ls-files 'src/libs/ajm*' 'src/**/ajm*' | head -120
printf '%s\n' '--- Opus and AJM diff ---'
git diff --unified=35 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h src/libs/ajm.cpp | sed -n '1,420p'
printf '%s\n' '--- decode declarations and call sites ---'
rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode|DecodeInstance|multiple_frames|AJM_RESULT_NOT_ENOUGH_ROOM|AJM_RESULT_PARTIAL_INPUT' src | head -260
printf '%s\n' '--- empty-input and pending handling ---'
rg -n -g '*.{h,hpp,cpp,c}' 'input_size\s*==\s*0|input\s*==\s*nullptr|DrainPending|m_pending|NOT_ENOUGH_ROOM|PARTIAL_INPUT' src/libs/ajm src | head -320
printf '%s\n' '--- Opus surrounding implementation ---'
sed -n '1,115p' src/libs/ajm/opus_decoder.h
sed -n '195,360p' src/libs/ajm/opus_decoder.h
printf '%s\n' '--- AJM public declarations ---'
rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode\(|AjmDecodeSplit|AjmDecodeResult|struct AjmDecodeResult|class AjmDecoder' src include 2>/dev/null | head -220

Repository: KytyPS5/KytyPS5

Length of output: 41985


🏁 Script executed:

set -eu
printf '%s\n' '--- tracked AJM files ---'
git ls-files 'src/libs/ajm*' 'src/**/ajm*' | head -120
printf '%s\n' '--- decode declarations and call sites ---'
rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode|DecodeInstance|multiple_frames|AJM_RESULT_NOT_ENOUGH_ROOM|AJM_RESULT_PARTIAL_INPUT' src | head -260
printf '%s\n' '--- empty-input and pending handling ---'
rg -n -g '*.{h,hpp,cpp,c}' 'input_size[[:space:]]*==[[:space:]]*0|input[[:space:]]*==[[:space:]]*nullptr|DrainPending|m_pending|NOT_ENOUGH_ROOM|PARTIAL_INPUT' src/libs/ajm src | head -320
printf '%s\n' '--- Opus implementation ---'
sed -n '1,115p' src/libs/ajm/opus_decoder.h
sed -n '195,360p' src/libs/ajm/opus_decoder.h
printf '%s\n' '--- public declarations ---'
rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode\(|AjmDecodeSplit|AjmDecodeResult|struct AjmDecodeResult|class AjmDecoder' src include 2>/dev/null | head -220
printf '%s\n' '--- PR diff ---'
git diff --unified=25 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h src/libs/ajm.cpp | sed -n '1,420p'

Repository: KytyPS5/KytyPS5

Length of output: 41592


🏁 Script executed:

set -eu
printf '%s\n' '--- decoder contract and result fields ---'
sed -n '45,175p' src/libs/ajm/decoder.h
printf '%s\n' '--- libAudio decode retry handling ---'
sed -n '980,1090p' src/libs/libAudio.cpp
printf '%s\n' '--- ngs2 decode handling ---'
sed -n '1470,1550p' src/libs/ngs2.cpp
printf '%s\n' '--- AJM public decode dispatch ---'
sed -n '760,855p' src/libs/ajm.cpp
sed -n '980,1050p' src/libs/ajm.cpp
printf '%s\n' '--- split decode construction ---'
sed -n '446,478p' src/libs/ajm.cpp
printf '%s\n' '--- comparable decoder ordering ---'
sed -n '90,175p' src/libs/ajm/aac_decoder.h
sed -n '140,225p' src/libs/ajm/mp3_decoder.h
sed -n '90,175p' src/libs/ajm/atrac9_decoder.h

Repository: KytyPS5/KytyPS5

Length of output: 29896


Drain pending PCM before rejecting empty input.

When a final Opus packet produces more PCM than output_size, AjmOpusDecoder::Decode consumes the packet, retains the excess in m_pending, and returns AJM_RESULT_NOT_ENOUGH_ROOM. A public AJM decode retry with no remaining packet reaches the zero-input guard and returns AJM_RESULT_PARTIAL_INPUT before DrainPending, so the final samples are never written. Move the empty-input check after the pending drain.

Suggested fix
-		if (input == nullptr || input_size == 0) {
+		if (input == nullptr && input_size != 0) {
 			result.result = AJM_RESULT_PARTIAL_INPUT;
 			return result;
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
	                       bool multiple_frames, AjmGaplessState* gapless) override {
		auto result = MakeResult();

		if (!m_is_initialized) {
			result.result = AJM_RESULT_NOT_INITIALIZED;
			return result;
		}
		if (m_codec_context == nullptr) {
			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
			return result;
		}
		if (input == nullptr && input_size != 0) {
			result.result = AJM_RESULT_PARTIAL_INPUT;
			return result;
		}
		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
			result.result = AJM_RESULT_INVALID_PARAMETER;
			return result;
		}

		if (output != nullptr && output_size != 0) {
			std::memset(output, 0, output_size);
		}

		const auto* data          = static_cast<const uint8_t*>(input);
		size_t      input_offset  = 0;
		size_t      output_offset = 0;
		bool        produced      = DrainPending(output, output_size, &output_offset, &result);

		while (m_pending_offset >= m_pending.size() &&
		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
		       output_offset < output_size) {
			const size_t length = static_cast<size_t>(data[input_offset]) |
			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
			if (length == 0 ||
			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
				result.result |= AJM_RESULT_INVALID_DATA;
				break;
			}

			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
			                  static_cast<int>(length), gapless, &result)) {
				break;
			}

			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
			if (!multiple_frames) {
				break;
			}
		}

		if (m_pending_offset < m_pending.size()) {
			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
		}
		if (!produced && result.result == OK) {
			result.result = AJM_RESULT_PARTIAL_INPUT;
		}

		result.input_consumed        = input_offset;
		result.output_written        = output_offset;
		result.frames_per_packet     = m_frames_per_packet;
		result.total_decoded_samples = m_total_decoded_samples;
		result.format                = GetFormat();
		return result;
	}

	void WriteCodecInfo(void* output, size_t output_size,
	                    const AjmDecodeResult& result) const override {
		(void)result;
		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
			return;
		}

		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
		info->frames_per_packet = m_frames_per_packet;
	}

	[[nodiscard]] size_t CodecInfoSize() const override {
		return sizeof(AjmSidebandDecOpusCodecInfo);
	}

	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 23:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#discussion_r4113287690) On `src/libs/ajm/opus_decoder.h` line 194 (outdated): ```diff @@ -0,0 +1,409 @@ +#pragma once + +#include "common/logging/log.h" +#include "libs/ajm/decoder.h" +#include "libs/ajm/ffmpeg_decoder_common.h" + +#include <algorithm> +#include <cinttypes> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <vector> + +namespace Libs::Audio::Ajm { + +struct AjmDecOpusInitializeParameters { + uint32_t channel_num; + uint32_t sample_rate; + uint32_t mapping_family; +}; + +struct AjmSidebandDecOpusCodecInfo { + uint32_t frames_per_packet; +}; + +static_assert(sizeof(AjmDecOpusInitializeParameters) == 12); +static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4); + +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10; +static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP = 0; +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP = 2; +static constexpr size_t AJM_DEC_OPUS_OPUS_HEAD_SIZE = 19; +// Each access unit is a little-endian 16-bit length followed by that many packet bytes. +static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2; + +class AjmOpusDecoder final: public AjmDecoder { +public: + AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding, + uint64_t flags) + : AjmDecoder(channels, sample_rate, encoding) { + (void)flags; + m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS); + if (m_codec == nullptr) { + LOGF("AJM Opus: avcodec_find_decoder failed\n"); + } + } + + ~AjmOpusDecoder() override { Release(); } + + AjmDecodeResult Initialize(const void* codec_parameters, + size_t codec_parameters_size) override { + auto result = MakeResult(); + + if (codec_parameters == nullptr || + codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters); + if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH || + params->sample_rate == 0) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) { + LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n", + params->mapping_family); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) { + LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n", + params->channel_num); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + Release(); + SetFormat(params->channel_num, params->sample_rate, m_sample_encoding); + m_mapping_family = params->mapping_family; + m_total_decoded_samples = 0; + m_frames_per_packet = 1; + m_is_initialized = false; + + if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + + m_is_initialized = true; + + LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n", + params->sample_rate, params->channel_num, params->mapping_family); + + return MakeResult(); + } + + void Reset() override { + m_total_decoded_samples = 0; + m_pending.clear(); + m_pending_offset = 0; + if (m_codec_context != nullptr) { + avcodec_flush_buffers(m_codec_context); + } + } + + AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, + bool multiple_frames, AjmGaplessState* gapless) override { + auto result = MakeResult(); + + if (!m_is_initialized) { + result.result = AJM_RESULT_NOT_INITIALIZED; + return result; + } + if (m_codec_context == nullptr) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + if (input == nullptr || input_size == 0) { + result.result = AJM_RESULT_PARTIAL_INPUT; + return result; + } + if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + if (output != nullptr && output_size != 0) { + std::memset(output, 0, output_size); + } + + const auto* data = static_cast<const uint8_t*>(input); + size_t input_offset = 0; + size_t output_offset = 0; + bool produced = DrainPending(output, output_size, &output_offset, &result); + + while (m_pending_offset >= m_pending.size() && + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && + output_offset < output_size) { + const size_t length = static_cast<size_t>(data[input_offset]) | + (static_cast<size_t>(data[input_offset + 1]) << 8u); + if (length == 0 || + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { + result.result |= AJM_RESULT_INVALID_DATA; + break; + } + + if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, + static_cast<int>(length), gapless, &result)) { + break; + } + + input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; + produced = DrainPending(output, output_size, &output_offset, &result) || produced; + if (!multiple_frames) { + break; + } + } + + if (m_pending_offset < m_pending.size()) { + result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; + } + if (!produced && result.result == OK) { + result.result = AJM_RESULT_PARTIAL_INPUT; + } + + result.input_consumed = input_offset; + result.output_written = output_offset; + result.frames_per_packet = m_frames_per_packet; + result.total_decoded_samples = m_total_decoded_samples; + result.format = GetFormat(); + return result; + } + + void WriteCodecInfo(void* output, size_t output_size, + const AjmDecodeResult& result) const override { + (void)result; + if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { + return; + } + + auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); + info->frames_per_packet = m_frames_per_packet; + } + + [[nodiscard]] size_t CodecInfoSize() const override { + return sizeof(AjmSidebandDecOpusCodecInfo); + } + + [[nodiscard]] AjmSidebandFormat GetFormat() const override { + return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); + } ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '109,194p' src/libs/ajm/opus_decoder.h sed -n '251,286p' src/libs/ajm/opus_decoder.h sed -n '420,465p' src/libs/ajm.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5964 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- tracked AJM files ---' git ls-files 'src/libs/ajm*' 'src/**/ajm*' | head -120 printf '%s\n' '--- Opus and AJM diff ---' git diff --unified=35 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h src/libs/ajm.cpp | sed -n '1,420p' printf '%s\n' '--- decode declarations and call sites ---' rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode|DecodeInstance|multiple_frames|AJM_RESULT_NOT_ENOUGH_ROOM|AJM_RESULT_PARTIAL_INPUT' src | head -260 printf '%s\n' '--- empty-input and pending handling ---' rg -n -g '*.{h,hpp,cpp,c}' 'input_size\s*==\s*0|input\s*==\s*nullptr|DrainPending|m_pending|NOT_ENOUGH_ROOM|PARTIAL_INPUT' src/libs/ajm src | head -320 printf '%s\n' '--- Opus surrounding implementation ---' sed -n '1,115p' src/libs/ajm/opus_decoder.h sed -n '195,360p' src/libs/ajm/opus_decoder.h printf '%s\n' '--- AJM public declarations ---' rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode\(|AjmDecodeSplit|AjmDecodeResult|struct AjmDecodeResult|class AjmDecoder' src include 2>/dev/null | head -220 ``` Repository: KytyPS5/KytyPS5 Length of output: 41985 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- tracked AJM files ---' git ls-files 'src/libs/ajm*' 'src/**/ajm*' | head -120 printf '%s\n' '--- decode declarations and call sites ---' rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode|DecodeInstance|multiple_frames|AJM_RESULT_NOT_ENOUGH_ROOM|AJM_RESULT_PARTIAL_INPUT' src | head -260 printf '%s\n' '--- empty-input and pending handling ---' rg -n -g '*.{h,hpp,cpp,c}' 'input_size[[:space:]]*==[[:space:]]*0|input[[:space:]]*==[[:space:]]*nullptr|DrainPending|m_pending|NOT_ENOUGH_ROOM|PARTIAL_INPUT' src/libs/ajm src | head -320 printf '%s\n' '--- Opus implementation ---' sed -n '1,115p' src/libs/ajm/opus_decoder.h sed -n '195,360p' src/libs/ajm/opus_decoder.h printf '%s\n' '--- public declarations ---' rg -n -g '*.{h,hpp,cpp,c}' 'AjmDecode\(|AjmDecodeSplit|AjmDecodeResult|struct AjmDecodeResult|class AjmDecoder' src include 2>/dev/null | head -220 printf '%s\n' '--- PR diff ---' git diff --unified=25 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h src/libs/ajm.cpp | sed -n '1,420p' ``` Repository: KytyPS5/KytyPS5 Length of output: 41592 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- decoder contract and result fields ---' sed -n '45,175p' src/libs/ajm/decoder.h printf '%s\n' '--- libAudio decode retry handling ---' sed -n '980,1090p' src/libs/libAudio.cpp printf '%s\n' '--- ngs2 decode handling ---' sed -n '1470,1550p' src/libs/ngs2.cpp printf '%s\n' '--- AJM public decode dispatch ---' sed -n '760,855p' src/libs/ajm.cpp sed -n '980,1050p' src/libs/ajm.cpp printf '%s\n' '--- split decode construction ---' sed -n '446,478p' src/libs/ajm.cpp printf '%s\n' '--- comparable decoder ordering ---' sed -n '90,175p' src/libs/ajm/aac_decoder.h sed -n '140,225p' src/libs/ajm/mp3_decoder.h sed -n '90,175p' src/libs/ajm/atrac9_decoder.h ``` Repository: KytyPS5/KytyPS5 Length of output: 29896 --- </details> **Drain pending PCM before rejecting empty input.** When a final Opus packet produces more PCM than `output_size`, `AjmOpusDecoder::Decode` consumes the packet, retains the excess in `m_pending`, and returns `AJM_RESULT_NOT_ENOUGH_ROOM`. A public AJM decode retry with no remaining packet reaches the zero-input guard and returns `AJM_RESULT_PARTIAL_INPUT` before `DrainPending`, so the final samples are never written. Move the empty-input check after the pending drain. <details><summary>Suggested fix</summary> ```diff - if (input == nullptr || input_size == 0) { + if (input == nullptr && input_size != 0) { result.result = AJM_RESULT_PARTIAL_INPUT; return result; } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, bool multiple_frames, AjmGaplessState* gapless) override { auto result = MakeResult(); if (!m_is_initialized) { result.result = AJM_RESULT_NOT_INITIALIZED; return result; } if (m_codec_context == nullptr) { result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; return result; } if (input == nullptr && input_size != 0) { result.result = AJM_RESULT_PARTIAL_INPUT; return result; } if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { result.result = AJM_RESULT_INVALID_PARAMETER; return result; } if (output != nullptr && output_size != 0) { std::memset(output, 0, output_size); } const auto* data = static_cast<const uint8_t*>(input); size_t input_offset = 0; size_t output_offset = 0; bool produced = DrainPending(output, output_size, &output_offset, &result); while (m_pending_offset >= m_pending.size() && input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && output_offset < output_size) { const size_t length = static_cast<size_t>(data[input_offset]) | (static_cast<size_t>(data[input_offset + 1]) << 8u); if (length == 0 || input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { result.result |= AJM_RESULT_INVALID_DATA; break; } if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, static_cast<int>(length), gapless, &result)) { break; } input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; produced = DrainPending(output, output_size, &output_offset, &result) || produced; if (!multiple_frames) { break; } } if (m_pending_offset < m_pending.size()) { result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; } if (!produced && result.result == OK) { result.result = AJM_RESULT_PARTIAL_INPUT; } result.input_consumed = input_offset; result.output_written = output_offset; result.frames_per_packet = m_frames_per_packet; result.total_decoded_samples = m_total_decoded_samples; result.format = GetFormat(); return result; } void WriteCodecInfo(void* output, size_t output_size, const AjmDecodeResult& result) const override { (void)result; if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { return; } auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); info->frames_per_packet = m_frames_per_packet; } [[nodiscard]] size_t CodecInfoSize() const override { return sizeof(AjmSidebandDecOpusCodecInfo); } [[nodiscard]] AjmSidebandFormat GetFormat() const override { return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:921a8723c16893fb1c783046 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 23:16 UTC · original · edited 2026-09-27 00:31 UTC
On src/libs/ajm/opus_decoder.h line 304 (outdated):

@@ -0,0 +1,409 @@
+#pragma once
+
+#include "common/logging/log.h"
+#include "libs/ajm/decoder.h"
+#include "libs/ajm/ffmpeg_decoder_common.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <vector>
+
+namespace Libs::Audio::Ajm {
+
+struct AjmDecOpusInitializeParameters {
+	uint32_t channel_num;
+	uint32_t sample_rate;
+	uint32_t mapping_family;
+};
+
+struct AjmSidebandDecOpusCodecInfo {
+	uint32_t frames_per_packet;
+};
+
+static_assert(sizeof(AjmDecOpusInitializeParameters) == 12);
+static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4);
+
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10;
+static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP    = 0;
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP      = 2;
+static constexpr size_t   AJM_DEC_OPUS_OPUS_HEAD_SIZE        = 19;
+// Each access unit is a little-endian 16-bit length followed by that many packet bytes.
+static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2;
+
+class AjmOpusDecoder final: public AjmDecoder {
+public:
+	AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding,
+	               uint64_t flags)
+	    : AjmDecoder(channels, sample_rate, encoding) {
+		(void)flags;
+		m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
+		if (m_codec == nullptr) {
+			LOGF("AJM Opus: avcodec_find_decoder failed\n");
+		}
+	}
+
+	~AjmOpusDecoder() override { Release(); }
+
+	AjmDecodeResult Initialize(const void* codec_parameters,
+	                           size_t      codec_parameters_size) override {
+		auto result = MakeResult();
+
+		if (codec_parameters == nullptr ||
+		    codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters);
+		if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH ||
+		    params->sample_rate == 0) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) {
+			LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n",
+			     params->mapping_family);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) {
+			LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n",
+			     params->channel_num);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		Release();
+		SetFormat(params->channel_num, params->sample_rate, m_sample_encoding);
+		m_mapping_family        = params->mapping_family;
+		m_total_decoded_samples = 0;
+		m_frames_per_packet     = 1;
+		m_is_initialized        = false;
+
+		if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+
+		m_is_initialized = true;
+
+		LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n",
+		     params->sample_rate, params->channel_num, params->mapping_family);
+
+		return MakeResult();
+	}
+
+	void Reset() override {
+		m_total_decoded_samples = 0;
+		m_pending.clear();
+		m_pending_offset = 0;
+		if (m_codec_context != nullptr) {
+			avcodec_flush_buffers(m_codec_context);
+		}
+	}
+
+	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
+	                       bool multiple_frames, AjmGaplessState* gapless) override {
+		auto result = MakeResult();
+
+		if (!m_is_initialized) {
+			result.result = AJM_RESULT_NOT_INITIALIZED;
+			return result;
+		}
+		if (m_codec_context == nullptr) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+		if (input == nullptr || input_size == 0) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+			return result;
+		}
+		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		if (output != nullptr && output_size != 0) {
+			std::memset(output, 0, output_size);
+		}
+
+		const auto* data          = static_cast<const uint8_t*>(input);
+		size_t      input_offset  = 0;
+		size_t      output_offset = 0;
+		bool        produced      = DrainPending(output, output_size, &output_offset, &result);
+
+		while (m_pending_offset >= m_pending.size() &&
+		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
+		       output_offset < output_size) {
+			const size_t length = static_cast<size_t>(data[input_offset]) |
+			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
+			if (length == 0 ||
+			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
+				result.result |= AJM_RESULT_INVALID_DATA;
+				break;
+			}
+
+			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
+			                  static_cast<int>(length), gapless, &result)) {
+				break;
+			}
+
+			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
+			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
+			if (!multiple_frames) {
+				break;
+			}
+		}
+
+		if (m_pending_offset < m_pending.size()) {
+			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
+		}
+		if (!produced && result.result == OK) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+		}
+
+		result.input_consumed        = input_offset;
+		result.output_written        = output_offset;
+		result.frames_per_packet     = m_frames_per_packet;
+		result.total_decoded_samples = m_total_decoded_samples;
+		result.format                = GetFormat();
+		return result;
+	}
+
+	void WriteCodecInfo(void* output, size_t output_size,
+	                    const AjmDecodeResult& result) const override {
+		(void)result;
+		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
+			return;
+		}
+
+		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
+		info->frames_per_packet = m_frames_per_packet;
+	}
+
+	[[nodiscard]] size_t CodecInfoSize() const override {
+		return sizeof(AjmSidebandDecOpusCodecInfo);
+	}
+
+	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
+		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
+	}
+
+private:
+	void Release() {
+		if (m_codec_context != nullptr) {
+			avcodec_free_context(&m_codec_context);
+		}
+	}
+	// The instance carries no container, so the identification header is rebuilt here.
+	static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate,
+	                         uint32_t mapping_family) {
+		std::memcpy(head, "OpusHead", 8);
+		head[8]  = 1;
+		head[9]  = static_cast<uint8_t>(channels);
+		head[10] = 0;
+		head[11] = 0;
+		head[12] = static_cast<uint8_t>(sample_rate & 0xffu);
+		head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu);
+		head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu);
+		head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu);
+		head[16] = 0;
+		head[17] = 0;
+		head[18] = static_cast<uint8_t>(mapping_family);
+	}
+
+	bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) {
+		if (m_codec == nullptr) {
+			return false;
+		}
+
+		m_codec_context = avcodec_alloc_context3(m_codec);
+		if (m_codec_context == nullptr) {
+			return false;
+		}
+
+		m_codec_context->sample_rate = static_cast<int>(sample_rate);
+		av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels));
+
+		auto* extradata = static_cast<uint8_t*>(
+		    av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
+		if (extradata == nullptr) {
+			Release();
+			return false;
+		}
+		FillOpusHead(extradata, channels, sample_rate, mapping_family);
+		m_codec_context->extradata      = extradata;
+		m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE);
+
+		if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) {
+			LOGF("AJM Opus: decoder initialization failed\n");
+			Release();
+			return false;
+		}
+
+		return true;
+	}
+
+	bool DrainPending(void* output, size_t output_size, size_t* output_offset,
+	                  AjmDecodeResult* result) {
+		if (output == nullptr || output_offset == nullptr || result == nullptr) {
+			return false;
+		}
+		const auto available = m_pending.size() - m_pending_offset;
+		if (available == 0 || *output_offset >= output_size) {
+			return false;
+		}
+		const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			return false;
+		}
+
+		auto bytes = std::min(available, output_size - *output_offset);
+		bytes -= bytes % bpf;
+		if (bytes == 0) {
+			return false;
+		}
+
+		std::memcpy(static_cast<uint8_t*>(output) + *output_offset,
+		            m_pending.data() + m_pending_offset, bytes);
+		*output_offset += bytes;
+		m_pending_offset += bytes;
+		if (m_pending_offset >= m_pending.size()) {
+			m_pending.clear();
+			m_pending_offset = 0;
+		}
+
+		const auto samples = static_cast<uint32_t>(bytes / bpf);
+		m_total_decoded_samples += samples;
+		result->total_decoded_samples = m_total_decoded_samples;
+		result->format                = GetFormat();
+		return samples != 0;
+	}
+
+	bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) {
+		if (frame == nullptr || result == nullptr) {
+			return false;
+		}
+
+		const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1));
+		if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) {
+			result->result = AJM_RESULT_TOO_MANY_CHANNELS;
+			return false;
+		}
+		const auto bpf = channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			result->result = AJM_RESULT_INVALID_PARAMETER;
+			return false;
+		}
+
+		SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)),
+		          m_sample_encoding);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -e
printf '%s\n' '--- changed files ---'
git diff --stat 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2
printf '%s\n' '--- opus decoder outline ---'
ast-grep outline src/libs/ajm/opus_decoder.h
printf '%s\n' '--- opus decoder relevant source ---'
cat -n src/libs/ajm/opus_decoder.h | sed -n '1,380p'
printf '%s\n' '--- conversion and sample-rate references ---'
rg -n -C 3 'AjmConvertFfmpegFrame|SetFormat\(|m_sample_rate|sample_rate|AjmDecOpus|OpusDecoder' src/libs/ajm
printf '%s\n' '--- AJM guidance and relevant callers ---'
rg -n -C 3 'AjmDecOpusInitializeParameters|mapping_family|sample rate|sample_rate|Opus' README.md docs src 2>/dev/null | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 41776


🤖 get_repo_knowledge executed:

get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture

Length of output: 14418


🏁 Script executed:

set -e
git diff --unified=80 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h
rg -n -C 8 'AjmConvertFfmpegFrame|class AjmOpusDecoder|SetFormat|sample_rate|OpusHead' src/libs/ajm

Repository: KytyPS5/KytyPS5

Length of output: 42115


🌐 Web query:

FFmpeg native libavcodec Opus decoder AVCodecContext sample_rate output 48000 source

💡 Result:

Yes. FFmpeg’s **native Opus decoder** sets `AVCodecContext.sample_rate` to **48000 Hz** in `opus_decode_init()` (`libavcodec/opusdec.c`). The source is in FFmpeg’s Doxygen source listing. [1]

Note: FFmpeg also has a separate **libopus-backed decoder** (`libopusdec.c`), which likewise sets the context sample rate to 48000 Hz. [2]

Sources: [1] ([fuchsia.googlesource.com](https://fuchsia.googlesource.com/third_party/ffmpeg/%2B/0d4c6a803cf31d9d2116e32655d44c769080646d/libavcodec/opusdec.c?utm_source=openai)) [2] ([ffmpeg.org](https://www.ffmpeg.org/doxygen/trunk/libopusdec_8c_source.html?utm_source=openai))

Citations:

- 1: https://fuchsia.googlesource.com/third_party/ffmpeg/%2B/0d4c6a803cf31d9d2116e32655d44c769080646d/libavcodec/opusdec.c?utm_source=openai
- 2: https://www.ffmpeg.org/doxygen/trunk/libopusdec_8c_source.html?utm_source=openai

🏁 Script executed:

set -e
printf '%s\n' '--- AJM Opus construction and decoder contract ---'
rg -n -C 12 'AjmOpusDecoder|AJM_CODEC.*OPUS|DEC_OPUS|Initialize\(.*codec|GetFormat\(\)' src/libs/ajm.cpp src/libs/ajm/decoder.h src/libs/ajm
printf '%s\n' '--- FFmpeg dependency declarations ---'
rg -n -C 5 'FFmpeg|avcodec|libavcodec|LIBAV' CMakeLists.txt cmake .github 2>/dev/null | head -n 300
printf '%s\n' '--- installed FFmpeg capability ---'
(command -v ffmpeg && ffmpeg -version | head -n 3) || true

Repository: KytyPS5/KytyPS5

Length of output: 41686


🌐 Web query:

SceAjmDecOpusInitializeParameters sampleRate output PCM sampling rate AJM

💡 Result:

`SceAjmDecOpusInitializeParameters`’s `sampleRate` is the **PCM output rate requested from the decoder**, not necessarily the Opus stream’s original/input rate.

Opus decoding supports **8, 12, 16, 24, or 48 kHz** output; **48 kHz** is the usual/default choice. The decoder can produce PCM at a supported lower rate when requested. ([opus-codec.org](https://www.opus-codec.org/docs/opus_api-1.6/group__opus__decoder.html?utm_source=openai))

So, for typical AJM Opus decoding, set `sampleRate` to **48000** unless your downstream audio path requires another supported rate. I couldn’t find public AJM-specific documentation confirming the field’s exact contract, so treat this as the Opus decoder behavior rather than a verified Sony API guarantee.

Citations:

- 1: https://www.opus-codec.org/docs/opus_api-1.6/group__opus__decoder.html?utm_source=openai

Resample Opus output to m_sample_rate.

FFmpeg’s native Opus decoder forces decoded frames to 48000 Hz. AjmConvertFfmpegFrame preserves that rate and configures SwrContext with the same input and output rate. AppendFrame then replaces the initialized format rate with 48000 Hz.

For a supported lower-rate initialization, the decoder can therefore expose 48000-Hz PCM and report too many decoded samples. Add a target-rate parameter to AjmConvertFfmpegFrame, resample to m_sample_rate, and keep the format rate from Initialize.

✅ Confirmed as addressed by @⁠joaodiaslobo

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 23:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#discussion_r4113287712) · edited 2026-09-27 00:31 UTC On `src/libs/ajm/opus_decoder.h` line 304 (outdated): ```diff @@ -0,0 +1,409 @@ +#pragma once + +#include "common/logging/log.h" +#include "libs/ajm/decoder.h" +#include "libs/ajm/ffmpeg_decoder_common.h" + +#include <algorithm> +#include <cinttypes> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <vector> + +namespace Libs::Audio::Ajm { + +struct AjmDecOpusInitializeParameters { + uint32_t channel_num; + uint32_t sample_rate; + uint32_t mapping_family; +}; + +struct AjmSidebandDecOpusCodecInfo { + uint32_t frames_per_packet; +}; + +static_assert(sizeof(AjmDecOpusInitializeParameters) == 12); +static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4); + +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10; +static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP = 0; +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP = 2; +static constexpr size_t AJM_DEC_OPUS_OPUS_HEAD_SIZE = 19; +// Each access unit is a little-endian 16-bit length followed by that many packet bytes. +static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2; + +class AjmOpusDecoder final: public AjmDecoder { +public: + AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding, + uint64_t flags) + : AjmDecoder(channels, sample_rate, encoding) { + (void)flags; + m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS); + if (m_codec == nullptr) { + LOGF("AJM Opus: avcodec_find_decoder failed\n"); + } + } + + ~AjmOpusDecoder() override { Release(); } + + AjmDecodeResult Initialize(const void* codec_parameters, + size_t codec_parameters_size) override { + auto result = MakeResult(); + + if (codec_parameters == nullptr || + codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters); + if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH || + params->sample_rate == 0) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) { + LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n", + params->mapping_family); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) { + LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n", + params->channel_num); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + Release(); + SetFormat(params->channel_num, params->sample_rate, m_sample_encoding); + m_mapping_family = params->mapping_family; + m_total_decoded_samples = 0; + m_frames_per_packet = 1; + m_is_initialized = false; + + if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + + m_is_initialized = true; + + LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n", + params->sample_rate, params->channel_num, params->mapping_family); + + return MakeResult(); + } + + void Reset() override { + m_total_decoded_samples = 0; + m_pending.clear(); + m_pending_offset = 0; + if (m_codec_context != nullptr) { + avcodec_flush_buffers(m_codec_context); + } + } + + AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, + bool multiple_frames, AjmGaplessState* gapless) override { + auto result = MakeResult(); + + if (!m_is_initialized) { + result.result = AJM_RESULT_NOT_INITIALIZED; + return result; + } + if (m_codec_context == nullptr) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + if (input == nullptr || input_size == 0) { + result.result = AJM_RESULT_PARTIAL_INPUT; + return result; + } + if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + if (output != nullptr && output_size != 0) { + std::memset(output, 0, output_size); + } + + const auto* data = static_cast<const uint8_t*>(input); + size_t input_offset = 0; + size_t output_offset = 0; + bool produced = DrainPending(output, output_size, &output_offset, &result); + + while (m_pending_offset >= m_pending.size() && + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && + output_offset < output_size) { + const size_t length = static_cast<size_t>(data[input_offset]) | + (static_cast<size_t>(data[input_offset + 1]) << 8u); + if (length == 0 || + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { + result.result |= AJM_RESULT_INVALID_DATA; + break; + } + + if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, + static_cast<int>(length), gapless, &result)) { + break; + } + + input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; + produced = DrainPending(output, output_size, &output_offset, &result) || produced; + if (!multiple_frames) { + break; + } + } + + if (m_pending_offset < m_pending.size()) { + result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; + } + if (!produced && result.result == OK) { + result.result = AJM_RESULT_PARTIAL_INPUT; + } + + result.input_consumed = input_offset; + result.output_written = output_offset; + result.frames_per_packet = m_frames_per_packet; + result.total_decoded_samples = m_total_decoded_samples; + result.format = GetFormat(); + return result; + } + + void WriteCodecInfo(void* output, size_t output_size, + const AjmDecodeResult& result) const override { + (void)result; + if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { + return; + } + + auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); + info->frames_per_packet = m_frames_per_packet; + } + + [[nodiscard]] size_t CodecInfoSize() const override { + return sizeof(AjmSidebandDecOpusCodecInfo); + } + + [[nodiscard]] AjmSidebandFormat GetFormat() const override { + return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); + } + +private: + void Release() { + if (m_codec_context != nullptr) { + avcodec_free_context(&m_codec_context); + } + } + // The instance carries no container, so the identification header is rebuilt here. + static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate, + uint32_t mapping_family) { + std::memcpy(head, "OpusHead", 8); + head[8] = 1; + head[9] = static_cast<uint8_t>(channels); + head[10] = 0; + head[11] = 0; + head[12] = static_cast<uint8_t>(sample_rate & 0xffu); + head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu); + head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu); + head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu); + head[16] = 0; + head[17] = 0; + head[18] = static_cast<uint8_t>(mapping_family); + } + + bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) { + if (m_codec == nullptr) { + return false; + } + + m_codec_context = avcodec_alloc_context3(m_codec); + if (m_codec_context == nullptr) { + return false; + } + + m_codec_context->sample_rate = static_cast<int>(sample_rate); + av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels)); + + auto* extradata = static_cast<uint8_t*>( + av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE)); + if (extradata == nullptr) { + Release(); + return false; + } + FillOpusHead(extradata, channels, sample_rate, mapping_family); + m_codec_context->extradata = extradata; + m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE); + + if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) { + LOGF("AJM Opus: decoder initialization failed\n"); + Release(); + return false; + } + + return true; + } + + bool DrainPending(void* output, size_t output_size, size_t* output_offset, + AjmDecodeResult* result) { + if (output == nullptr || output_offset == nullptr || result == nullptr) { + return false; + } + const auto available = m_pending.size() - m_pending_offset; + if (available == 0 || *output_offset >= output_size) { + return false; + } + const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + return false; + } + + auto bytes = std::min(available, output_size - *output_offset); + bytes -= bytes % bpf; + if (bytes == 0) { + return false; + } + + std::memcpy(static_cast<uint8_t*>(output) + *output_offset, + m_pending.data() + m_pending_offset, bytes); + *output_offset += bytes; + m_pending_offset += bytes; + if (m_pending_offset >= m_pending.size()) { + m_pending.clear(); + m_pending_offset = 0; + } + + const auto samples = static_cast<uint32_t>(bytes / bpf); + m_total_decoded_samples += samples; + result->total_decoded_samples = m_total_decoded_samples; + result->format = GetFormat(); + return samples != 0; + } + + bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) { + if (frame == nullptr || result == nullptr) { + return false; + } + + const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1)); + if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) { + result->result = AJM_RESULT_TOO_MANY_CHANNELS; + return false; + } + const auto bpf = channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + result->result = AJM_RESULT_INVALID_PARAMETER; + return false; + } + + SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)), + m_sample_encoding); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -e printf '%s\n' '--- changed files ---' git diff --stat 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 printf '%s\n' '--- opus decoder outline ---' ast-grep outline src/libs/ajm/opus_decoder.h printf '%s\n' '--- opus decoder relevant source ---' cat -n src/libs/ajm/opus_decoder.h | sed -n '1,380p' printf '%s\n' '--- conversion and sample-rate references ---' rg -n -C 3 'AjmConvertFfmpegFrame|SetFormat\(|m_sample_rate|sample_rate|AjmDecOpus|OpusDecoder' src/libs/ajm printf '%s\n' '--- AJM guidance and relevant callers ---' rg -n -C 3 'AjmDecOpusInitializeParameters|mapping_family|sample rate|sample_rate|Opus' README.md docs src 2>/dev/null | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 41776 --- 🤖 get_repo_knowledge executed: `get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture` Length of output: 14418 --- 🏁 Script executed: ```bash set -e git diff --unified=80 16b83a034cdc7abed2482605c77921b10056d83c bd926c2ad7994a2c7610f80bec2b26e1c18871a2 -- src/libs/ajm/opus_decoder.h rg -n -C 8 'AjmConvertFfmpegFrame|class AjmOpusDecoder|SetFormat|sample_rate|OpusHead' src/libs/ajm ``` Repository: KytyPS5/KytyPS5 Length of output: 42115 --- 🌐 Web query: `FFmpeg native libavcodec Opus decoder AVCodecContext sample_rate output 48000 source` 💡 Result: ``` Yes. FFmpeg’s **native Opus decoder** sets `AVCodecContext.sample_rate` to **48000 Hz** in `opus_decode_init()` (`libavcodec/opusdec.c`). The source is in FFmpeg’s Doxygen source listing. [1] Note: FFmpeg also has a separate **libopus-backed decoder** (`libopusdec.c`), which likewise sets the context sample rate to 48000 Hz. [2] Sources: [1] ([fuchsia.googlesource.com](https://fuchsia.googlesource.com/third_party/ffmpeg/%2B/0d4c6a803cf31d9d2116e32655d44c769080646d/libavcodec/opusdec.c?utm_source=openai)) [2] ([ffmpeg.org](https://www.ffmpeg.org/doxygen/trunk/libopusdec_8c_source.html?utm_source=openai)) Citations: - 1: https://fuchsia.googlesource.com/third_party/ffmpeg/%2B/0d4c6a803cf31d9d2116e32655d44c769080646d/libavcodec/opusdec.c?utm_source=openai - 2: https://www.ffmpeg.org/doxygen/trunk/libopusdec_8c_source.html?utm_source=openai ``` --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- AJM Opus construction and decoder contract ---' rg -n -C 12 'AjmOpusDecoder|AJM_CODEC.*OPUS|DEC_OPUS|Initialize\(.*codec|GetFormat\(\)' src/libs/ajm.cpp src/libs/ajm/decoder.h src/libs/ajm printf '%s\n' '--- FFmpeg dependency declarations ---' rg -n -C 5 'FFmpeg|avcodec|libavcodec|LIBAV' CMakeLists.txt cmake .github 2>/dev/null | head -n 300 printf '%s\n' '--- installed FFmpeg capability ---' (command -v ffmpeg && ffmpeg -version | head -n 3) || true ``` Repository: KytyPS5/KytyPS5 Length of output: 41686 --- 🌐 Web query: `SceAjmDecOpusInitializeParameters sampleRate output PCM sampling rate AJM` 💡 Result: ``` `SceAjmDecOpusInitializeParameters`’s `sampleRate` is the **PCM output rate requested from the decoder**, not necessarily the Opus stream’s original/input rate. Opus decoding supports **8, 12, 16, 24, or 48 kHz** output; **48 kHz** is the usual/default choice. The decoder can produce PCM at a supported lower rate when requested. ([opus-codec.org](https://www.opus-codec.org/docs/opus_api-1.6/group__opus__decoder.html?utm_source=openai)) So, for typical AJM Opus decoding, set `sampleRate` to **48000** unless your downstream audio path requires another supported rate. I couldn’t find public AJM-specific documentation confirming the field’s exact contract, so treat this as the Opus decoder behavior rather than a verified Sony API guarantee. Citations: - 1: https://www.opus-codec.org/docs/opus_api-1.6/group__opus__decoder.html?utm_source=openai ``` --- </details> **Resample Opus output to `m_sample_rate`.** FFmpeg’s native Opus decoder forces decoded frames to 48000 Hz. `AjmConvertFfmpegFrame` preserves that rate and configures `SwrContext` with the same input and output rate. `AppendFrame` then replaces the initialized format rate with 48000 Hz. For a supported lower-rate initialization, the decoder can therefore expose 48000-Hz PCM and report too many decoded samples. Add a target-rate parameter to `AjmConvertFfmpegFrame`, resample to `m_sample_rate`, and keep the format rate from `Initialize`. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2c7bad29c2e93ddddd57442d --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠joaodiaslobo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 23:16 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: d337b106-a0d2-448f-b2da-9245937f8ac6

📥 Commits

Reviewing files that changed from the base of the PR and between bec67b7863 and bd926c2ad7994a2c7610f80bec2b26e1c18871a2.

📒 Files selected for processing (2)
  • src/libs/ajm.cpp
  • src/libs/ajm/opus_decoder.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 23:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#pullrequestreview-5327997857) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `d337b106-a0d2-448f-b2da-9245937f8ac6` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between bec67b78639dfaf212141479d0028921845de3c8 and bd926c2ad7994a2c7610f80bec2b26e1c18871a2. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/libs/ajm.cpp` * `src/libs/ajm/opus_decoder.h` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 23:47 UTC · original · reviewed

♻️ Duplicate comments (1)
src/libs/ajm/opus_decoder.h (1)

305-306: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep the initialized sample rate. Do not overwrite it with the FFmpeg frame rate.

FFmpeg's Opus decoder always outputs 48000 Hz. AjmConvertFfmpegFrame keeps frame->sample_rate and does not resample. Line 305 then replaces m_sample_rate from Initialize with 48000. If a game initializes at a lower Opus rate, such as 24000 Hz, the decoder returns 48000-Hz PCM, reports the wrong format, and counts too many decoded samples. To fix this, resample to m_sample_rate inside the conversion step and leave the format rate from Initialize unchanged.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 29c376f1-b614-4793-b8e8-3c14f0c25b90

📥 Commits

Reviewing files that changed from the base of the PR and between bd926c2ad7994a2c7610f80bec2b26e1c18871a2 and a14dc7787100388e5f651f541101f9b45ea4111d.

📒 Files selected for processing (1)
  • src/libs/ajm/opus_decoder.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 23:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#pullrequestreview-5328131588) · **reviewed** <details> <summary>♻️ Duplicate comments (1)</summary><blockquote> <details> <summary>src/libs/ajm/opus_decoder.h (1)</summary><blockquote> `305-306`: _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Keep the initialized sample rate. Do not overwrite it with the FFmpeg frame rate.** FFmpeg's Opus decoder always outputs 48000 Hz. `AjmConvertFfmpegFrame` keeps `frame->sample_rate` and does not resample. Line 305 then replaces `m_sample_rate` from `Initialize` with 48000. If a game initializes at a lower Opus rate, such as 24000 Hz, the decoder returns 48000-Hz PCM, reports the wrong format, and counts too many decoded samples. To fix this, resample to `m_sample_rate` inside the conversion step and leave the format rate from `Initialize` unchanged. <!-- cr-comment:v1:094d8439b15fccea7403f3af --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `29c376f1-b614-4793-b8e8-3c14f0c25b90` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between bd926c2ad7994a2c7610f80bec2b26e1c18871a2 and a14dc7787100388e5f651f541101f9b45ea4111d. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/ajm/opus_decoder.h` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠joaodiaslobo on GitHub · 2026-09-27 00:16 UTC · original
On src/libs/ajm/opus_decoder.h line 304 (outdated):

@@ -0,0 +1,409 @@
+#pragma once
+
+#include "common/logging/log.h"
+#include "libs/ajm/decoder.h"
+#include "libs/ajm/ffmpeg_decoder_common.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <vector>
+
+namespace Libs::Audio::Ajm {
+
+struct AjmDecOpusInitializeParameters {
+	uint32_t channel_num;
+	uint32_t sample_rate;
+	uint32_t mapping_family;
+};
+
+struct AjmSidebandDecOpusCodecInfo {
+	uint32_t frames_per_packet;
+};
+
+static_assert(sizeof(AjmDecOpusInitializeParameters) == 12);
+static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4);
+
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10;
+static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP    = 0;
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP      = 2;
+static constexpr size_t   AJM_DEC_OPUS_OPUS_HEAD_SIZE        = 19;
+// Each access unit is a little-endian 16-bit length followed by that many packet bytes.
+static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2;
+
+class AjmOpusDecoder final: public AjmDecoder {
+public:
+	AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding,
+	               uint64_t flags)
+	    : AjmDecoder(channels, sample_rate, encoding) {
+		(void)flags;
+		m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
+		if (m_codec == nullptr) {
+			LOGF("AJM Opus: avcodec_find_decoder failed\n");
+		}
+	}
+
+	~AjmOpusDecoder() override { Release(); }
+
+	AjmDecodeResult Initialize(const void* codec_parameters,
+	                           size_t      codec_parameters_size) override {
+		auto result = MakeResult();
+
+		if (codec_parameters == nullptr ||
+		    codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters);
+		if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH ||
+		    params->sample_rate == 0) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) {
+			LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n",
+			     params->mapping_family);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) {
+			LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n",
+			     params->channel_num);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		Release();
+		SetFormat(params->channel_num, params->sample_rate, m_sample_encoding);
+		m_mapping_family        = params->mapping_family;
+		m_total_decoded_samples = 0;
+		m_frames_per_packet     = 1;
+		m_is_initialized        = false;
+
+		if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+
+		m_is_initialized = true;
+
+		LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n",
+		     params->sample_rate, params->channel_num, params->mapping_family);
+
+		return MakeResult();
+	}
+
+	void Reset() override {
+		m_total_decoded_samples = 0;
+		m_pending.clear();
+		m_pending_offset = 0;
+		if (m_codec_context != nullptr) {
+			avcodec_flush_buffers(m_codec_context);
+		}
+	}
+
+	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
+	                       bool multiple_frames, AjmGaplessState* gapless) override {
+		auto result = MakeResult();
+
+		if (!m_is_initialized) {
+			result.result = AJM_RESULT_NOT_INITIALIZED;
+			return result;
+		}
+		if (m_codec_context == nullptr) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+		if (input == nullptr || input_size == 0) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+			return result;
+		}
+		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		if (output != nullptr && output_size != 0) {
+			std::memset(output, 0, output_size);
+		}
+
+		const auto* data          = static_cast<const uint8_t*>(input);
+		size_t      input_offset  = 0;
+		size_t      output_offset = 0;
+		bool        produced      = DrainPending(output, output_size, &output_offset, &result);
+
+		while (m_pending_offset >= m_pending.size() &&
+		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
+		       output_offset < output_size) {
+			const size_t length = static_cast<size_t>(data[input_offset]) |
+			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
+			if (length == 0 ||
+			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
+				result.result |= AJM_RESULT_INVALID_DATA;
+				break;
+			}
+
+			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
+			                  static_cast<int>(length), gapless, &result)) {
+				break;
+			}
+
+			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
+			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
+			if (!multiple_frames) {
+				break;
+			}
+		}
+
+		if (m_pending_offset < m_pending.size()) {
+			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
+		}
+		if (!produced && result.result == OK) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+		}
+
+		result.input_consumed        = input_offset;
+		result.output_written        = output_offset;
+		result.frames_per_packet     = m_frames_per_packet;
+		result.total_decoded_samples = m_total_decoded_samples;
+		result.format                = GetFormat();
+		return result;
+	}
+
+	void WriteCodecInfo(void* output, size_t output_size,
+	                    const AjmDecodeResult& result) const override {
+		(void)result;
+		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
+			return;
+		}
+
+		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
+		info->frames_per_packet = m_frames_per_packet;
+	}
+
+	[[nodiscard]] size_t CodecInfoSize() const override {
+		return sizeof(AjmSidebandDecOpusCodecInfo);
+	}
+
+	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
+		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
+	}
+
+private:
+	void Release() {
+		if (m_codec_context != nullptr) {
+			avcodec_free_context(&m_codec_context);
+		}
+	}
+	// The instance carries no container, so the identification header is rebuilt here.
+	static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate,
+	                         uint32_t mapping_family) {
+		std::memcpy(head, "OpusHead", 8);
+		head[8]  = 1;
+		head[9]  = static_cast<uint8_t>(channels);
+		head[10] = 0;
+		head[11] = 0;
+		head[12] = static_cast<uint8_t>(sample_rate & 0xffu);
+		head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu);
+		head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu);
+		head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu);
+		head[16] = 0;
+		head[17] = 0;
+		head[18] = static_cast<uint8_t>(mapping_family);
+	}
+
+	bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) {
+		if (m_codec == nullptr) {
+			return false;
+		}
+
+		m_codec_context = avcodec_alloc_context3(m_codec);
+		if (m_codec_context == nullptr) {
+			return false;
+		}
+
+		m_codec_context->sample_rate = static_cast<int>(sample_rate);
+		av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels));
+
+		auto* extradata = static_cast<uint8_t*>(
+		    av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
+		if (extradata == nullptr) {
+			Release();
+			return false;
+		}
+		FillOpusHead(extradata, channels, sample_rate, mapping_family);
+		m_codec_context->extradata      = extradata;
+		m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE);
+
+		if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) {
+			LOGF("AJM Opus: decoder initialization failed\n");
+			Release();
+			return false;
+		}
+
+		return true;
+	}
+
+	bool DrainPending(void* output, size_t output_size, size_t* output_offset,
+	                  AjmDecodeResult* result) {
+		if (output == nullptr || output_offset == nullptr || result == nullptr) {
+			return false;
+		}
+		const auto available = m_pending.size() - m_pending_offset;
+		if (available == 0 || *output_offset >= output_size) {
+			return false;
+		}
+		const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			return false;
+		}
+
+		auto bytes = std::min(available, output_size - *output_offset);
+		bytes -= bytes % bpf;
+		if (bytes == 0) {
+			return false;
+		}
+
+		std::memcpy(static_cast<uint8_t*>(output) + *output_offset,
+		            m_pending.data() + m_pending_offset, bytes);
+		*output_offset += bytes;
+		m_pending_offset += bytes;
+		if (m_pending_offset >= m_pending.size()) {
+			m_pending.clear();
+			m_pending_offset = 0;
+		}
+
+		const auto samples = static_cast<uint32_t>(bytes / bpf);
+		m_total_decoded_samples += samples;
+		result->total_decoded_samples = m_total_decoded_samples;
+		result->format                = GetFormat();
+		return samples != 0;
+	}
+
+	bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) {
+		if (frame == nullptr || result == nullptr) {
+			return false;
+		}
+
+		const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1));
+		if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) {
+			result->result = AJM_RESULT_TOO_MANY_CHANNELS;
+			return false;
+		}
+		const auto bpf = channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			result->result = AJM_RESULT_INVALID_PARAMETER;
+			return false;
+		}
+
+		SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)),
+		          m_sample_encoding);

AjmConvertFfmpegFrame is shared with the AAC, MP3 and ATRAC9 decoders where taking the frame rate is correct, so adding a target rate parameter there reaches further than this PR. Every Opus stream I have seen initializes at 48000 Hz, but I can reject other rates in Initialize with a log line if preferred.

**@⁠joaodiaslobo** on GitHub · 2026-09-27 00:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#discussion_r4113488156) On `src/libs/ajm/opus_decoder.h` line 304 (outdated): ```diff @@ -0,0 +1,409 @@ +#pragma once + +#include "common/logging/log.h" +#include "libs/ajm/decoder.h" +#include "libs/ajm/ffmpeg_decoder_common.h" + +#include <algorithm> +#include <cinttypes> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <vector> + +namespace Libs::Audio::Ajm { + +struct AjmDecOpusInitializeParameters { + uint32_t channel_num; + uint32_t sample_rate; + uint32_t mapping_family; +}; + +struct AjmSidebandDecOpusCodecInfo { + uint32_t frames_per_packet; +}; + +static_assert(sizeof(AjmDecOpusInitializeParameters) == 12); +static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4); + +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10; +static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP = 0; +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP = 2; +static constexpr size_t AJM_DEC_OPUS_OPUS_HEAD_SIZE = 19; +// Each access unit is a little-endian 16-bit length followed by that many packet bytes. +static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2; + +class AjmOpusDecoder final: public AjmDecoder { +public: + AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding, + uint64_t flags) + : AjmDecoder(channels, sample_rate, encoding) { + (void)flags; + m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS); + if (m_codec == nullptr) { + LOGF("AJM Opus: avcodec_find_decoder failed\n"); + } + } + + ~AjmOpusDecoder() override { Release(); } + + AjmDecodeResult Initialize(const void* codec_parameters, + size_t codec_parameters_size) override { + auto result = MakeResult(); + + if (codec_parameters == nullptr || + codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters); + if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH || + params->sample_rate == 0) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) { + LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n", + params->mapping_family); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) { + LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n", + params->channel_num); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + Release(); + SetFormat(params->channel_num, params->sample_rate, m_sample_encoding); + m_mapping_family = params->mapping_family; + m_total_decoded_samples = 0; + m_frames_per_packet = 1; + m_is_initialized = false; + + if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + + m_is_initialized = true; + + LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n", + params->sample_rate, params->channel_num, params->mapping_family); + + return MakeResult(); + } + + void Reset() override { + m_total_decoded_samples = 0; + m_pending.clear(); + m_pending_offset = 0; + if (m_codec_context != nullptr) { + avcodec_flush_buffers(m_codec_context); + } + } + + AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, + bool multiple_frames, AjmGaplessState* gapless) override { + auto result = MakeResult(); + + if (!m_is_initialized) { + result.result = AJM_RESULT_NOT_INITIALIZED; + return result; + } + if (m_codec_context == nullptr) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + if (input == nullptr || input_size == 0) { + result.result = AJM_RESULT_PARTIAL_INPUT; + return result; + } + if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + if (output != nullptr && output_size != 0) { + std::memset(output, 0, output_size); + } + + const auto* data = static_cast<const uint8_t*>(input); + size_t input_offset = 0; + size_t output_offset = 0; + bool produced = DrainPending(output, output_size, &output_offset, &result); + + while (m_pending_offset >= m_pending.size() && + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && + output_offset < output_size) { + const size_t length = static_cast<size_t>(data[input_offset]) | + (static_cast<size_t>(data[input_offset + 1]) << 8u); + if (length == 0 || + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { + result.result |= AJM_RESULT_INVALID_DATA; + break; + } + + if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, + static_cast<int>(length), gapless, &result)) { + break; + } + + input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; + produced = DrainPending(output, output_size, &output_offset, &result) || produced; + if (!multiple_frames) { + break; + } + } + + if (m_pending_offset < m_pending.size()) { + result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; + } + if (!produced && result.result == OK) { + result.result = AJM_RESULT_PARTIAL_INPUT; + } + + result.input_consumed = input_offset; + result.output_written = output_offset; + result.frames_per_packet = m_frames_per_packet; + result.total_decoded_samples = m_total_decoded_samples; + result.format = GetFormat(); + return result; + } + + void WriteCodecInfo(void* output, size_t output_size, + const AjmDecodeResult& result) const override { + (void)result; + if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { + return; + } + + auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); + info->frames_per_packet = m_frames_per_packet; + } + + [[nodiscard]] size_t CodecInfoSize() const override { + return sizeof(AjmSidebandDecOpusCodecInfo); + } + + [[nodiscard]] AjmSidebandFormat GetFormat() const override { + return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); + } + +private: + void Release() { + if (m_codec_context != nullptr) { + avcodec_free_context(&m_codec_context); + } + } + // The instance carries no container, so the identification header is rebuilt here. + static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate, + uint32_t mapping_family) { + std::memcpy(head, "OpusHead", 8); + head[8] = 1; + head[9] = static_cast<uint8_t>(channels); + head[10] = 0; + head[11] = 0; + head[12] = static_cast<uint8_t>(sample_rate & 0xffu); + head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu); + head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu); + head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu); + head[16] = 0; + head[17] = 0; + head[18] = static_cast<uint8_t>(mapping_family); + } + + bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) { + if (m_codec == nullptr) { + return false; + } + + m_codec_context = avcodec_alloc_context3(m_codec); + if (m_codec_context == nullptr) { + return false; + } + + m_codec_context->sample_rate = static_cast<int>(sample_rate); + av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels)); + + auto* extradata = static_cast<uint8_t*>( + av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE)); + if (extradata == nullptr) { + Release(); + return false; + } + FillOpusHead(extradata, channels, sample_rate, mapping_family); + m_codec_context->extradata = extradata; + m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE); + + if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) { + LOGF("AJM Opus: decoder initialization failed\n"); + Release(); + return false; + } + + return true; + } + + bool DrainPending(void* output, size_t output_size, size_t* output_offset, + AjmDecodeResult* result) { + if (output == nullptr || output_offset == nullptr || result == nullptr) { + return false; + } + const auto available = m_pending.size() - m_pending_offset; + if (available == 0 || *output_offset >= output_size) { + return false; + } + const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + return false; + } + + auto bytes = std::min(available, output_size - *output_offset); + bytes -= bytes % bpf; + if (bytes == 0) { + return false; + } + + std::memcpy(static_cast<uint8_t*>(output) + *output_offset, + m_pending.data() + m_pending_offset, bytes); + *output_offset += bytes; + m_pending_offset += bytes; + if (m_pending_offset >= m_pending.size()) { + m_pending.clear(); + m_pending_offset = 0; + } + + const auto samples = static_cast<uint32_t>(bytes / bpf); + m_total_decoded_samples += samples; + result->total_decoded_samples = m_total_decoded_samples; + result->format = GetFormat(); + return samples != 0; + } + + bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) { + if (frame == nullptr || result == nullptr) { + return false; + } + + const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1)); + if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) { + result->result = AJM_RESULT_TOO_MANY_CHANNELS; + return false; + } + const auto bpf = channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + result->result = AJM_RESULT_INVALID_PARAMETER; + return false; + } + + SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)), + m_sample_encoding); ``` `AjmConvertFfmpegFrame` is shared with the AAC, MP3 and ATRAC9 decoders where taking the frame rate is correct, so adding a target rate parameter there reaches further than this PR. Every Opus stream I have seen initializes at 48000 Hz, but I can reject other rates in `Initialize` with a log line if preferred.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-27 00:16 UTC · original
On src/libs/ajm/opus_decoder.h line 304 (outdated):

@@ -0,0 +1,409 @@
+#pragma once
+
+#include "common/logging/log.h"
+#include "libs/ajm/decoder.h"
+#include "libs/ajm/ffmpeg_decoder_common.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <vector>
+
+namespace Libs::Audio::Ajm {
+
+struct AjmDecOpusInitializeParameters {
+	uint32_t channel_num;
+	uint32_t sample_rate;
+	uint32_t mapping_family;
+};
+
+struct AjmSidebandDecOpusCodecInfo {
+	uint32_t frames_per_packet;
+};
+
+static_assert(sizeof(AjmDecOpusInitializeParameters) == 12);
+static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4);
+
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10;
+static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP    = 0;
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP      = 2;
+static constexpr size_t   AJM_DEC_OPUS_OPUS_HEAD_SIZE        = 19;
+// Each access unit is a little-endian 16-bit length followed by that many packet bytes.
+static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2;
+
+class AjmOpusDecoder final: public AjmDecoder {
+public:
+	AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding,
+	               uint64_t flags)
+	    : AjmDecoder(channels, sample_rate, encoding) {
+		(void)flags;
+		m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
+		if (m_codec == nullptr) {
+			LOGF("AJM Opus: avcodec_find_decoder failed\n");
+		}
+	}
+
+	~AjmOpusDecoder() override { Release(); }
+
+	AjmDecodeResult Initialize(const void* codec_parameters,
+	                           size_t      codec_parameters_size) override {
+		auto result = MakeResult();
+
+		if (codec_parameters == nullptr ||
+		    codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters);
+		if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH ||
+		    params->sample_rate == 0) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) {
+			LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n",
+			     params->mapping_family);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) {
+			LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n",
+			     params->channel_num);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		Release();
+		SetFormat(params->channel_num, params->sample_rate, m_sample_encoding);
+		m_mapping_family        = params->mapping_family;
+		m_total_decoded_samples = 0;
+		m_frames_per_packet     = 1;
+		m_is_initialized        = false;
+
+		if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+
+		m_is_initialized = true;
+
+		LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n",
+		     params->sample_rate, params->channel_num, params->mapping_family);
+
+		return MakeResult();
+	}
+
+	void Reset() override {
+		m_total_decoded_samples = 0;
+		m_pending.clear();
+		m_pending_offset = 0;
+		if (m_codec_context != nullptr) {
+			avcodec_flush_buffers(m_codec_context);
+		}
+	}
+
+	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
+	                       bool multiple_frames, AjmGaplessState* gapless) override {
+		auto result = MakeResult();
+
+		if (!m_is_initialized) {
+			result.result = AJM_RESULT_NOT_INITIALIZED;
+			return result;
+		}
+		if (m_codec_context == nullptr) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+		if (input == nullptr || input_size == 0) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+			return result;
+		}
+		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		if (output != nullptr && output_size != 0) {
+			std::memset(output, 0, output_size);
+		}
+
+		const auto* data          = static_cast<const uint8_t*>(input);
+		size_t      input_offset  = 0;
+		size_t      output_offset = 0;
+		bool        produced      = DrainPending(output, output_size, &output_offset, &result);
+
+		while (m_pending_offset >= m_pending.size() &&
+		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
+		       output_offset < output_size) {
+			const size_t length = static_cast<size_t>(data[input_offset]) |
+			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
+			if (length == 0 ||
+			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
+				result.result |= AJM_RESULT_INVALID_DATA;
+				break;
+			}
+
+			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
+			                  static_cast<int>(length), gapless, &result)) {
+				break;
+			}
+
+			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
+			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
+			if (!multiple_frames) {
+				break;
+			}
+		}
+
+		if (m_pending_offset < m_pending.size()) {
+			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
+		}
+		if (!produced && result.result == OK) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+		}
+
+		result.input_consumed        = input_offset;
+		result.output_written        = output_offset;
+		result.frames_per_packet     = m_frames_per_packet;
+		result.total_decoded_samples = m_total_decoded_samples;
+		result.format                = GetFormat();
+		return result;
+	}
+
+	void WriteCodecInfo(void* output, size_t output_size,
+	                    const AjmDecodeResult& result) const override {
+		(void)result;
+		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
+			return;
+		}
+
+		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
+		info->frames_per_packet = m_frames_per_packet;
+	}
+
+	[[nodiscard]] size_t CodecInfoSize() const override {
+		return sizeof(AjmSidebandDecOpusCodecInfo);
+	}
+
+	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
+		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
+	}
+
+private:
+	void Release() {
+		if (m_codec_context != nullptr) {
+			avcodec_free_context(&m_codec_context);
+		}
+	}
+	// The instance carries no container, so the identification header is rebuilt here.
+	static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate,
+	                         uint32_t mapping_family) {
+		std::memcpy(head, "OpusHead", 8);
+		head[8]  = 1;
+		head[9]  = static_cast<uint8_t>(channels);
+		head[10] = 0;
+		head[11] = 0;
+		head[12] = static_cast<uint8_t>(sample_rate & 0xffu);
+		head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu);
+		head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu);
+		head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu);
+		head[16] = 0;
+		head[17] = 0;
+		head[18] = static_cast<uint8_t>(mapping_family);
+	}
+
+	bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) {
+		if (m_codec == nullptr) {
+			return false;
+		}
+
+		m_codec_context = avcodec_alloc_context3(m_codec);
+		if (m_codec_context == nullptr) {
+			return false;
+		}
+
+		m_codec_context->sample_rate = static_cast<int>(sample_rate);
+		av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels));
+
+		auto* extradata = static_cast<uint8_t*>(
+		    av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
+		if (extradata == nullptr) {
+			Release();
+			return false;
+		}
+		FillOpusHead(extradata, channels, sample_rate, mapping_family);
+		m_codec_context->extradata      = extradata;
+		m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE);
+
+		if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) {
+			LOGF("AJM Opus: decoder initialization failed\n");
+			Release();
+			return false;
+		}
+
+		return true;
+	}
+
+	bool DrainPending(void* output, size_t output_size, size_t* output_offset,
+	                  AjmDecodeResult* result) {
+		if (output == nullptr || output_offset == nullptr || result == nullptr) {
+			return false;
+		}
+		const auto available = m_pending.size() - m_pending_offset;
+		if (available == 0 || *output_offset >= output_size) {
+			return false;
+		}
+		const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			return false;
+		}
+
+		auto bytes = std::min(available, output_size - *output_offset);
+		bytes -= bytes % bpf;
+		if (bytes == 0) {
+			return false;
+		}
+
+		std::memcpy(static_cast<uint8_t*>(output) + *output_offset,
+		            m_pending.data() + m_pending_offset, bytes);
+		*output_offset += bytes;
+		m_pending_offset += bytes;
+		if (m_pending_offset >= m_pending.size()) {
+			m_pending.clear();
+			m_pending_offset = 0;
+		}
+
+		const auto samples = static_cast<uint32_t>(bytes / bpf);
+		m_total_decoded_samples += samples;
+		result->total_decoded_samples = m_total_decoded_samples;
+		result->format                = GetFormat();
+		return samples != 0;
+	}
+
+	bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) {
+		if (frame == nullptr || result == nullptr) {
+			return false;
+		}
+
+		const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1));
+		if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) {
+			result->result = AJM_RESULT_TOO_MANY_CHANNELS;
+			return false;
+		}
+		const auto bpf = channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			result->result = AJM_RESULT_INVALID_PARAMETER;
+			return false;
+		}
+
+		SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)),
+		          m_sample_encoding);

@joaodiaslobo, thanks for the clarification. I agree that changing AjmConvertFfmpegFrame would affect decoders outside this PR.

For this PR, please reject non-48000 Hz rates in AjmOpusDecoder::Initialize and log the unsupported rate. That keeps the accepted initialization rates consistent with the PCM rate produced by the current FFmpeg Opus path. Lower-rate output can be added later if needed.


✏️ Learnings added
Learnt from: joaodiaslobo
Repo: KytyPS5/KytyPS5 PR: 858
File: src/libs/ajm/opus_decoder.h:305-306
Timestamp: 2026-09-27T00:16:25.000Z
Learning: In `src/libs/ajm/opus_decoder.h`, `AjmConvertFfmpegFrame` is shared with the AJM AAC, MP3, and ATRAC9 decoders. Those decoders use the decoded frame's sample rate, so an Opus-specific output-rate policy should not change the shared conversion behavior for them.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-27 00:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#discussion_r4113489014) On `src/libs/ajm/opus_decoder.h` line 304 (outdated): ```diff @@ -0,0 +1,409 @@ +#pragma once + +#include "common/logging/log.h" +#include "libs/ajm/decoder.h" +#include "libs/ajm/ffmpeg_decoder_common.h" + +#include <algorithm> +#include <cinttypes> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <vector> + +namespace Libs::Audio::Ajm { + +struct AjmDecOpusInitializeParameters { + uint32_t channel_num; + uint32_t sample_rate; + uint32_t mapping_family; +}; + +struct AjmSidebandDecOpusCodecInfo { + uint32_t frames_per_packet; +}; + +static_assert(sizeof(AjmDecOpusInitializeParameters) == 12); +static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4); + +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10; +static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP = 0; +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP = 2; +static constexpr size_t AJM_DEC_OPUS_OPUS_HEAD_SIZE = 19; +// Each access unit is a little-endian 16-bit length followed by that many packet bytes. +static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2; + +class AjmOpusDecoder final: public AjmDecoder { +public: + AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding, + uint64_t flags) + : AjmDecoder(channels, sample_rate, encoding) { + (void)flags; + m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS); + if (m_codec == nullptr) { + LOGF("AJM Opus: avcodec_find_decoder failed\n"); + } + } + + ~AjmOpusDecoder() override { Release(); } + + AjmDecodeResult Initialize(const void* codec_parameters, + size_t codec_parameters_size) override { + auto result = MakeResult(); + + if (codec_parameters == nullptr || + codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters); + if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH || + params->sample_rate == 0) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) { + LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n", + params->mapping_family); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) { + LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n", + params->channel_num); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + Release(); + SetFormat(params->channel_num, params->sample_rate, m_sample_encoding); + m_mapping_family = params->mapping_family; + m_total_decoded_samples = 0; + m_frames_per_packet = 1; + m_is_initialized = false; + + if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + + m_is_initialized = true; + + LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n", + params->sample_rate, params->channel_num, params->mapping_family); + + return MakeResult(); + } + + void Reset() override { + m_total_decoded_samples = 0; + m_pending.clear(); + m_pending_offset = 0; + if (m_codec_context != nullptr) { + avcodec_flush_buffers(m_codec_context); + } + } + + AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, + bool multiple_frames, AjmGaplessState* gapless) override { + auto result = MakeResult(); + + if (!m_is_initialized) { + result.result = AJM_RESULT_NOT_INITIALIZED; + return result; + } + if (m_codec_context == nullptr) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + if (input == nullptr || input_size == 0) { + result.result = AJM_RESULT_PARTIAL_INPUT; + return result; + } + if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + if (output != nullptr && output_size != 0) { + std::memset(output, 0, output_size); + } + + const auto* data = static_cast<const uint8_t*>(input); + size_t input_offset = 0; + size_t output_offset = 0; + bool produced = DrainPending(output, output_size, &output_offset, &result); + + while (m_pending_offset >= m_pending.size() && + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && + output_offset < output_size) { + const size_t length = static_cast<size_t>(data[input_offset]) | + (static_cast<size_t>(data[input_offset + 1]) << 8u); + if (length == 0 || + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { + result.result |= AJM_RESULT_INVALID_DATA; + break; + } + + if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, + static_cast<int>(length), gapless, &result)) { + break; + } + + input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; + produced = DrainPending(output, output_size, &output_offset, &result) || produced; + if (!multiple_frames) { + break; + } + } + + if (m_pending_offset < m_pending.size()) { + result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; + } + if (!produced && result.result == OK) { + result.result = AJM_RESULT_PARTIAL_INPUT; + } + + result.input_consumed = input_offset; + result.output_written = output_offset; + result.frames_per_packet = m_frames_per_packet; + result.total_decoded_samples = m_total_decoded_samples; + result.format = GetFormat(); + return result; + } + + void WriteCodecInfo(void* output, size_t output_size, + const AjmDecodeResult& result) const override { + (void)result; + if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { + return; + } + + auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); + info->frames_per_packet = m_frames_per_packet; + } + + [[nodiscard]] size_t CodecInfoSize() const override { + return sizeof(AjmSidebandDecOpusCodecInfo); + } + + [[nodiscard]] AjmSidebandFormat GetFormat() const override { + return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); + } + +private: + void Release() { + if (m_codec_context != nullptr) { + avcodec_free_context(&m_codec_context); + } + } + // The instance carries no container, so the identification header is rebuilt here. + static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate, + uint32_t mapping_family) { + std::memcpy(head, "OpusHead", 8); + head[8] = 1; + head[9] = static_cast<uint8_t>(channels); + head[10] = 0; + head[11] = 0; + head[12] = static_cast<uint8_t>(sample_rate & 0xffu); + head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu); + head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu); + head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu); + head[16] = 0; + head[17] = 0; + head[18] = static_cast<uint8_t>(mapping_family); + } + + bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) { + if (m_codec == nullptr) { + return false; + } + + m_codec_context = avcodec_alloc_context3(m_codec); + if (m_codec_context == nullptr) { + return false; + } + + m_codec_context->sample_rate = static_cast<int>(sample_rate); + av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels)); + + auto* extradata = static_cast<uint8_t*>( + av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE)); + if (extradata == nullptr) { + Release(); + return false; + } + FillOpusHead(extradata, channels, sample_rate, mapping_family); + m_codec_context->extradata = extradata; + m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE); + + if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) { + LOGF("AJM Opus: decoder initialization failed\n"); + Release(); + return false; + } + + return true; + } + + bool DrainPending(void* output, size_t output_size, size_t* output_offset, + AjmDecodeResult* result) { + if (output == nullptr || output_offset == nullptr || result == nullptr) { + return false; + } + const auto available = m_pending.size() - m_pending_offset; + if (available == 0 || *output_offset >= output_size) { + return false; + } + const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + return false; + } + + auto bytes = std::min(available, output_size - *output_offset); + bytes -= bytes % bpf; + if (bytes == 0) { + return false; + } + + std::memcpy(static_cast<uint8_t*>(output) + *output_offset, + m_pending.data() + m_pending_offset, bytes); + *output_offset += bytes; + m_pending_offset += bytes; + if (m_pending_offset >= m_pending.size()) { + m_pending.clear(); + m_pending_offset = 0; + } + + const auto samples = static_cast<uint32_t>(bytes / bpf); + m_total_decoded_samples += samples; + result->total_decoded_samples = m_total_decoded_samples; + result->format = GetFormat(); + return samples != 0; + } + + bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) { + if (frame == nullptr || result == nullptr) { + return false; + } + + const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1)); + if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) { + result->result = AJM_RESULT_TOO_MANY_CHANNELS; + return false; + } + const auto bpf = channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + result->result = AJM_RESULT_INVALID_PARAMETER; + return false; + } + + SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)), + m_sample_encoding); ``` `@joaodiaslobo`, thanks for the clarification. I agree that changing `AjmConvertFfmpegFrame` would affect decoders outside this PR. For this PR, please reject non-48000 Hz rates in `AjmOpusDecoder::Initialize` and log the unsupported rate. That keeps the accepted initialization rates consistent with the PCM rate produced by the current FFmpeg Opus path. Lower-rate output can be added later if needed. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: joaodiaslobo Repo: KytyPS5/KytyPS5 PR: 858 File: src/libs/ajm/opus_decoder.h:305-306 Timestamp: 2026-09-27T00:16:25.000Z Learning: In `src/libs/ajm/opus_decoder.h`, `AjmConvertFfmpegFrame` is shared with the AJM AAC, MP3, and ATRAC9 decoders. Those decoders use the decoded frame's sample rate, so an Opus-specific output-rate policy should not change the shared conversion behavior for them. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠joaodiaslobo on GitHub · 2026-09-27 00:23 UTC · original
On src/libs/ajm/opus_decoder.h line 304 (outdated):

@@ -0,0 +1,409 @@
+#pragma once
+
+#include "common/logging/log.h"
+#include "libs/ajm/decoder.h"
+#include "libs/ajm/ffmpeg_decoder_common.h"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <vector>
+
+namespace Libs::Audio::Ajm {
+
+struct AjmDecOpusInitializeParameters {
+	uint32_t channel_num;
+	uint32_t sample_rate;
+	uint32_t mapping_family;
+};
+
+struct AjmSidebandDecOpusCodecInfo {
+	uint32_t frames_per_packet;
+};
+
+static_assert(sizeof(AjmDecOpusInitializeParameters) == 12);
+static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4);
+
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10;
+static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP    = 0;
+static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP      = 2;
+static constexpr size_t   AJM_DEC_OPUS_OPUS_HEAD_SIZE        = 19;
+// Each access unit is a little-endian 16-bit length followed by that many packet bytes.
+static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2;
+
+class AjmOpusDecoder final: public AjmDecoder {
+public:
+	AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding,
+	               uint64_t flags)
+	    : AjmDecoder(channels, sample_rate, encoding) {
+		(void)flags;
+		m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
+		if (m_codec == nullptr) {
+			LOGF("AJM Opus: avcodec_find_decoder failed\n");
+		}
+	}
+
+	~AjmOpusDecoder() override { Release(); }
+
+	AjmDecodeResult Initialize(const void* codec_parameters,
+	                           size_t      codec_parameters_size) override {
+		auto result = MakeResult();
+
+		if (codec_parameters == nullptr ||
+		    codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters);
+		if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH ||
+		    params->sample_rate == 0) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) {
+			LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n",
+			     params->mapping_family);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+		if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) {
+			LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n",
+			     params->channel_num);
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		Release();
+		SetFormat(params->channel_num, params->sample_rate, m_sample_encoding);
+		m_mapping_family        = params->mapping_family;
+		m_total_decoded_samples = 0;
+		m_frames_per_packet     = 1;
+		m_is_initialized        = false;
+
+		if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+
+		m_is_initialized = true;
+
+		LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n",
+		     params->sample_rate, params->channel_num, params->mapping_family);
+
+		return MakeResult();
+	}
+
+	void Reset() override {
+		m_total_decoded_samples = 0;
+		m_pending.clear();
+		m_pending_offset = 0;
+		if (m_codec_context != nullptr) {
+			avcodec_flush_buffers(m_codec_context);
+		}
+	}
+
+	AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size,
+	                       bool multiple_frames, AjmGaplessState* gapless) override {
+		auto result = MakeResult();
+
+		if (!m_is_initialized) {
+			result.result = AJM_RESULT_NOT_INITIALIZED;
+			return result;
+		}
+		if (m_codec_context == nullptr) {
+			result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL;
+			return result;
+		}
+		if (input == nullptr || input_size == 0) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+			return result;
+		}
+		if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
+			result.result = AJM_RESULT_INVALID_PARAMETER;
+			return result;
+		}
+
+		if (output != nullptr && output_size != 0) {
+			std::memset(output, 0, output_size);
+		}
+
+		const auto* data          = static_cast<const uint8_t*>(input);
+		size_t      input_offset  = 0;
+		size_t      output_offset = 0;
+		bool        produced      = DrainPending(output, output_size, &output_offset, &result);
+
+		while (m_pending_offset >= m_pending.size() &&
+		       input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size &&
+		       output_offset < output_size) {
+			const size_t length = static_cast<size_t>(data[input_offset]) |
+			                      (static_cast<size_t>(data[input_offset + 1]) << 8u);
+			if (length == 0 ||
+			    input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) {
+				result.result |= AJM_RESULT_INVALID_DATA;
+				break;
+			}
+
+			if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE,
+			                  static_cast<int>(length), gapless, &result)) {
+				break;
+			}
+
+			input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length;
+			produced = DrainPending(output, output_size, &output_offset, &result) || produced;
+			if (!multiple_frames) {
+				break;
+			}
+		}
+
+		if (m_pending_offset < m_pending.size()) {
+			result.result |= AJM_RESULT_NOT_ENOUGH_ROOM;
+		}
+		if (!produced && result.result == OK) {
+			result.result = AJM_RESULT_PARTIAL_INPUT;
+		}
+
+		result.input_consumed        = input_offset;
+		result.output_written        = output_offset;
+		result.frames_per_packet     = m_frames_per_packet;
+		result.total_decoded_samples = m_total_decoded_samples;
+		result.format                = GetFormat();
+		return result;
+	}
+
+	void WriteCodecInfo(void* output, size_t output_size,
+	                    const AjmDecodeResult& result) const override {
+		(void)result;
+		if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) {
+			return;
+		}
+
+		auto* info              = static_cast<AjmSidebandDecOpusCodecInfo*>(output);
+		info->frames_per_packet = m_frames_per_packet;
+	}
+
+	[[nodiscard]] size_t CodecInfoSize() const override {
+		return sizeof(AjmSidebandDecOpusCodecInfo);
+	}
+
+	[[nodiscard]] AjmSidebandFormat GetFormat() const override {
+		return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding);
+	}
+
+private:
+	void Release() {
+		if (m_codec_context != nullptr) {
+			avcodec_free_context(&m_codec_context);
+		}
+	}
+	// The instance carries no container, so the identification header is rebuilt here.
+	static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate,
+	                         uint32_t mapping_family) {
+		std::memcpy(head, "OpusHead", 8);
+		head[8]  = 1;
+		head[9]  = static_cast<uint8_t>(channels);
+		head[10] = 0;
+		head[11] = 0;
+		head[12] = static_cast<uint8_t>(sample_rate & 0xffu);
+		head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu);
+		head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu);
+		head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu);
+		head[16] = 0;
+		head[17] = 0;
+		head[18] = static_cast<uint8_t>(mapping_family);
+	}
+
+	bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) {
+		if (m_codec == nullptr) {
+			return false;
+		}
+
+		m_codec_context = avcodec_alloc_context3(m_codec);
+		if (m_codec_context == nullptr) {
+			return false;
+		}
+
+		m_codec_context->sample_rate = static_cast<int>(sample_rate);
+		av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels));
+
+		auto* extradata = static_cast<uint8_t*>(
+		    av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
+		if (extradata == nullptr) {
+			Release();
+			return false;
+		}
+		FillOpusHead(extradata, channels, sample_rate, mapping_family);
+		m_codec_context->extradata      = extradata;
+		m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE);
+
+		if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) {
+			LOGF("AJM Opus: decoder initialization failed\n");
+			Release();
+			return false;
+		}
+
+		return true;
+	}
+
+	bool DrainPending(void* output, size_t output_size, size_t* output_offset,
+	                  AjmDecodeResult* result) {
+		if (output == nullptr || output_offset == nullptr || result == nullptr) {
+			return false;
+		}
+		const auto available = m_pending.size() - m_pending_offset;
+		if (available == 0 || *output_offset >= output_size) {
+			return false;
+		}
+		const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			return false;
+		}
+
+		auto bytes = std::min(available, output_size - *output_offset);
+		bytes -= bytes % bpf;
+		if (bytes == 0) {
+			return false;
+		}
+
+		std::memcpy(static_cast<uint8_t*>(output) + *output_offset,
+		            m_pending.data() + m_pending_offset, bytes);
+		*output_offset += bytes;
+		m_pending_offset += bytes;
+		if (m_pending_offset >= m_pending.size()) {
+			m_pending.clear();
+			m_pending_offset = 0;
+		}
+
+		const auto samples = static_cast<uint32_t>(bytes / bpf);
+		m_total_decoded_samples += samples;
+		result->total_decoded_samples = m_total_decoded_samples;
+		result->format                = GetFormat();
+		return samples != 0;
+	}
+
+	bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) {
+		if (frame == nullptr || result == nullptr) {
+			return false;
+		}
+
+		const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1));
+		if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) {
+			result->result = AJM_RESULT_TOO_MANY_CHANNELS;
+			return false;
+		}
+		const auto bpf = channels * AjmBytesPerSample(m_sample_encoding);
+		if (bpf == 0) {
+			result->result = AJM_RESULT_INVALID_PARAMETER;
+			return false;
+		}
+
+		SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)),
+		          m_sample_encoding);

Added the rate rejection in Initialize.

**@⁠joaodiaslobo** on GitHub · 2026-09-27 00:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/858#discussion_r4113506380) On `src/libs/ajm/opus_decoder.h` line 304 (outdated): ```diff @@ -0,0 +1,409 @@ +#pragma once + +#include "common/logging/log.h" +#include "libs/ajm/decoder.h" +#include "libs/ajm/ffmpeg_decoder_common.h" + +#include <algorithm> +#include <cinttypes> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <vector> + +namespace Libs::Audio::Ajm { + +struct AjmDecOpusInitializeParameters { + uint32_t channel_num; + uint32_t sample_rate; + uint32_t mapping_family; +}; + +struct AjmSidebandDecOpusCodecInfo { + uint32_t frames_per_packet; +}; + +static_assert(sizeof(AjmDecOpusInitializeParameters) == 12); +static_assert(sizeof(AjmSidebandDecOpusCodecInfo) == 4); + +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH = 10; +static constexpr uint32_t AJM_DEC_OPUS_MAPPING_FAMILY_RTP = 0; +static constexpr uint32_t AJM_DEC_OPUS_MAX_CHANNELS_RTP = 2; +static constexpr size_t AJM_DEC_OPUS_OPUS_HEAD_SIZE = 19; +// Each access unit is a little-endian 16-bit length followed by that many packet bytes. +static constexpr size_t AJM_DEC_OPUS_PACKET_LENGTH_SIZE = 2; + +class AjmOpusDecoder final: public AjmDecoder { +public: + AjmOpusDecoder(uint32_t channels, uint32_t sample_rate, AjmSampleEncoding encoding, + uint64_t flags) + : AjmDecoder(channels, sample_rate, encoding) { + (void)flags; + m_codec = avcodec_find_decoder(AV_CODEC_ID_OPUS); + if (m_codec == nullptr) { + LOGF("AJM Opus: avcodec_find_decoder failed\n"); + } + } + + ~AjmOpusDecoder() override { Release(); } + + AjmDecodeResult Initialize(const void* codec_parameters, + size_t codec_parameters_size) override { + auto result = MakeResult(); + + if (codec_parameters == nullptr || + codec_parameters_size < sizeof(AjmDecOpusInitializeParameters)) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + const auto* params = static_cast<const AjmDecOpusInitializeParameters*>(codec_parameters); + if (params->channel_num == 0 || params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH || + params->sample_rate == 0) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->mapping_family != AJM_DEC_OPUS_MAPPING_FAMILY_RTP) { + LOGF("AJM Opus: mapping family %" PRIu32 " is not implemented\n", + params->mapping_family); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + if (params->channel_num > AJM_DEC_OPUS_MAX_CHANNELS_RTP) { + LOGF("AJM Opus: mapping family 0 does not define %" PRIu32 " channels\n", + params->channel_num); + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + Release(); + SetFormat(params->channel_num, params->sample_rate, m_sample_encoding); + m_mapping_family = params->mapping_family; + m_total_decoded_samples = 0; + m_frames_per_packet = 1; + m_is_initialized = false; + + if (!OpenDecoder(params->channel_num, params->sample_rate, params->mapping_family)) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + + m_is_initialized = true; + + LOGF("AJM Opus initialized: %" PRIu32 " Hz, %" PRIu32 " ch, mapping=%" PRIu32 "\n", + params->sample_rate, params->channel_num, params->mapping_family); + + return MakeResult(); + } + + void Reset() override { + m_total_decoded_samples = 0; + m_pending.clear(); + m_pending_offset = 0; + if (m_codec_context != nullptr) { + avcodec_flush_buffers(m_codec_context); + } + } + + AjmDecodeResult Decode(const void* input, size_t input_size, void* output, size_t output_size, + bool multiple_frames, AjmGaplessState* gapless) override { + auto result = MakeResult(); + + if (!m_is_initialized) { + result.result = AJM_RESULT_NOT_INITIALIZED; + return result; + } + if (m_codec_context == nullptr) { + result.result = AJM_RESULT_CODEC_ERROR | AJM_RESULT_FATAL; + return result; + } + if (input == nullptr || input_size == 0) { + result.result = AJM_RESULT_PARTIAL_INPUT; + return result; + } + if (input_size > static_cast<size_t>(std::numeric_limits<int>::max())) { + result.result = AJM_RESULT_INVALID_PARAMETER; + return result; + } + + if (output != nullptr && output_size != 0) { + std::memset(output, 0, output_size); + } + + const auto* data = static_cast<const uint8_t*>(input); + size_t input_offset = 0; + size_t output_offset = 0; + bool produced = DrainPending(output, output_size, &output_offset, &result); + + while (m_pending_offset >= m_pending.size() && + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE <= input_size && + output_offset < output_size) { + const size_t length = static_cast<size_t>(data[input_offset]) | + (static_cast<size_t>(data[input_offset + 1]) << 8u); + if (length == 0 || + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length > input_size) { + result.result |= AJM_RESULT_INVALID_DATA; + break; + } + + if (!DecodePacket(data + input_offset + AJM_DEC_OPUS_PACKET_LENGTH_SIZE, + static_cast<int>(length), gapless, &result)) { + break; + } + + input_offset += AJM_DEC_OPUS_PACKET_LENGTH_SIZE + length; + produced = DrainPending(output, output_size, &output_offset, &result) || produced; + if (!multiple_frames) { + break; + } + } + + if (m_pending_offset < m_pending.size()) { + result.result |= AJM_RESULT_NOT_ENOUGH_ROOM; + } + if (!produced && result.result == OK) { + result.result = AJM_RESULT_PARTIAL_INPUT; + } + + result.input_consumed = input_offset; + result.output_written = output_offset; + result.frames_per_packet = m_frames_per_packet; + result.total_decoded_samples = m_total_decoded_samples; + result.format = GetFormat(); + return result; + } + + void WriteCodecInfo(void* output, size_t output_size, + const AjmDecodeResult& result) const override { + (void)result; + if (output == nullptr || output_size < sizeof(AjmSidebandDecOpusCodecInfo)) { + return; + } + + auto* info = static_cast<AjmSidebandDecOpusCodecInfo*>(output); + info->frames_per_packet = m_frames_per_packet; + } + + [[nodiscard]] size_t CodecInfoSize() const override { + return sizeof(AjmSidebandDecOpusCodecInfo); + } + + [[nodiscard]] AjmSidebandFormat GetFormat() const override { + return AjmMakeFormat(m_channels, m_sample_rate, m_sample_encoding); + } + +private: + void Release() { + if (m_codec_context != nullptr) { + avcodec_free_context(&m_codec_context); + } + } + // The instance carries no container, so the identification header is rebuilt here. + static void FillOpusHead(uint8_t* head, uint32_t channels, uint32_t sample_rate, + uint32_t mapping_family) { + std::memcpy(head, "OpusHead", 8); + head[8] = 1; + head[9] = static_cast<uint8_t>(channels); + head[10] = 0; + head[11] = 0; + head[12] = static_cast<uint8_t>(sample_rate & 0xffu); + head[13] = static_cast<uint8_t>((sample_rate >> 8u) & 0xffu); + head[14] = static_cast<uint8_t>((sample_rate >> 16u) & 0xffu); + head[15] = static_cast<uint8_t>((sample_rate >> 24u) & 0xffu); + head[16] = 0; + head[17] = 0; + head[18] = static_cast<uint8_t>(mapping_family); + } + + bool OpenDecoder(uint32_t channels, uint32_t sample_rate, uint32_t mapping_family) { + if (m_codec == nullptr) { + return false; + } + + m_codec_context = avcodec_alloc_context3(m_codec); + if (m_codec_context == nullptr) { + return false; + } + + m_codec_context->sample_rate = static_cast<int>(sample_rate); + av_channel_layout_default(&m_codec_context->ch_layout, static_cast<int>(channels)); + + auto* extradata = static_cast<uint8_t*>( + av_mallocz(AJM_DEC_OPUS_OPUS_HEAD_SIZE + AV_INPUT_BUFFER_PADDING_SIZE)); + if (extradata == nullptr) { + Release(); + return false; + } + FillOpusHead(extradata, channels, sample_rate, mapping_family); + m_codec_context->extradata = extradata; + m_codec_context->extradata_size = static_cast<int>(AJM_DEC_OPUS_OPUS_HEAD_SIZE); + + if (avcodec_open2(m_codec_context, m_codec, nullptr) < 0) { + LOGF("AJM Opus: decoder initialization failed\n"); + Release(); + return false; + } + + return true; + } + + bool DrainPending(void* output, size_t output_size, size_t* output_offset, + AjmDecodeResult* result) { + if (output == nullptr || output_offset == nullptr || result == nullptr) { + return false; + } + const auto available = m_pending.size() - m_pending_offset; + if (available == 0 || *output_offset >= output_size) { + return false; + } + const auto bpf = m_channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + return false; + } + + auto bytes = std::min(available, output_size - *output_offset); + bytes -= bytes % bpf; + if (bytes == 0) { + return false; + } + + std::memcpy(static_cast<uint8_t*>(output) + *output_offset, + m_pending.data() + m_pending_offset, bytes); + *output_offset += bytes; + m_pending_offset += bytes; + if (m_pending_offset >= m_pending.size()) { + m_pending.clear(); + m_pending_offset = 0; + } + + const auto samples = static_cast<uint32_t>(bytes / bpf); + m_total_decoded_samples += samples; + result->total_decoded_samples = m_total_decoded_samples; + result->format = GetFormat(); + return samples != 0; + } + + bool AppendFrame(const AVFrame* frame, AjmGaplessState* gapless, AjmDecodeResult* result) { + if (frame == nullptr || result == nullptr) { + return false; + } + + const auto channels = static_cast<uint32_t>(std::max(frame->ch_layout.nb_channels, 1)); + if (channels > AJM_DEC_OPUS_MAX_CHANNELS_FOR_10CH) { + result->result = AJM_RESULT_TOO_MANY_CHANNELS; + return false; + } + const auto bpf = channels * AjmBytesPerSample(m_sample_encoding); + if (bpf == 0) { + result->result = AJM_RESULT_INVALID_PARAMETER; + return false; + } + + SetFormat(channels, static_cast<uint32_t>(std::max(frame->sample_rate, 1)), + m_sample_encoding); ``` Added the rate rejection in `Initialize`.
This discussion has been locked. Commenting is limited to contributors.
No description provided.