From 5606da754a720b0c923ad33eba46640f9301fc5f Mon Sep 17 00:00:00 2001
From: Joshua Colp <jcolp@digium.com>
Date: Wed, 22 Jul 2015 07:16:40 -0300
Subject: [PATCH] audiohook: Read the correct number of samples based on
 audiohook format.

Due to changes in audiohooks to support different sample rates the
underlying storage of samples is in the format of the audiohook
itself and not of the format being requested. This means that if a
channel is using G722 the samples stored will be at 16kHz. If
something subsequently reads from the audiohook at a format which
is not the same sample rate as the audiohook the number of samples
needs to be adjusted.

Given the following example:
1. Channel writing into audiohook at 16kHz (as it is using G722).
2. Chanspy reading from audiohook at 8kHz.

The original code would read 160 samples from the audiohook for
each 20ms of audio. This is incorrect. Since the audio in the
audiohook is at 16kHz the actual number needing to be read is 320.
Failure to read this much would cause the audiohook to reset
itself constantly as the buffer became full.

This change adjusts the requested number of samples by determining
the duration of audio requested and then calculating how many
samples that would be in the audiohook format.

ASTERISK-25247 #close

Change-Id: Ia91ce516121882387a315fd8ee116b118b90653d
---
 main/audiohook.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/main/audiohook.c b/main/audiohook.c
index f01a640453..c1df580df3 100644
--- a/main/audiohook.c
+++ b/main/audiohook.c
@@ -377,6 +377,16 @@ static struct ast_frame *audiohook_read_frame_helper(struct ast_audiohook *audio
 		audiohook_set_internal_rate(audiohook, ast_format_rate(format), 1);
 	}
 
+	/* If the sample rate of the requested format differs from that of the underlying audiohook
+	 * sample rate determine how many samples we actually need to get from the audiohook. This
+	 * needs to occur as the signed linear factory stores them at the rate of the audiohook.
+	 * We do this by determining the duration of audio they've requested and then determining
+	 * how many samples that would be in the audiohook format.
+	 */
+	if (ast_format_rate(format) != audiohook->hook_internal_samp_rate) {
+		samples = (audiohook->hook_internal_samp_rate / 1000) * (samples / (ast_format_rate(format) / 1000));
+	}
+
 	if (!(read_frame = (direction == AST_AUDIOHOOK_DIRECTION_BOTH ?
 		audiohook_read_frame_both(audiohook, samples, read_reference, write_reference) :
 		audiohook_read_frame_single(audiohook, samples, direction)))) {
-- 
GitLab