From c515850165b48e5988903abf921acbec9d7bafd2 Mon Sep 17 00:00:00 2001
From: Yalu Zhang <yalu.zhang@iopsys.eu>
Date: Mon, 3 Jun 2024 17:00:58 +0200
Subject: [PATCH] Reduce the jitter to trnasmit the RTP packets to network

Change the scheduling policy and proirity of the thread to run pbx_thread().
---
 main/pbx.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/main/pbx.c b/main/pbx.c
index 6aa3f51757..a9ec90004d 100644
--- a/main/pbx.c
+++ b/main/pbx.c
@@ -40,6 +40,9 @@
 #if defined(SOLARIS)
 #include <sys/loadavg.h>
 #endif
+#include <sys/types.h>
+#include <sched.h>
+#include <string.h>
 
 #include "asterisk/lock.h"
 #include "asterisk/cli.h"
@@ -4703,6 +4706,25 @@ static void *pbx_thread(void *data)
 	   PBX has finished running on the channel
 	 */
 	struct ast_channel *c = data;
+	int policy, priority_min, priority_max;
+	struct sched_param param = { .sched_priority = 0, };
+	pthread_t thread = pthread_self();
+	int tid = ast_get_tid();
+
+	// Change the thread schedule policy and priority
+	priority_min = sched_get_priority_min(SCHED_FIFO);
+	priority_max = sched_get_priority_max(SCHED_FIFO);
+	param.sched_priority = priority_max;
+	if (pthread_setschedparam(thread, SCHED_FIFO, &param) != 0) {
+		ast_log(LOG_ERROR, "pthread_setschedparam failed, %s\n", strerror(errno));
+	}
+	// Get the new schedule policy and priority
+	policy = SCHED_FIFO - 1;
+	param.sched_priority = priority_min - 1; // set as an invalid value intentionally
+	if (pthread_getschedparam(thread, &policy, &param) != 0) {
+		ast_log(LOG_ERROR, "pthread_getschedparam failed, %s\n", strerror(errno));
+	}
+	ast_verbose("thread entry is %s, tid=%d, new schedule policy=%d, priority=%d\n", __func__, tid, policy, param.sched_priority);
 
 	__ast_pbx_run(c, NULL);
 	decrease_call_count();
-- 
GitLab