1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
| import numpy as np from typing import List, Dict, Optional, Callable, Any from dataclasses import dataclass from enum import Enum import time import threading import queue import math
class MediaType(Enum): """媒体类型""" AUDIO = "audio" VIDEO = "video"
class CodecType(Enum): """编解码器类型""" OPUS = "opus" G722 = "G722" PCMU = "PCMU" PCMA = "PCMA" VP8 = "VP8" VP9 = "VP9" H264 = "H264" AV1 = "AV1"
@dataclass class MediaFrame: """媒体帧""" media_type: MediaType data: np.ndarray timestamp: float sequence_number: int codec: CodecType sample_rate: Optional[int] = None channels: Optional[int] = None width: Optional[int] = None height: Optional[int] = None frame_rate: Optional[float] = None
@dataclass class RTPPacket: """RTP数据包""" version: int = 2 padding: bool = False extension: bool = False csrc_count: int = 0 marker: bool = False payload_type: int = 0 sequence_number: int = 0 timestamp: int = 0 ssrc: int = 0 payload: bytes = b'' def encode(self) -> bytes: """编码RTP包""" header = bytearray(12) header[0] = (self.version << 6) | (int(self.padding) << 5) | \ (int(self.extension) << 4) | self.csrc_count header[1] = (int(self.marker) << 7) | self.payload_type header[2:4] = self.sequence_number.to_bytes(2, 'big') header[4:8] = self.timestamp.to_bytes(4, 'big') header[8:12] = self.ssrc.to_bytes(4, 'big') return bytes(header) + self.payload @classmethod def decode(cls, data: bytes) -> 'RTPPacket': """解码RTP包""" if len(data) < 12: raise ValueError("RTP packet too short") packet = cls() packet.version = (data[0] >> 6) & 0x03 packet.padding = bool((data[0] >> 5) & 0x01) packet.extension = bool((data[0] >> 4) & 0x01) packet.csrc_count = data[0] & 0x0F packet.marker = bool((data[1] >> 7) & 0x01) packet.payload_type = data[1] & 0x7F packet.sequence_number = int.from_bytes(data[2:4], 'big') packet.timestamp = int.from_bytes(data[4:8], 'big') packet.ssrc = int.from_bytes(data[8:12], 'big') header_length = 12 + packet.csrc_count * 4 packet.payload = data[header_length:] return packet
class AudioProcessor: """音频处理器""" def __init__(self, sample_rate: int = 48000, channels: int = 2, frame_size: int = 960): self.sample_rate = sample_rate self.channels = channels self.frame_size = frame_size self.sequence_number = 0 self.gain = 1.0 self.noise_gate_threshold = 0.01 self.enable_agc = True self.enable_aec = True self.enable_ns = True def generate_audio_frame(self, frequency: float = 440.0, duration: float = 0.02) -> MediaFrame: """生成音频帧(用于测试)""" samples = int(self.sample_rate * duration) t = np.linspace(0, duration, samples, False) audio_data = np.sin(2 * np.pi * frequency * t) * 0.3 if self.channels == 2: audio_data = np.column_stack([audio_data, audio_data]) frame = MediaFrame( media_type=MediaType.AUDIO, data=audio_data.astype(np.float32), timestamp=time.time(), sequence_number=self.sequence_number, codec=CodecType.OPUS, sample_rate=self.sample_rate, channels=self.channels ) self.sequence_number += 1 return frame def apply_audio_processing(self, frame: MediaFrame) -> MediaFrame: """应用音频处理""" processed_data = frame.data.copy() if np.max(np.abs(processed_data)) < self.noise_gate_threshold: processed_data *= 0.1 if self.enable_agc: processed_data = self.apply_agc(processed_data) if self.enable_ns: processed_data = self.apply_noise_suppression(processed_data) if self.enable_aec: processed_data = self.apply_echo_cancellation(processed_data) processed_data *= self.gain processed_data = np.clip(processed_data, -1.0, 1.0) frame.data = processed_data return frame def apply_agc(self, audio_data: np.ndarray) -> np.ndarray: """自动增益控制""" target_level = 0.3 current_level = np.sqrt(np.mean(audio_data ** 2)) if current_level > 0: gain_adjustment = target_level / current_level gain_adjustment = np.clip(gain_adjustment, 0.1, 3.0) return audio_data * gain_adjustment return audio_data def apply_noise_suppression(self, audio_data: np.ndarray) -> np.ndarray: """噪声抑制(简化版谱减法)""" if len(audio_data.shape) == 1: return self.high_pass_filter(audio_data) else: processed = np.zeros_like(audio_data) for ch in range(audio_data.shape[1]): processed[:, ch] = self.high_pass_filter(audio_data[:, ch]) return processed def high_pass_filter(self, signal: np.ndarray, cutoff: float = 80.0) -> np.ndarray: """简单的高通滤波器""" alpha = 1.0 / (1.0 + 2.0 * np.pi * cutoff / self.sample_rate) filtered = np.zeros_like(signal) filtered[0] = signal[0] for i in range(1, len(signal)): filtered[i] = alpha * (filtered[i-1] + signal[i] - signal[i-1]) return filtered def apply_echo_cancellation(self, audio_data: np.ndarray) -> np.ndarray: """回声消除(简化版)""" echo_delay = int(0.1 * self.sample_rate) echo_attenuation = 0.3 if len(audio_data) > echo_delay: audio_data[echo_delay:] -= echo_attenuation * audio_data[:-echo_delay] return audio_data def encode_opus(self, frame: MediaFrame) -> bytes: """OPUS编码(模拟)""" quantized = (frame.data * 32767).astype(np.int16) compressed_size = len(quantized.tobytes()) // 4 compressed_data = quantized.tobytes()[:compressed_size] return compressed_data def decode_opus(self, encoded_data: bytes, frame_info: Dict) -> MediaFrame: """OPUS解码(模拟)""" decompressed_size = len(encoded_data) * 4 padded_data = encoded_data + b'\x00' * (decompressed_size - len(encoded_data)) audio_samples = np.frombuffer(padded_data[:decompressed_size], dtype=np.int16) audio_data = audio_samples.astype(np.float32) / 32767.0 if self.channels > 1 and len(audio_data) % self.channels == 0: audio_data = audio_data.reshape(-1, self.channels) return MediaFrame( media_type=MediaType.AUDIO, data=audio_data, timestamp=frame_info.get('timestamp', time.time()), sequence_number=frame_info.get('sequence_number', 0), codec=CodecType.OPUS, sample_rate=self.sample_rate, channels=self.channels )
class VideoProcessor: """视频处理器""" def __init__(self, width: int = 640, height: int = 480, frame_rate: float = 30.0): self.width = width self.height = height self.frame_rate = frame_rate self.sequence_number = 0 self.enable_denoising = True self.enable_enhancement = True self.target_bitrate = 1000000 def generate_video_frame(self, pattern: str = "gradient") -> MediaFrame: """生成视频帧(用于测试)""" if pattern == "gradient": frame_data = np.zeros((self.height, self.width, 3), dtype=np.uint8) for y in range(self.height): for x in range(self.width): frame_data[y, x] = [ int(255 * x / self.width), int(255 * y / self.height), 128 ] elif pattern == "checkerboard": frame_data = np.zeros((self.height, self.width, 3), dtype=np.uint8) square_size = 32 for y in range(self.height): for x in range(self.width): if ((x // square_size) + (y // square_size)) % 2 == 0: frame_data[y, x] = [255, 255, 255] else: frame_data[y, x] = [0, 0, 0] else: frame_data = np.random.randint(0, 256, (self.height, self.width, 3), dtype=np.uint8) frame = MediaFrame( media_type=MediaType.VIDEO, data=frame_data, timestamp=time.time(), sequence_number=self.sequence_number, codec=CodecType.VP8, width=self.width, height=self.height, frame_rate=self.frame_rate ) self.sequence_number += 1 return frame def apply_video_processing(self, frame: MediaFrame) -> MediaFrame: """应用视频处理""" processed_data = frame.data.copy() if self.enable_denoising: processed_data = self.apply_denoising(processed_data) if self.enable_enhancement: processed_data = self.apply_enhancement(processed_data) frame.data = processed_data return frame def apply_denoising(self, image: np.ndarray) -> np.ndarray: """视频降噪(简化版高斯滤波)""" kernel_size = 3 sigma = 0.8 kernel = self.gaussian_kernel(kernel_size, sigma) filtered_image = np.zeros_like(image) pad = kernel_size // 2 for c in range(image.shape[2]): channel = image[:, :, c] padded = np.pad(channel, pad, mode='edge') for y in range(image.shape[0]): for x in range(image.shape[1]): region = padded[y:y+kernel_size, x:x+kernel_size] filtered_image[y, x, c] = np.sum(region * kernel) return filtered_image.astype(np.uint8) def gaussian_kernel(self, size: int, sigma: float) -> np.ndarray: """生成高斯核""" kernel = np.zeros((size, size)) center = size // 2 for y in range(size): for x in range(size): dx = x - center dy = y - center kernel[y, x] = np.exp(-(dx*dx + dy*dy) / (2 * sigma * sigma)) return kernel / np.sum(kernel) def apply_enhancement(self, image: np.ndarray) -> np.ndarray: """图像增强""" enhanced = image.astype(np.float32) enhanced = self.adjust_contrast(enhanced, 1.2) enhanced = self.adjust_brightness(enhanced, 10) return np.clip(enhanced, 0, 255).astype(np.uint8) def adjust_contrast(self, image: np.ndarray, factor: float) -> np.ndarray: """调整对比度""" mean = np.mean(image) return (image - mean) * factor + mean def adjust_brightness(self, image: np.ndarray, delta: float) -> np.ndarray: """调整亮度""" return image + delta def encode_vp8(self, frame: MediaFrame) -> bytes: """VP8编码(模拟)""" compressed_data = self.simple_video_compression(frame.data) return compressed_data def simple_video_compression(self, image: np.ndarray) -> bytes: """简单的视频压缩""" yuv = self.rgb_to_yuv(image) y = yuv[:, :, 0] u = yuv[::2, ::2, 1] v = yuv[::2, ::2, 2] y_quantized = (y / 4).astype(np.uint8) * 4 u_quantized = (u / 8).astype(np.uint8) * 8 v_quantized = (v / 8).astype(np.uint8) * 8 compressed = np.concatenate([ y_quantized.flatten(), u_quantized.flatten(), v_quantized.flatten() ]) return compressed.tobytes() def rgb_to_yuv(self, rgb: np.ndarray) -> np.ndarray: """RGB转YUV""" yuv = np.zeros_like(rgb, dtype=np.float32) yuv[:, :, 0] = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2] yuv[:, :, 1] = -0.169 * rgb[:, :, 0] - 0.331 * rgb[:, :, 1] + 0.5 * rgb[:, :, 2] + 128 yuv[:, :, 2] = 0.5 * rgb[:, :, 0] - 0.419 * rgb[:, :, 1] - 0.081 * rgb[:, :, 2] + 128 return np.clip(yuv, 0, 255).astype(np.uint8) def decode_vp8(self, encoded_data: bytes, frame_info: Dict) -> MediaFrame: """VP8解码(模拟)""" data_array = np.frombuffer(encoded_data, dtype=np.uint8) y_size = self.width * self.height u_size = (self.width // 2) * (self.height // 2) v_size = u_size if len(data_array) >= y_size + u_size + v_size: y = data_array[:y_size].reshape(self.height, self.width) u = data_array[y_size:y_size+u_size].reshape(self.height//2, self.width//2) v = data_array[y_size+u_size:y_size+u_size+v_size].reshape(self.height//2, self.width//2) u_upsampled = np.repeat(np.repeat(u, 2, axis=0), 2, axis=1) v_upsampled = np.repeat(np.repeat(v, 2, axis=0), 2, axis=1) yuv = np.stack([y, u_upsampled, v_upsampled], axis=2) rgb = self.yuv_to_rgb(yuv) else: rgb = np.zeros((self.height, self.width, 3), dtype=np.uint8) return MediaFrame( media_type=MediaType.VIDEO, data=rgb, timestamp=frame_info.get('timestamp', time.time()), sequence_number=frame_info.get('sequence_number', 0), codec=CodecType.VP8, width=self.width, height=self.height, frame_rate=self.frame_rate ) def yuv_to_rgb(self, yuv: np.ndarray) -> np.ndarray: """YUV转RGB""" rgb = np.zeros_like(yuv, dtype=np.float32) y = yuv[:, :, 0].astype(np.float32) u = yuv[:, :, 1].astype(np.float32) - 128 v = yuv[:, :, 2].astype(np.float32) - 128 rgb[:, :, 0] = y + 1.402 * v rgb[:, :, 1] = y - 0.344 * u - 0.714 * v rgb[:, :, 2] = y + 1.772 * u return np.clip(rgb, 0, 255).astype(np.uint8)
class RTPTransport: """RTP传输层""" def __init__(self, local_port: int = 5004, remote_host: str = "localhost", remote_port: int = 5006): self.local_port = local_port self.remote_host = remote_host self.remote_port = remote_port self.ssrc = random.randint(0, 0xFFFFFFFF) self.sequence_number = random.randint(0, 0xFFFF) self.timestamp_offset = random.randint(0, 0xFFFFFFFF) self.packets_sent = 0 self.packets_received = 0 self.bytes_sent = 0 self.bytes_received = 0 self.packet_loss_rate = 0.0 self.send_queue = queue.Queue() self.receive_queue = queue.Queue() self.running = False self.send_thread = None self.receive_thread = None def start(self): """启动RTP传输""" self.running = True self.send_thread = threading.Thread(target=self._send_loop) self.receive_thread = threading.Thread(target=self._receive_loop) self.send_thread.start() self.receive_thread.start() print(f"RTP transport started on port {self.local_port}") def stop(self): """停止RTP传输""" self.running = False if self.send_thread: self.send_thread.join() if self.receive_thread: self.receive_thread.join() print("RTP transport stopped") def send_media_frame(self, frame: MediaFrame, payload_type: int = 96): """发送媒体帧""" if frame.media_type == MediaType.AUDIO: payload = self._encode_audio_frame(frame) else: payload = self._encode_video_frame(frame) rtp_packet = RTPPacket( payload_type=payload_type, sequence_number=self.sequence_number, timestamp=int(frame.timestamp * 90000) + self.timestamp_offset, ssrc=self.ssrc, payload=payload ) self.send_queue.put(rtp_packet) self.sequence_number = (self.sequence_number + 1) % 0x10000 def _encode_audio_frame(self, frame: MediaFrame) -> bytes: """编码音频帧""" audio_data = (frame.data * 32767).astype(np.int16) return audio_data.tobytes() def _encode_video_frame(self, frame: MediaFrame) -> bytes: """编码视频帧""" return frame.data.tobytes() def _send_loop(self): """发送循环""" import socket try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while self.running: try: rtp_packet = self.send_queue.get(timeout=0.1) packet_data = rtp_packet.encode() sock.sendto(packet_data, (self.remote_host, self.remote_port)) self.packets_sent += 1 self.bytes_sent += len(packet_data) except queue.Empty: continue except Exception as e: print(f"Send error: {e}") except Exception as e: print(f"Send loop error: {e}") finally: if 'sock' in locals(): sock.close() def _receive_loop(self): """接收循环""" import socket try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', self.local_port)) sock.settimeout(0.1) while self.running: try: data, addr = sock.recvfrom(1500) rtp_packet = RTPPacket.decode(data) self.receive_queue.put(rtp_packet) self.packets_received += 1 self.bytes_received += len(data) except socket.timeout: continue except Exception as e: print(f"Receive error: {e}") except Exception as e: print(f"Receive loop error: {e}") finally: if 'sock' in locals(): sock.close() def get_received_frame(self) -> Optional[MediaFrame]: """获取接收到的媒体帧""" try: rtp_packet = self.receive_queue.get_nowait() frame = MediaFrame( media_type=MediaType.AUDIO, data=np.frombuffer(rtp_packet.payload, dtype=np.int16).astype(np.float32) / 32767.0, timestamp=rtp_packet.timestamp / 90000.0, sequence_number=rtp_packet.sequence_number, codec=CodecType.OPUS ) return frame except queue.Empty: return None def get_statistics(self) -> Dict[str, Any]: """获取传输统计""" return { 'packets_sent': self.packets_sent, 'packets_received': self.packets_received, 'bytes_sent': self.bytes_sent, 'bytes_received': self.bytes_received, 'packet_loss_rate': self.packet_loss_rate }
def demo_media_processing(): print("WebRTC Media Processing Demo") print("=============================") print("\n1. Audio Processing Demo") audio_processor = AudioProcessor() audio_frame = audio_processor.generate_audio_frame(frequency=440.0) print(f"Generated audio frame: {audio_frame.data.shape}, {audio_frame.sample_rate}Hz") processed_audio = audio_processor.apply_audio_processing(audio_frame) print(f"Processed audio frame: RMS = {np.sqrt(np.mean(processed_audio.data**2)):.4f}") encoded_audio = audio_processor.encode_opus(processed_audio) decoded_audio = audio_processor.decode_opus(encoded_audio, { 'timestamp': processed_audio.timestamp, 'sequence_number': processed_audio.sequence_number }) print(f"Audio codec: {len(encoded_audio)} bytes -> {decoded_audio.data.shape}") print("\n2. Video Processing Demo") video_processor = VideoProcessor() video_frame = video_processor.generate_video_frame("gradient") print(f"Generated video frame: {video_frame.data.shape}") processed_video = video_processor.apply_video_processing(video_frame) print(f"Processed video frame: mean brightness = {np.mean(processed_video.data):.2f}") encoded_video = video_processor.encode_vp8(processed_video) decoded_video = video_processor.decode_vp8(encoded_video, { 'timestamp': processed_video.timestamp, 'sequence_number': processed_video.sequence_number }) print(f"Video codec: {len(encoded_video)} bytes -> {decoded_video.data.shape}") print("\n3. RTP Transport Demo") rtp_transport = RTPTransport() rtp_transport.start() try: for i in range(5): frame = audio_processor.generate_audio_frame(frequency=440.0 + i * 100) rtp_transport.send_media_frame(frame) time.sleep(0.02) time.sleep(0.5) stats = rtp_transport.get_statistics() print(f"RTP Statistics: {stats}") finally: rtp_transport.stop()
if __name__ == "__main__": demo_media_processing()
|