From b376a0af0db163f3c74cb7eddc9fc10daaad15f0 Mon Sep 17 00:00:00 2001
From: Grzegorz Sluja <grzegorz.sluja@sigma.se>
Date: Fri, 19 Aug 2022 12:48:43 +0200
Subject: [PATCH] Play local ringback tone only if there is no incoming media

---
 channels/chan_brcm.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)

diff --git a/channels/chan_brcm.c b/channels/chan_brcm.c
index 44973c3f80..7b2f7ae291 100644
--- a/channels/chan_brcm.c
+++ b/channels/chan_brcm.c
@@ -576,8 +576,11 @@ static int brcm_indicate(struct ast_channel *ast, int condition, const void *dat
 	case AST_CONTROL_SRCCHANGE:
 		break;
 	case AST_CONTROL_RINGING:
+		ast_debug(4, "Got AST_CONTROL_RINGING on %s, sub->codec = %d\n", ast_channel_name(ast), sub->codec);
 		sub->channel_state = RINGBACK;
-		endpt_signal(sub->parent->line_id, "ringback", "on", NULL);
+		// Play local ringback tone only if there is no incoming media packet
+		if (sub->codec == -1)
+			endpt_signal(sub->parent->line_id, "ringback", "on", NULL);
 		if (sub->owner && (sub->call_id == 0)) {
 			sub->call_id = ast_channel_callid(sub->owner);
 			endpt_connection(sub->parent->line_id, sub->call_id, "update");
@@ -650,7 +653,7 @@ static int brcm_indicate(struct ast_channel *ast, int condition, const void *dat
 		res = -1;
 		break;
 	case AST_CONTROL_PROGRESS:
-		ast_debug(4, "Got PROGRESS on %s\n", ast_channel_name(ast));
+		ast_debug(4, "Got AST_CONTROL_PROGRESS on %s\n", ast_channel_name(ast));
 		/* Early media is coming our way */
 		/* What do we do with that? */
 		res = -1;
@@ -1342,10 +1345,10 @@ static int brcm_write(struct ast_channel *ast, struct ast_frame *frame)
 	if (sub->channel_state == ONHOLD) {
 		return 0;
 	}
-    if (frame->frametype == AST_FRAME_CNG) {
-        /*packet_size = sizeof(audio_packet_t) - 1 + RTP_HEADER_SIZE + frame->datalen;
-        CNG paket has only 1 data for the noise lvl, datalen=1*/
-        packet_size = sizeof(audio_packet_t) + RTP_HEADER_SIZE ;
+	if (frame->frametype == AST_FRAME_CNG) {
+		/*packet_size = sizeof(audio_packet_t) - 1 + RTP_HEADER_SIZE + frame->datalen;
+		CNG paket has only 1 data for the noise lvl, datalen=1*/
+		packet_size = sizeof(audio_packet_t) + RTP_HEADER_SIZE ;
 		ap = calloc(1, packet_size);
 		if (!ap) {
 			ast_log(LOG_ERROR, "Out of memory\n");
@@ -1373,7 +1376,7 @@ static int brcm_write(struct ast_channel *ast, struct ast_frame *frame)
 		pvt_unlock(sub->parent);
 		pe_bus_send(audio_tx_bus, (uint8_t *)ap, packet_size);
 		free(ap);
-    }
+	}
 
 	if(frame->frametype == AST_FRAME_VOICE) {
 		packet_size = sizeof(audio_packet_t) - 1 + RTP_HEADER_SIZE + frame->datalen;
-- 
GitLab