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
| class PipelineBuilder: """管道构建器""" def __init__(self, name: str = "custom-pipeline"): self.gst_core = GStreamerCore() self.pipeline_name = name self.element_configs = [] self.link_configs = [] self.property_configs = [] self.caps_configs = [] self.pipeline_templates = { 'video_player': self._video_player_template, 'audio_player': self._audio_player_template, 'video_transcoder': self._video_transcoder_template, 'rtmp_streamer': self._rtmp_streamer_template, 'webcam_capture': self._webcam_capture_template, 'screen_recorder': self._screen_recorder_template } def add_element(self, factory_name: str, element_name: str, properties: Dict[str, Any] = None) -> 'PipelineBuilder': """添加元素配置""" self.element_configs.append({ 'factory_name': factory_name, 'element_name': element_name, 'properties': properties or {} }) return self def link(self, src_element: str, sink_element: str, src_pad: str = None, sink_pad: str = None, caps: str = None) -> 'PipelineBuilder': """添加连接配置""" self.link_configs.append({ 'src_element': src_element, 'sink_element': sink_element, 'src_pad': src_pad, 'sink_pad': sink_pad, 'caps': caps }) return self def set_property(self, element_name: str, property_name: str, value: Any) -> 'PipelineBuilder': """添加属性配置""" self.property_configs.append({ 'element_name': element_name, 'property_name': property_name, 'value': value }) return self def set_caps(self, element_name: str, caps: str) -> 'PipelineBuilder': """添加Caps配置""" self.caps_configs.append({ 'element_name': element_name, 'caps': caps }) return self def build(self) -> Optional[GStreamerCore]: """构建管道""" try: if not self.gst_core.create_pipeline(self.pipeline_name): return None print(f"Building pipeline '{self.pipeline_name}'...") for config in self.element_configs: element = self.gst_core.add_element( config['factory_name'], config['element_name'] ) if not element: print(f"Failed to add element: {config['element_name']}") return None for prop_name, prop_value in config['properties'].items(): self.gst_core.set_element_property( config['element_name'], prop_name, prop_value ) for config in self.property_configs: self.gst_core.set_element_property( config['element_name'], config['property_name'], config['value'] ) for config in self.caps_configs: element = self.gst_core.elements.get(config['element_name']) if element and 'caps' in [prop.name for prop in element.list_properties()]: caps = Gst.Caps.from_string(config['caps']) if caps: element.set_property('caps', caps) for config in self.link_configs: if config['caps']: capsfilter_name = f"capsfilter_{len(self.gst_core.elements)}" capsfilter = self.gst_core.add_element("capsfilter", capsfilter_name) if capsfilter: caps = Gst.Caps.from_string(config['caps']) capsfilter.set_property('caps', caps) if not (self.gst_core.link_elements(config['src_element'], capsfilter_name) and self.gst_core.link_elements(capsfilter_name, config['sink_element'])): print(f"Failed to link with caps: {config['src_element']} -> {config['sink_element']}") return None else: if not self.gst_core.link_elements( config['src_element'], config['sink_element'], config['src_pad'], config['sink_pad'] ): print(f"Failed to link: {config['src_element']} -> {config['sink_element']}") return None print(f"Pipeline '{self.pipeline_name}' built successfully") return self.gst_core except Exception as e: print(f"Error building pipeline: {e}") return None def from_template(self, template_name: str, **kwargs) -> 'PipelineBuilder': """从模板创建管道""" template_func = self.pipeline_templates.get(template_name) if template_func: return template_func(**kwargs) else: print(f"Template '{template_name}' not found") return self def _video_player_template(self, input_file: str, **kwargs) -> 'PipelineBuilder': """视频播放器模板""" return (self .add_element("filesrc", "file-source", {'location': input_file}) .add_element("decodebin", "decoder") .add_element("videoconvert", "video-convert") .add_element("videoscale", "video-scale") .add_element("autovideosink", "video-sink") .add_element("audioconvert", "audio-convert") .add_element("audioresample", "audio-resample") .add_element("autoaudiosink", "audio-sink")) def _audio_player_template(self, input_file: str, **kwargs) -> 'PipelineBuilder': """音频播放器模板""" return (self .add_element("filesrc", "file-source", {'location': input_file}) .add_element("decodebin", "decoder") .add_element("audioconvert", "audio-convert") .add_element("audioresample", "audio-resample") .add_element("autoaudiosink", "audio-sink")) def _video_transcoder_template(self, input_file: str, output_file: str, video_codec: str = 'h264', audio_codec: str = 'aac', **kwargs) -> 'PipelineBuilder': """视频转码器模板""" video_encoders = { 'h264': 'x264enc', 'h265': 'x265enc', 'vp8': 'vp8enc', 'vp9': 'vp9enc' } audio_encoders = { 'aac': 'faac', 'mp3': 'lamemp3enc', 'vorbis': 'vorbisenc', 'opus': 'opusenc' } output_ext = output_file.split('.')[-1].lower() muxers = { 'mp4': 'mp4mux', 'mkv': 'matroskamux', 'webm': 'webmmux', 'avi': 'avimux' } video_enc = video_encoders.get(video_codec, 'x264enc') audio_enc = audio_encoders.get(audio_codec, 'faac') muxer = muxers.get(output_ext, 'mp4mux') return (self .add_element("filesrc", "file-source", {'location': input_file}) .add_element("decodebin", "decoder") .add_element("videoconvert", "video-convert") .add_element("videoscale", "video-scale") .add_element(video_enc, "video-encoder") .add_element("audioconvert", "audio-convert") .add_element("audioresample", "audio-resample") .add_element(audio_enc, "audio-encoder") .add_element(muxer, "muxer") .add_element("filesink", "file-sink", {'location': output_file})) def _rtmp_streamer_template(self, rtmp_url: str, video_device: str = '/dev/video0', **kwargs) -> 'PipelineBuilder': """RTMP推流模板""" return (self .add_element("v4l2src", "video-source", {'device': video_device}) .add_element("videoconvert", "video-convert") .add_element("videoscale", "video-scale") .add_element("x264enc", "video-encoder", { 'bitrate': kwargs.get('video_bitrate', 2000), 'tune': 'zerolatency' }) .add_element("alsasrc", "audio-source") .add_element("audioconvert", "audio-convert") .add_element("audioresample", "audio-resample") .add_element("faac", "audio-encoder", { 'bitrate': kwargs.get('audio_bitrate', 128000) }) .add_element("flvmux", "muxer") .add_element("rtmpsink", "rtmp-sink", {'location': rtmp_url})) def _webcam_capture_template(self, output_file: str, video_device: str = '/dev/video0', **kwargs) -> 'PipelineBuilder': """摄像头录制模板""" width = kwargs.get('width', 1280) height = kwargs.get('height', 720) framerate = kwargs.get('framerate', 30) video_caps = f"video/x-raw,width={width},height={height},framerate={framerate}/1" return (self .add_element("v4l2src", "video-source", {'device': video_device}) .add_element("videoconvert", "video-convert") .add_element("videoscale", "video-scale") .add_element("x264enc", "video-encoder") .add_element("mp4mux", "muxer") .add_element("filesink", "file-sink", {'location': output_file}) .set_caps("video-source", video_caps)) def _screen_recorder_template(self, output_file: str, **kwargs) -> 'PipelineBuilder': """屏幕录制模板""" x = kwargs.get('x', 0) y = kwargs.get('y', 0) width = kwargs.get('width', 1920) height = kwargs.get('height', 1080) return (self .add_element("ximagesrc", "screen-source", { 'startx': x, 'starty': y, 'endx': x + width, 'endy': y + height }) .add_element("videoconvert", "video-convert") .add_element("videorate", "video-rate") .add_element("x264enc", "video-encoder") .add_element("mp4mux", "muxer") .add_element("filesink", "file-sink", {'location': output_file})) def get_available_templates(self) -> List[str]: """获取可用模板列表""" return list(self.pipeline_templates.keys()) def describe_template(self, template_name: str) -> str: """描述模板功能""" descriptions = { 'video_player': 'Play video files with automatic format detection', 'audio_player': 'Play audio files with automatic format detection', 'video_transcoder': 'Transcode video files between different formats', 'rtmp_streamer': 'Stream video from webcam to RTMP server', 'webcam_capture': 'Capture video from webcam to file', 'screen_recorder': 'Record screen content to video file' } return descriptions.get(template_name, 'No description available')
def demo_pipeline_builder(): print("Pipeline Builder Demo") print("=====================") print("\n1. Available Pipeline Templates") builder = PipelineBuilder() templates = builder.get_available_templates() for template in templates: description = builder.describe_template(template) print(f" {template}: {description}") print("\n2. Building Video Test Player") player_builder = (PipelineBuilder("test-video-player") .add_element("videotestsrc", "video-source", { 'pattern': 0, 'num-buffers': 300 }) .add_element("videoconvert", "video-convert") .add_element("videoscale", "video-scale") .add_element("autovideosink", "video-sink") .link("video-source", "video-convert") .link("video-convert", "video-scale") .link("video-scale", "video-sink")) player_core = player_builder.build() if player_core: print("Test video player built successfully") pipeline_info = player_core.get_pipeline_info() print(f"Pipeline info: {pipeline_info['elements_count']} elements") print(f"Elements: {', '.join(pipeline_info['elements'])}") if player_core.start_pipeline(): print("Playing test video for 3 seconds...") time.sleep(3) player_core.cleanup() print("\n3. Building Custom Transcoding Pipeline") transcoder_builder = (PipelineBuilder("audio-transcoder") .add_element("audiotestsrc", "audio-source", { 'num-buffers': 1000, 'freq': 440 }) .add_element("audioconvert", "audio-convert") .add_element("audioresample", "audio-resample") .add_element("lamemp3enc", "mp3-encoder", { 'bitrate': 128 }) .add_element("filesink", "file-sink", { 'location': 'test_output.mp3' }) .link("audio-source", "audio-convert") .link("audio-convert", "audio-resample") .link("audio-resample", "mp3-encoder") .link("mp3-encoder", "file-sink")) transcoder_core = transcoder_builder.build() if transcoder_core: print("Audio transcoder built successfully") pipeline_info = transcoder_core.get_pipeline_info() print(f"Pipeline: {' -> '.join(pipeline_info['elements'])}") transcoder_core.cleanup() print("\n4. Building Pipeline with Caps Constraints") caps_builder = (PipelineBuilder("caps-constrained-pipeline") .add_element("videotestsrc", "video-source") .add_element("capsfilter", "caps-filter") .add_element("videoconvert", "video-convert") .add_element("fakesink", "fake-sink") .set_caps("caps-filter", "video/x-raw,width=320,height=240,framerate=15/1") .link("video-source", "caps-filter") .link("caps-filter", "video-convert") .link("video-convert", "fake-sink")) caps_core = caps_builder.build() if caps_core: print("Caps-constrained pipeline built successfully") caps_core.cleanup() print("\nPipeline Builder demo completed")
if __name__ == "__main__": demo_pipeline_builder()
|