Мультипроцесс

This commit is contained in:
zakhy 2025-04-22 16:24:11 +07:00
parent 45136d5566
commit 4f1cda50dc

View File

@ -6,7 +6,9 @@ import socket
import struct
import subprocess
import sys
import time
import traceback
from multiprocessing import Process
import django
import websockets
@ -26,19 +28,23 @@ def log(msg):
def get_call_initialize_command():
return [{
"identifier": "call:1/initialization_request",
"payload": {
"voip_port": str(API_PORT),
"supported_codecs": [{
"codec_id": RTP_PAYLOAD_TYPE,
"name": "G711A",
"packet_duration": PACKET_DURATION_MS,
"sampling_rate": 8000
}],
"is_supported_webrtc": False
return [
{
"identifier": "call:1/initialization_request",
"payload": {
"voip_port": str(API_PORT),
"supported_codecs": [
{
"codec_id": RTP_PAYLOAD_TYPE,
"name": "G711A",
"packet_duration": PACKET_DURATION_MS,
"sampling_rate": 8000,
}
],
"is_supported_webrtc": False,
},
}
}]
]
def get_location_initialize_command():
@ -46,23 +52,24 @@ def get_location_initialize_command():
def get_transmit_command(promise_id, ssrc, target, source):
return [{
"identifier": "call:1/transmit_request",
"payload": {
"promise_id": promise_id,
"source": source,
"target": target,
"modifier": "not",
"voip_ssrc": ssrc
return [
{
"identifier": "call:1/transmit_request",
"payload": {
"promise_id": promise_id,
"source": source,
"target": target,
"modifier": "not",
"voip_ssrc": ssrc,
},
}
}]
]
def get_promise_cancel_command(promise_id):
return [{
"identifier": "core/promise_cancel",
"payload": {"promise_id": promise_id}
}]
return [
{"identifier": "core/promise_cancel", "payload": {"promise_id": promise_id}}
]
async def send_messages(websocket, message):
@ -74,8 +81,59 @@ async def send_messages(websocket, message):
await websocket.close()
async def handle_channel_transmission(channel, voice_call, websocket, auth_dict, promise_id_start):
ssrc = SSRC
def convert_audio_to_g711a(input_file):
output_file = "converted_audio.g711a"
command = [
"ffmpeg",
"-y",
"-i",
input_file,
"-ar",
"8000",
"-ac",
"1",
"-f",
"alaw",
output_file,
]
subprocess.run(command, check=True)
with open(output_file, "rb") as f:
audio_data = f.read()
os.remove(output_file)
return audio_data
def start_audio_stream_sync(audio_path, dest_ip, dest_port, ssrc):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sequence_number = 0
timestamp = 0
packet_size = 160
timestamp_increment = packet_size
audio_data = convert_audio_to_g711a(audio_path)
duration_sec = len(audio_data) / 8000
print(
f"[AUDIO-PROC] Подготовлено {len(audio_data)} байт (~{duration_sec:.2f} сек). Отправка началась..."
)
for i in range(0, len(audio_data), packet_size):
frame_data = audio_data[i : i + packet_size]
if not frame_data:
break
rtp_header = struct.pack(
"!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc
)
rtp_packet = rtp_header + frame_data
sock.sendto(rtp_packet, (dest_ip, dest_port))
sequence_number = (sequence_number + 1) % 65536
timestamp = (timestamp + timestamp_increment) % (2**32)
time.sleep(PACKET_DURATION_MS / 1000) # native sleep here
sock.close()
print(f"[AUDIO-PROC] Отправка завершена.")
async def handle_channel_transmission(channel, voice_call, websocket, auth_dict, promise_id_start, channel_id):
ssrc = SSRC + channel_id # Например, добавим `uid` канала для уникальности
source_id = auth_dict["client_id"]
retry_attempts = 0
promise_id = promise_id_start
@ -86,7 +144,6 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
promise_granted = False
own_tx_received = False
retry_due_to_timeout = False
try:
while True:
@ -96,6 +153,7 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
for item in message_items:
identifier = item.get("identifier")
payload = item.get("payload")
if identifier != "location:0/position_broadcast":
log(f"<<< Ответ получен: {item}")
@ -104,8 +162,6 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
if state == "granted":
promise_granted = True
log(f"[{channel}] Promise granted.")
elif state == "queued":
log(f"[{channel}] Promise queued...")
elif state == "faulted":
log(f"[{channel}] Promise faulted. Ретрай...")
break
@ -115,19 +171,29 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
own_tx_received = True
if promise_granted and own_tx_received:
log(f"[{channel}] Условия выполнены. Стартуем трансляцию")
await start_audio_stream(
voice_call.alarm_file.audio_file.path,
auth_dict["radiusip_host_ws"],
API_PORT,
ssrc
log(f"[{channel}] Условия выполнены. Стартуем трансляцию в отдельном процессе")
# Подсчёт длительности
audio_path = voice_call.alarm_file.audio_file.path
audio_data = convert_audio_to_g711a(audio_path)
duration_sec = len(audio_data) / 8000
# Запуск в отдельном процессе
proc = Process(
target=start_audio_stream_sync,
args=(audio_path, auth_dict["radiusip_host_ws"], API_PORT, ssrc)
)
proc.start()
# Ждём завершения
await asyncio.sleep(duration_sec + 1)
# Завершаем promise
await send_messages(websocket, get_promise_cancel_command(promise_id))
return True
except asyncio.TimeoutError:
log(f"[{channel}] Timeout ожидания. Ретрай...")
retry_due_to_timeout = True
retry_attempts += 1
promise_id += 1
@ -158,11 +224,7 @@ async def receive_messages(websocket, auth_dict):
for ch in voice_call.channels.all():
channel = ch.uid
success = await handle_channel_transmission(
channel,
voice_call,
websocket,
auth_dict,
promise_id
channel, voice_call, websocket, auth_dict, promise_id, ch.id
)
promise_id += 1
await set_voice_call_sent(voice_call)
@ -177,7 +239,9 @@ async def receive_messages(websocket, auth_dict):
call_mapi_initialized = True
ssrc = item["payload"].get("voip_ssrc", SSRC)
elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"):
elif identifier == "location:0/position_broadcast" and auth_dict.get(
"wlocationsystem"
):
await save_location(item["payload"])
except Exception:
@ -186,7 +250,11 @@ async def receive_messages(websocket, auth_dict):
@sync_to_async
def get_voice_calls():
return VoiceCall.objects.filter(sent=False).prefetch_related("alarm_file", "channels").first()
return (
VoiceCall.objects.filter(sent=False)
.prefetch_related("alarm_file", "channels")
.first()
)
@sync_to_async
@ -216,7 +284,17 @@ def create_or_update_location(data):
def convert_audio_to_g711a(input_file):
output_file = "converted_audio.g711a"
command = [
"ffmpeg", "-y", "-i", input_file, "-ar", "8000", "-ac", "1", "-f", "alaw", output_file
"ffmpeg",
"-y",
"-i",
input_file,
"-ar",
"8000",
"-ac",
"1",
"-f",
"alaw",
output_file,
]
subprocess.run(command, check=True)
with open(output_file, "rb") as f:
@ -234,15 +312,19 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
audio_data = convert_audio_to_g711a(audio_path)
duration_sec = len(audio_data) / 8000
log(f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки.")
log(
f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки."
)
log("Начинаем отправку аудио по RTP...")
for i in range(0, len(audio_data), packet_size):
frame_data = audio_data[i:i+packet_size]
frame_data = audio_data[i : i + packet_size]
if not frame_data:
break
rtp_header = struct.pack("!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc)
rtp_header = struct.pack(
"!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc
)
rtp_packet = rtp_header + frame_data
sock.sendto(rtp_packet, (dest_ip, dest_port))
sequence_number = (sequence_number + 1) % 65536
@ -268,7 +350,9 @@ def get_settings_from_db():
"radiusip_api_key": get_settings(prefix + "token", ""),
"radiusip_login": get_settings(prefix + "login", ""),
"radiusip_password": get_settings(prefix + "pass", ""),
"raduisip_group": get_settings(prefix + "group", "dmr:1@groups.17826016.global"),
"raduisip_group": get_settings(
prefix + "group", "dmr:1@groups.17826016.global"
),
"wlocationsystem": wlocationsystem == "Radiusip",
"plasystem": plasystem == "Radiusip",
}
@ -277,19 +361,23 @@ def get_settings_from_db():
async def main():
auth_dict = await get_settings_from_db()
uri = f"ws://{auth_dict['radiusip_host_ws']}:{auth_dict['radiusip_port_ws']}/"
connection_request = [{
"identifier": "core/connection_request",
"payload": {
"login": auth_dict["radiusip_login"],
"password": auth_dict["radiusip_password"],
"api_key": auth_dict["radiusip_api_key"],
"token": None
connection_request = [
{
"identifier": "core/connection_request",
"payload": {
"login": auth_dict["radiusip_login"],
"password": auth_dict["radiusip_password"],
"api_key": auth_dict["radiusip_api_key"],
"token": None,
},
}
}]
]
while True:
try:
async with websockets.connect(uri, ping_interval=20, ping_timeout=10) as websocket:
async with websockets.connect(
uri, ping_interval=20, ping_timeout=10
) as websocket:
await send_messages(websocket, connection_request)
await receive_messages(websocket, auth_dict)
except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError):
@ -301,7 +389,7 @@ async def main():
if __name__ == "__main__":
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
sys.path.append(project_root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mfssogr.settings")