├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── readme.md ├── session ├── Cargo.toml ├── assets │ └── mysql_init.sql ├── config.yml ├── src │ ├── app.rs │ ├── gb │ │ ├── handler │ │ │ ├── builder.rs │ │ │ ├── cmd.rs │ │ │ ├── events.rs │ │ │ ├── mod.rs │ │ │ ├── parser.rs │ │ │ └── requester.rs │ │ ├── io.rs │ │ ├── mod.rs │ │ └── shared.rs │ ├── general │ │ ├── cache.rs │ │ ├── http.rs │ │ ├── mod.rs │ │ ├── model.rs │ │ ├── runner.rs │ │ └── schedule.rs │ ├── main.rs │ ├── service │ │ ├── biz.rs │ │ ├── callback.rs │ │ ├── handler.rs │ │ └── mod.rs │ ├── storage │ │ ├── entity.rs │ │ ├── mapper.rs │ │ ├── mod.rs │ │ └── pics.rs │ ├── utils │ │ ├── id_builder.rs │ │ ├── mod.rs │ │ └── se_token.rs │ └── web │ │ ├── api.rs │ │ ├── hook.rs │ │ ├── mod.rs │ │ └── se.rs └── tests │ └── test.rs ├── sources ├── c_d_list.png ├── c_list.png ├── c_play.png ├── d_add.png ├── d_list.png ├── down.png ├── playback.png └── swagger.png └── stream ├── Cargo.toml ├── config.yml ├── readme └── src ├── app.rs ├── biz ├── api.rs ├── call.rs └── mod.rs ├── coder ├── h264.rs └── mod.rs ├── comm ├── mod.rs └── valid.rs ├── container ├── flv.rs ├── hls.rs ├── mod.rs ├── mp4.rs ├── ps.rs └── rtp.rs ├── general ├── cfg.rs ├── mod.rs ├── mode.rs └── util.rs ├── io ├── hook_handler.rs ├── http_handler.rs ├── mod.rs ├── rtcp_handler.rs └── rtp_handler.rs ├── main.rs ├── state ├── cache.rs └── mod.rs └── trans ├── demuxer.rs ├── flv_muxer.rs ├── hls_muxer.rs └── mod.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/target 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = ["session", "stream"] 4 | 5 | [profile.dev] 6 | debug = true 7 | opt-level = 0 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 KANG ZE 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # 这是一个基于GB28181的视频监控实现:兼容2016、2022版本。采用纯RUST语言编码,高效、安全、无惧并发;设备与用户端到端打通、闭环信令服务、流媒体服务。 2 | 3 | 4 | ## 🌟 TCP/UDP端口复用、单机/集群部署、SWAGGER接口文档、不做破坏性更新【接口稳定】、开箱即用【无需编译链接各种依赖】 5 | 6 | ### 🔗 1. 前端场景界面 demo(VUE 项目):[simple-app](https://github.com/epimore/simple-app) 7 | ### 🔗 2. 自定义业务场景 demo(JAVA 项目):[simple-biz](https://github.com/epimore/simple-biz) 8 | 9 | ### ✨✨✨ 在线测试地址:[epimore.cn](https://epimore.cn) 10 | 11 | ## GMV:SESSION 信令服务已实现: 12 | 1. 设备注册、注销、心跳、状态(在线/离线) 13 | 2. 设备(子设备)信息、点播/历史回播/视频下载 14 | 3. 自动管理流:流注册超时、无人观看、响应超时等自动关闭流 15 | 4. 根据cron表达式配置自动采集抓拍实时图像 16 | 5. 解析设备告警及推送 17 | 6. ... 18 | 19 | ## GMV:STREAM 流媒体服务已实现 20 | ```text 21 | RTP -> PS -> H264 -> HTTP-FLV(直/点播)、MP4(录像) 22 | -> H264 -> HTTP-FLV(直/点播)、MP4(录像) 23 | ... 24 | ``` 25 | 26 | ### v1版本:完成。 27 | 1. 实时播放 - 完成 28 | 2. 历史回放 - 完成 29 | 1. 倍数播放 - 完成 30 | 2. 拖动播放 - 完成 31 | 3. 云台控制 - 完成 32 | 1. 转向 - 完成 33 | 2. 焦距调整 - 完成 34 | 4. 告警推送 - 完成 35 | 5. 定时抓拍 - 完成 36 | 6. 图片上传 - 完成 37 | 7. 视频离线下载 - 完成 38 | 39 | ## TODO: 40 | ### v2版本:预计25年年中启动 41 | // 流媒体服务使用ffmpeg实现,以扩展支持协议减少轮子。 42 | 1. 级联 -- SESSION 43 | 2. 支持H265,HLS... -- STREAM 44 | 3. 统一响应码 45 | ### V3版本:预计25年底启动 46 | 1. 按需推流 47 | 2. 图片AI识别-插件化业务场景 48 | 3. 多数据库配置 49 | 50 | ![0](./sources/swagger.png "API文档") 51 | ![1](./sources/d_list.png "设备目录") 52 | ![2](./sources/d_add.png "设备添加") 53 | ![3](./sources/c_list.png "设备目录通道") 54 | ![4](./sources/c_d_list.png "通道目录操作") 55 | ![5](./sources/c_play.png "通道点播") 56 | ![6](./sources/playback.png "历史回放") 57 | ![7](./sources/down.png "云端下载") 58 | 59 | ## 微信交流添加:epimore;备注GMV -------------------------------------------------------------------------------- /session/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "gmv-session" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | rsip = "0.4" 10 | sqlx = { version = "0.8",default-features = false} 11 | common = { package = "common_db",git = "https://github.com/epimore/pigs.git",rev = "8b9fb07c", features = ["net"] } 12 | #common = { package = "common_db", path = "../../pigs/common_db", features = ["net"] } 13 | uuid = { version = "1.7.0", features = ["v4"] } 14 | quick-xml = { version = "0.31", features = ["encoding_rs", "encoding"] } 15 | encoding_rs = "0.8" 16 | poem = { version = "3.1", features = ["rustls"] } 17 | poem-openapi = { version = "5.1", features = ["swagger-ui"] } 18 | reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } 19 | sdp-types = "0.1" 20 | regex = "1.10" 21 | image = "0.25" 22 | rayon = "1.10" 23 | crossbeam-channel = "0.5" 24 | parking_lot = "0.12" 25 | url = "2.5" 26 | cron = "0.15" -------------------------------------------------------------------------------- /session/assets/mysql_init.sql: -------------------------------------------------------------------------------- 1 | SET NAMES utf8mb4; 2 | SET FOREIGN_KEY_CHECKS = 0; 3 | 4 | -- ---------------------------- 5 | -- Table structure for C_AREA_CODE 6 | -- ---------------------------- 7 | DROP TABLE IF EXISTS `C_AREA_CODE`; 8 | CREATE TABLE `C_AREA_CODE` ( 9 | `code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '行政区划代码', 10 | `name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划', 11 | `name_full` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划-全称', 12 | `province_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划代码-省', 13 | `province_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划-省', 14 | `city_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划代码-市', 15 | `city_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划-市', 16 | `district_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划代码-区/县', 17 | `district_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划-区/县', 18 | `street_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划代码-乡镇/街道', 19 | `street_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '行政区划-乡镇/街道', 20 | `level` int NULL DEFAULT NULL COMMENT '行政区划级别', 21 | PRIMARY KEY (`code`) USING BTREE, 22 | INDEX `index_code`(`code` ASC) USING BTREE, 23 | INDEX `index_name`(`name` ASC) USING BTREE 24 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; 25 | 26 | -- ---------------------------- 27 | -- Table structure for GMV_DEVICE 28 | -- ---------------------------- 29 | DROP TABLE IF EXISTS `GMV_DEVICE`; 30 | CREATE TABLE `GMV_DEVICE` ( 31 | `DEVICE_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '设备主键ID', 32 | `TRANSPORT` varchar(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '网络协议:TCP/UDP', 33 | `REGISTER_EXPIRES` int UNSIGNED NULL DEFAULT NULL COMMENT '注册有效期', 34 | `REGISTER_TIME` datetime NULL DEFAULT NULL COMMENT '最近注册时间', 35 | `LOCAL_ADDR` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备本地地址', 36 | `SIP_FROM` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '请求发送者', 37 | `SIP_TO` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '请求接收者', 38 | `DEVICE_TYPE` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备类型IPC/NVR/DVR...', 39 | `MANUFACTURER` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '厂家名称', 40 | `MODEL` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备型号', 41 | `FIRMWARE` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '固件版本', 42 | `MAX_CAMERA` smallint UNSIGNED NULL DEFAULT NULL COMMENT '最大相机数', 43 | `STATUS` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '0-离线,1-在线', 44 | `GB_VERSION` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT '2.0' COMMENT '国标版本', 45 | `LAST_UPDATE_TIME` datetime NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间', 46 | `tenant_id` int NULL DEFAULT NULL COMMENT '租户ID', 47 | `org_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '机构编码', 48 | PRIMARY KEY (`DEVICE_ID`) USING BTREE 49 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '设备主表' ROW_FORMAT = Dynamic; 50 | 51 | -- ---------------------------- 52 | -- Table structure for GMV_DEVICE_CHANNEL 53 | -- ---------------------------- 54 | DROP TABLE IF EXISTS `GMV_DEVICE_CHANNEL`; 55 | CREATE TABLE `GMV_DEVICE_CHANNEL` ( 56 | `DEVICE_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '设备ID', 57 | `CHANNEL_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '通道ID', 58 | `NAME` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备名称', 59 | `MANUFACTURER` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备厂商', 60 | `MODEL` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备型号', 61 | `OWNER` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备归属', 62 | `STATUS` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT 'ON' COMMENT '设备状态ON默认/OFF/STATUS1/ONLINE/OFFLINE....', 63 | `CIVIL_CODE` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '行政区域', 64 | `ADDRESS` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '安装地址', 65 | `PARENTAL` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '是否有子设备 1 有, 0 没有', 66 | `BLOCK` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '警区', 67 | `PARENT_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '父设备/区域/系统 ID', 68 | `IP_ADDRESS` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备/区域/系统 IP 地址', 69 | `PORT` int NULL DEFAULT NULL COMMENT '设备/区域/系统端口', 70 | `PASSWORD` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备口令', 71 | `LONGITUDE` decimal(12, 6) NULL DEFAULT NULL COMMENT '经度', 72 | `LATITUDE` decimal(12, 6) NULL DEFAULT NULL COMMENT '纬度', 73 | `PTZ_TYPE` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '摄像机类型扩展,标识摄像机类型: 1-球机; 2-半球; 3-固定枪机;4-遥控枪机,5遥控半球,6多目设备拼接通道,7多目设备分割通道。', 74 | `SUPPLY_LIGHT_TYPE` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '摄像机补光属性。 1-无补光、 2-红外补光、 3-白光补光。', 75 | `ALIAS_NAME` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '设备别名', 76 | `SNAPSHOT` int NULL DEFAULT 1 COMMENT '是否启用拍照:0-否,1-是;默认1', 77 | `over_pic_id` bigint NULL DEFAULT NULL COMMENT '封面图片ID', 78 | PRIMARY KEY (`DEVICE_ID`, `CHANNEL_ID`) USING BTREE 79 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '摄像机通道信息' ROW_FORMAT = Dynamic; 80 | 81 | -- ---------------------------- 82 | -- Table structure for GMV_DEVICE_SEQ 83 | -- ---------------------------- 84 | DROP TABLE IF EXISTS `GMV_DEVICE_SEQ`; 85 | CREATE TABLE `GMV_DEVICE_SEQ` ( 86 | `DOMIN` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SIP设备域', 87 | `SEQ_NO` int NULL DEFAULT NULL COMMENT '序号', 88 | `INFO` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, 89 | PRIMARY KEY (`DOMIN`) USING BTREE 90 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; 91 | 92 | -- ---------------------------- 93 | -- Table structure for GMV_FILE_INFO 94 | -- ---------------------------- 95 | DROP TABLE IF EXISTS `GMV_FILE_INFO`; 96 | CREATE TABLE `GMV_FILE_INFO` ( 97 | `ID` bigint NOT NULL AUTO_INCREMENT, 98 | `DEVICE_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '设备ID', 99 | `CHANNEL_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '通道ID', 100 | `BIZ_TIME` datetime NULL DEFAULT NULL COMMENT '生成时间', 101 | `BIZ_ID` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '业务ID', 102 | `FILE_TYPE` int NULL DEFAULT NULL COMMENT '文件类型:0-图片,1-视频,2-音频,3-视音频,4-其他', 103 | `FILE_SIZE` bigint UNSIGNED NULL DEFAULT NULL COMMENT '文件大小BYTE', 104 | `FILE_NAME` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文件名称', 105 | `FILE_FORMAT` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '文件格式', 106 | `DIR_PATH` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '(相对)存储路径', 107 | `ABS_PATH` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '绝对路径', 108 | `NOTE` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '注释', 109 | `IS_DEL` int NULL DEFAULT 0 COMMENT '是否删除;1-是,0-否;默认0', 110 | `CREATE_TIME` datetime NULL DEFAULT NULL COMMENT '创建时间', 111 | PRIMARY KEY (`ID`) USING BTREE, 112 | INDEX `dc_index`(`DEVICE_ID` ASC, `CHANNEL_ID` ASC) USING BTREE, 113 | INDEX `idx_device_channel_id`(`DEVICE_ID` ASC, `CHANNEL_ID` ASC, `ID` DESC) USING BTREE 114 | ) ENGINE = InnoDB AUTO_INCREMENT = 66 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '文件信息' ROW_FORMAT = Dynamic; 115 | 116 | -- ---------------------------- 117 | -- Table structure for GMV_OAUTH 118 | -- ---------------------------- 119 | DROP TABLE IF EXISTS `GMV_OAUTH`; 120 | CREATE TABLE `GMV_OAUTH` ( 121 | `DEVICE_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '中心8行业2类型3网络1序号6', 122 | `DOMAIN_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '34020000002000000001' COMMENT '设备域ID', 123 | `DOMAIN` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '设备域', 124 | `PWD` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '密码', 125 | `PWD_CHECK` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '0-不校验,1-检查', 126 | `ALIAS` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '别名', 127 | `STATUS` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '0-启用,1-禁用', 128 | `HEARTBEAT_SEC` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '心跳间隔:秒', 129 | `CREATE_TIME` datetime NULL DEFAULT NULL COMMENT '创建时间', 130 | `DEL` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '0-未删除,1-已删除', 131 | `tenant_id` int NULL DEFAULT NULL COMMENT '租户ID', 132 | `org_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '机构编码', 133 | PRIMARY KEY (`DEVICE_ID`) USING BTREE, 134 | UNIQUE INDEX `DEVICE_ID`(`DEVICE_ID` ASC) USING BTREE 135 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '认证表' ROW_FORMAT = Dynamic; 136 | 137 | -- ---------------------------- 138 | -- Table structure for GMV_RECORD 139 | -- ---------------------------- 140 | DROP TABLE IF EXISTS `GMV_RECORD`; 141 | CREATE TABLE `GMV_RECORD` ( 142 | `BIZ_ID` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '业务ID', 143 | `DEVICE_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '设备编号', 144 | `CHANNEL_ID` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '通道编号', 145 | `USER_ID` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户ID', 146 | `ST` datetime NULL DEFAULT NULL COMMENT '录像开始时间', 147 | `ET` datetime NULL DEFAULT NULL COMMENT '录像结束时间', 148 | `SPEED` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '倍速', 149 | `CT` datetime NULL DEFAULT NULL COMMENT '创建时间', 150 | `STATE` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '录制状态:0=进行,1=完成,2=录制部分,3=失败', 151 | `LT` datetime NULL DEFAULT NULL COMMENT '最后更新时间', 152 | `STREAM_APP_NAME` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '流媒体名称', 153 | PRIMARY KEY (`BIZ_ID`) USING BTREE 154 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '云端录像' ROW_FORMAT = Dynamic; 155 | 156 | SET FOREIGN_KEY_CHECKS = 1; -------------------------------------------------------------------------------- /session/config.yml: -------------------------------------------------------------------------------- 1 | log: 2 | level: info 3 | prefix: session 4 | store_path: ./logs 5 | specify: 6 | - crate_name: poem::server 7 | level: debug 8 | file_name_prefix: poem #日志文件前缀 9 | additivity: false #是否记录到默认日志文件中 10 | - crate_name: sqlx #sqlx用指全部,可sqlx::xxx 11 | level: info #日志等级 12 | file_name_prefix: sql #日志文件前缀 13 | additivity: false #是否记录到其默认日志文件中 14 | - crate_name: gmv_session::gb::io$ #信令日志 15 | level: debug #日志等级 16 | file_name_prefix: gb #日志文件前缀 17 | additivity: false #是否记录到其默认日志文件中 18 | - crate_name: gmv_session::web #请求日志 19 | level: info #日志等级 20 | file_name_prefix: web #日志文件前缀 21 | additivity: false #是否记录到其默认日志文件中 22 | 23 | 24 | http: 25 | port: 18567 26 | timeout: 30000 #请求超时 单位秒 27 | prefix: /session 28 | server_name: GMV:SESSION 29 | version: v0.2 30 | 31 | db: 32 | mysql: 33 | host_or_ip: 101.33.200.169 34 | port: 33061 35 | db_name: gmv 36 | user: epimore 37 | pass: clRXVjIzU1VrS3BEMXZmNxp5adMgQy599aQeu0tHYg0= #密码的密文 38 | attrs: 39 | log_global_sql_level: debug #记录全局sql,默认debug,此处将被log.level过滤 40 | log_slow_sql_timeout: 30 #以警告的等级记录超时30秒的sql,默认1秒 41 | timezone: "Asia/Shanghai" 42 | charset: utf8mb4 43 | ssl_level: 0 #加密等级,默认1,取值[0,1],0-不加密,1-可选加密:服务端支持则加密、否则不加密,2-必选加密,服务端不支持则不建立连接,3-满足2外还需验证主机名,4-满足2外还需验证CA证书 44 | ssl_ca_crt_file: path/to/ca.crt #CA 证书 ssl_level:3 生效 45 | ssl_ca_client_cert_file: path/to/client.crt #SSL 客户端证书 ssl_level:3 生效 46 | ssl_ca_client_key_file: path/to/client.key #SSL 客户端密钥 ssl_level:3 生效 47 | pool: 48 | max_connections: 100 # 默认100,最大连接池值,即峰值时,操作进行排队 49 | min_connections: 60 # 默认等同于max_size,最小连接池值,即空闲时也维持 50 | connection_timeout: 30 # 默认8秒,连接超时时间(最大255) 51 | max_lifetime: 1800 # 默认30 秒,连接最大存活时间 52 | idle_timeout: 1800 # 默认8 秒,连接空闲回收 53 | check_health: true # 默认true,连接池维持健康测试 54 | server: 55 | session: 56 | lan_ip: 172.18.38.186 # 不能写成0.0.0.0或者127.0.0.1,必须是网卡上的地址 57 | wan_ip: 172.18.38.186 # 公网IP 58 | lan_port: 25600 #lan端口 59 | wan_port: 25600 #wan端口 60 | alarm: 61 | enable: true #是否开启告警推送,默认true 62 | push_url: http://127.0.0.1:38888/event/alarm #推送地址 63 | priority: 4 #告警等级推送 1-4,默认最低4 64 | videos: 65 | storage_path: ./videos/down #云端录像存储地址,与流媒体服务共享存储【多节点分开部署则使用NFS共享文件系统】 66 | pics: 67 | enable: true #是否开启采集拍照,默认false 68 | push_url: https://epimore.cn/session/api/es/pic/upload 69 | cron_cycle: 0 */5 * * * * #拍照周期cron表达式,默认每5分钟执行一次 70 | num: 1 #连拍张数,最大10 默认1 71 | interval: 1 #连拍间隔秒 max u8 72 | storage_path: ./pics/raw #图片存储地址 73 | storage_format: jpeg #图片存储格式:jpeg,bmp,farbfeld,gif,hdr,ico,exr,png,pnm,qoi,tga,tiff,avif,webp;默认jpeg 74 | stream: 75 | proxy_enable: false #是否统一代理流出口,否-使用流媒体服务的公网ip返回结果 76 | proxy_addr: https://epimore.cn #流代理地址;eg:https://epimore.cn/s1/play/4FEqqzfqsa0Vzqqq2lqqc1lqq4fa.flv?gmv-token=uxxx 77 | nodes: 78 | - name: s1 #流媒体服务的标识,节点名称,唯一值,不能与其他节点重复 79 | pub_ip: 172.18.38.186 #流媒体服务接收rtp流的公网地址 80 | pub_port: 18568 #流媒体服务接收rtp流的端口 81 | local_ip: 127.0.0.1 #节点局域网IP,用于流媒体服务之间通信 82 | local_port: 18570 #节点局域网端口,用于流媒体服务之间通信 83 | # - name: s2 #流媒体服务的标识,节点名称,唯一值,不能与其他节点重复 84 | # pub_ip: 172.18.38.186 #流媒体服务接收rtp流的公网地址 85 | # pub_port: 19568 #流媒体服务接收rtp流的端口 86 | # local_ip: 127.0.0.1 #节点局域网IP,用于流媒体服务之间通信 87 | # local_port: 18570 #节点局域网端口,用于流媒体服务之间通信 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /session/src/app.rs: -------------------------------------------------------------------------------- 1 | use std::net::UdpSocket; 2 | 3 | use common::daemon::Daemon; 4 | use common::dbx::mysqlx; 5 | use common::exception::{GlobalError, GlobalResult, TransError}; 6 | use common::log::{error, info}; 7 | use common::logger; 8 | use common::tokio; 9 | 10 | use crate::gb::SessionConf; 11 | use crate::general::http::Http; 12 | use crate::general::runner::{PicsRunner, Runner}; 13 | 14 | #[derive(Debug)] 15 | pub struct AppInfo { 16 | session_conf: SessionConf, 17 | http: Http, 18 | } 19 | 20 | impl Daemon<(std::net::TcpListener, (Option, Option))> for AppInfo { 21 | fn init_privilege() -> GlobalResult<(Self, (std::net::TcpListener, (Option, Option)))> 22 | where 23 | Self: Sized, 24 | { 25 | let app_info = AppInfo { 26 | session_conf: SessionConf::get_session_by_conf(), 27 | http: Http::get_http_by_conf(), 28 | }; 29 | logger::Logger::init()?; 30 | banner(); 31 | let http_listener = app_info.http.listen_http_server()?; 32 | let tu = app_info.session_conf.listen_gb_server()?; 33 | Ok((app_info, (http_listener, tu))) 34 | } 35 | 36 | fn run_app(self, t: (std::net::TcpListener, (Option, Option))) -> GlobalResult<()> { 37 | let http = self.http; 38 | let (http_listener, tu) = t; 39 | tokio::runtime::Builder::new_multi_thread() 40 | .enable_all() 41 | .build() 42 | .unwrap() 43 | .block_on(async { 44 | mysqlx::init_conn_pool()?; 45 | let web = tokio::spawn(async move { 46 | info!("Web server start running..."); 47 | http.run(http_listener).await?; 48 | error!("Web server stop"); 49 | Ok::<(), GlobalError>(()) 50 | }); 51 | let se = tokio::spawn(async move { 52 | info!("Session server start running..."); 53 | SessionConf::run(tu).await?; 54 | error!("Session server stop"); 55 | Ok::<(), GlobalError>(()) 56 | }); 57 | PicsRunner::next().await; 58 | se.await.hand_log(|msg| error!("Session:{msg}"))??; 59 | web.await.hand_log(|msg| error!("WEB:{msg}"))??; 60 | Ok::<(), GlobalError>(()) 61 | })?; 62 | error!("系统异常退出..."); 63 | Ok(()) 64 | } 65 | } 66 | 67 | fn banner() { 68 | let br = r#" 69 | ___ __ __ __ __ _ ___ ___ ___ ___ ___ ___ _ _ 70 | o O O / __| | \/ | \ \ / / (_) / __| | __| / __| / __| |_ _| / _ \ | \| | 71 | o | (_ | | |\/| | \ V / _ \__ \ | _| \__ \ \__ \ | | | (_) | | .` | 72 | o0__[O] \___| |_|__|_| _\_/_ _(_)_ |___/ |___| |___/ |___/ |___| \___/ |_|\_| 73 | {======|_|""G""|_|""M""|_|""V""|_|"":""|_|""S""|_|""E""|_|""S""|_|""S""|_|""I""|_|""O""|_|""N""| 74 | ./0--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' 75 | "#; 76 | info!("{}", br); 77 | } -------------------------------------------------------------------------------- /session/src/gb/handler/cmd.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::time::Duration; 3 | 4 | use regex::Regex; 5 | use rsip::prelude::{HeadersExt, UntypedHeader}; 6 | use rsip::{Response, SipMessage}; 7 | 8 | use common::exception::{GlobalError, GlobalResult, TransError}; 9 | use common::log::{debug, error, warn}; 10 | use common::tokio::sync::mpsc; 11 | use common::tokio::time::Instant; 12 | 13 | use crate::gb::handler::builder::{RequestBuilder, ResponseBuilder}; 14 | use crate::gb::shared::event::{Container, EventSession, Ident}; 15 | use crate::gb::shared::rw::RequestOutput; 16 | use crate::general::model::{PtzControlModel, StreamMode}; 17 | 18 | pub struct CmdResponse; 19 | 20 | pub struct CmdQuery; 21 | 22 | impl CmdQuery { 23 | pub async fn query_preset(device_id: &String, channel_id_opt: Option<&String>) -> GlobalResult<()> { 24 | let (ident, msg) = RequestBuilder::query_preset(device_id, channel_id_opt).await?; 25 | RequestOutput::new(ident, msg, None).do_send() 26 | } 27 | pub async fn query_device_info(device_id: &String) -> GlobalResult<()> { 28 | let (ident, msg) = RequestBuilder::query_device_info(device_id).await?; 29 | RequestOutput::new(ident, msg, None).do_send() 30 | } 31 | pub async fn query_device_catalog(device_id: &String) -> GlobalResult<()> { 32 | let (ident, msg) = RequestBuilder::query_device_catalog(device_id).await?; 33 | RequestOutput::new(ident, msg, None).do_send() 34 | } 35 | pub async fn subscribe_device_catalog(device_id: &String) -> GlobalResult<()> { 36 | let (ident, msg) = RequestBuilder::subscribe_device_catalog(device_id).await?; 37 | RequestOutput::new(ident, msg, None).do_send() 38 | } 39 | pub async fn lazy_query_device_info(device_id: &String) -> GlobalResult<()> { 40 | let (ident, msg) = RequestBuilder::query_device_info(device_id).await?; 41 | let when = Instant::now() + Duration::from_secs(2); 42 | EventSession::listen_event(&ident.clone(), when, Container::build_actor(ident, msg, None)) 43 | } 44 | pub async fn lazy_query_device_catalog(device_id: &String) -> GlobalResult<()> { 45 | let (ident, msg) = RequestBuilder::query_device_catalog(device_id).await?; 46 | let when = Instant::now() + Duration::from_secs(2); 47 | EventSession::listen_event(&ident.clone(), when, Container::build_actor(ident, msg, None)) 48 | } 49 | 50 | pub async fn lazy_subscribe_device_catalog(device_id: &String) -> GlobalResult<()> { 51 | let (ident, msg) = RequestBuilder::subscribe_device_catalog(device_id).await?; 52 | let when = Instant::now() + Duration::from_secs(2); 53 | EventSession::listen_event(&ident.clone(), when, Container::build_actor(ident, msg, None)) 54 | } 55 | } 56 | 57 | pub struct CmdControl; 58 | 59 | impl CmdControl { 60 | pub async fn control_ptz(ptz_control_model: &PtzControlModel) -> GlobalResult<()> { 61 | let (ident, msg) = RequestBuilder::control_ptz(ptz_control_model).await?; 62 | RequestOutput::new(ident, msg, None).do_send() 63 | } 64 | 65 | pub async fn snapshot_image(device_id: &String, channel_id: &String, num: u8, interval: u8, uri: &String, session_id: &String) -> GlobalResult<()> { 66 | let (ident, msg) = RequestBuilder::control_snapshot_image(device_id, channel_id, num, interval, uri, session_id).await?; 67 | RequestOutput::new(ident, msg, None).do_send() 68 | // let device = GmvDevice::query_gmv_device_by_device_id(device_id).await?.ok_or_else(|| GlobalError::new_sys_error(&format!("未知设备: {device_id}"), |msg| error!("{msg}")))?; 69 | // match device.get_gb_version().as_deref() { 70 | // Some("3.0") => { 71 | // let (ident, msg) = RequestBuilder::control_snapshot_image(device_id, channel_id, num, interval, uri, session_id).await?; 72 | // RequestOutput::new(ident, msg, None).do_send() 73 | // } 74 | // _ => { 75 | // Err(GlobalError::new_sys_error(&format!("未知设备: {device_id}"), |msg| error!("{msg}"))) 76 | // } 77 | // } 78 | } 79 | } 80 | 81 | pub struct CmdNotify; 82 | 83 | pub struct CmdStream; 84 | 85 | impl CmdStream { 86 | pub async fn download_invite(device_id: &String, channel_id: &String, dst_ip: &String, dst_port: u16, stream_mode: StreamMode, ssrc: &String, st: u32, et: u32, speed: u8) 87 | -> GlobalResult<(Response, HashMap, String, String)> { 88 | let (ident, msg) = RequestBuilder::download(device_id, channel_id, dst_ip, dst_port, stream_mode, ssrc, st, et, speed) 89 | .await.hand_log(|msg| warn!("{msg}"))?; 90 | Self::invite_stream(ident, msg).await 91 | } 92 | 93 | pub async fn play_back_invite(device_id: &String, channel_id: &String, dst_ip: &String, dst_port: u16, stream_mode: StreamMode, ssrc: &String, st: u32, et: u32) 94 | -> GlobalResult<(Response, HashMap, String, String)> { 95 | let (ident, msg) = RequestBuilder::playback(device_id, channel_id, dst_ip, dst_port, stream_mode, ssrc, st, et) 96 | .await.hand_log(|msg| warn!("{msg}"))?; 97 | Self::invite_stream(ident, msg).await 98 | } 99 | pub async fn play_live_invite(device_id: &String, channel_id: &String, dst_ip: &String, dst_port: u16, stream_mode: StreamMode, ssrc: &String) 100 | -> GlobalResult<(Response, HashMap, String, String)> { 101 | let (ident, msg) = RequestBuilder::play_live_request(device_id, channel_id, dst_ip, dst_port, stream_mode, ssrc) 102 | .await.hand_log(|msg| warn!("{msg}"))?; 103 | Self::invite_stream(ident, msg).await 104 | } 105 | 106 | pub fn invite_ack(device_id: &String, response: &Response) -> GlobalResult<(String, u32)> { 107 | let ack_request = RequestBuilder::build_ack_request_by_response(response)?; 108 | let call_id = ack_request.call_id_header().hand_log(|msg| warn!("{msg}"))?.value().to_string(); 109 | let seq = ack_request.cseq_header().hand_log(|msg| warn!("{msg}"))?.seq().hand_log(|msg| warn!("{msg}"))?; 110 | RequestOutput::do_send_off(device_id, ack_request).hand_log(|msg| warn!("{msg}"))?; 111 | Ok((call_id, seq)) 112 | } 113 | pub async fn play_speed(device_id: &String, channel_id: &String, speed: f32, from_tag: &str, to_tag: &str, seq: u32, call_id: String) -> GlobalResult<()> { 114 | let (ident, msg) = RequestBuilder::speed(device_id, channel_id, speed, from_tag, to_tag, seq, call_id).await?; 115 | let (tx, mut rx) = mpsc::channel(10); 116 | RequestOutput::new(ident.clone(), msg, Some(tx)).do_send().hand_log(|msg| error!("未响应:{msg}"))?; 117 | if let Some((Some(res), _)) = rx.recv().await { 118 | if res.status_code.code() == 200 { 119 | EventSession::remove_event(&ident); 120 | return Ok(()); 121 | } 122 | error!("speed: ident = {:?},channel_id = {},res = {}",&ident,channel_id,res.status_code); 123 | } 124 | EventSession::remove_event(&ident); 125 | return Err(GlobalError::new_biz_error(1000, "speed倍速未响应或超时", |msg| error!("{msg}"))); 126 | } 127 | pub async fn play_seek(device_id: &String, channel_id: &String, seek: u32, from_tag: &str, to_tag: &str, seq: u32, call_id: String) -> GlobalResult<()> { 128 | let (ident, msg) = RequestBuilder::seek(device_id, channel_id, seek, from_tag, to_tag, seq, call_id).await?; 129 | let (tx, mut rx) = mpsc::channel(10); 130 | RequestOutput::new(ident.clone(), msg, Some(tx)).do_send().hand_log(|msg| error!("未响应:{msg}"))?; 131 | if let Some((Some(res), _)) = rx.recv().await { 132 | if res.status_code.code() == 200 { 133 | EventSession::remove_event(&ident); 134 | return Ok(()); 135 | } 136 | error!("seek: ident = {:?},channel_id = {},res = {}",&ident,channel_id,res.status_code); 137 | } 138 | EventSession::remove_event(&ident); 139 | return Err(GlobalError::new_biz_error(1000, "seek拖动未响应或超时", |msg| error!("{msg}"))); 140 | } 141 | 142 | pub async fn play_bye(seq: u32, call_id: String, device_id: &String, channel_id: &String, from_tag: &str, to_tag: &str) -> GlobalResult<()> { 143 | let (ident, msg) = RequestBuilder::build_bye_request(seq, call_id, device_id, channel_id, from_tag, to_tag).await?; 144 | let (tx, mut rx) = mpsc::channel(10); 145 | 146 | RequestOutput::new(ident.clone(), msg, Some(tx)).do_send().hand_log(|msg| error!("未响应:{msg}"))?; 147 | 148 | if let Some((Some(res), _)) = rx.recv().await { 149 | if res.status_code.code() == 200 { 150 | EventSession::remove_event(&ident); 151 | return Ok(()); 152 | } 153 | error!("关闭摄像机: ident = {:?},channel_id = {},res = {}",&ident,channel_id,res.status_code); 154 | } 155 | EventSession::remove_event(&ident); 156 | return Err(GlobalError::new_biz_error(1000, "关闭摄像机直播未响应或超时", |msg| error!("{msg}"))); 157 | } 158 | async fn invite_stream(ident: Ident, msg: SipMessage) -> GlobalResult<(Response, HashMap, String, String)> { 159 | let (tx, mut rx) = mpsc::channel(10); 160 | RequestOutput::new(ident.clone(), msg, Some(tx)).do_send()?; 161 | while let Some((Some(res), _)) = rx.recv().await { 162 | let code = res.status_code.code(); 163 | let code_msg = res.status_code.to_string(); 164 | debug!("{ident:?} : {code} => {code_msg}"); 165 | if code >= 300 { 166 | EventSession::remove_event(&ident); 167 | return Err(GlobalError::new_biz_error(3000, &code_msg, |msg| error!("{msg}"))); 168 | } 169 | if code == 200 { 170 | let session = sdp_types::Session::parse(res.body()).unwrap(); 171 | debug!("{ident:?} :{:?}",&session); 172 | let re = Regex::new(r"\s+").unwrap(); 173 | let mut media_map = HashMap::new(); 174 | for media in session.medias { 175 | for attr in media.attributes { 176 | if attr.attribute.eq("rtpmap") { 177 | if let Some(info) = attr.value { 178 | if let Some((key, val)) = re.replace_all(info.trim(), " ").split_once(" ") { 179 | let tp = key.parse::().hand_log(|msg| error!("{msg}"))?; 180 | let i = val.find('/').unwrap_or(val.len()); 181 | media_map.insert(tp, val[0..i].to_uppercase()); 182 | } 183 | } 184 | } 185 | } 186 | } 187 | let from_tag = ResponseBuilder::get_tag_by_header_from(&res)?; 188 | let to_tag = ResponseBuilder::get_tag_by_header_to(&res)?; 189 | EventSession::remove_event(&ident); 190 | return Ok((res, media_map, from_tag, to_tag)); 191 | } 192 | } 193 | EventSession::remove_event(&ident); 194 | return Err(GlobalError::new_biz_error(1000, "摄像机响应超时", |msg| error!("{msg}"))); 195 | } 196 | } 197 | 198 | 199 | #[cfg(test)] 200 | #[allow(unused)] 201 | mod test { 202 | use regex::Regex; 203 | 204 | #[test] 205 | fn test_parse_sdp() { 206 | let sdp_str = "v=0 207 | o=33010602001310019325 0 0 IN IP4 10.64.49.44 208 | s=Play 209 | c=IN IP4 10.64.49.218 210 | t=0 0 211 | m=video 5514 RTP/AVP 96 212 | a=rtpmap:96 PS/90000 213 | a=sendonly 214 | y=0060205514"; 215 | let session = sdp_types::Session::parse(sdp_str.as_ref()).unwrap(); 216 | println!("{:#?}", session); 217 | } 218 | 219 | 220 | #[test] 221 | fn test_str_blank() { 222 | let str0 = " 96 PS/90000 "; 223 | let str1 = "96 PS/90000"; 224 | let str2 = "96 PS/90000"; 225 | let str3 = " 96 PS/90000"; 226 | let str4 = "96 PS/90000 "; 227 | let re = Regex::new(r"\s+").unwrap(); 228 | let s0 = str0.trim().replace(" ", " "); 229 | 230 | println!("{s0}"); 231 | } 232 | } -------------------------------------------------------------------------------- /session/src/gb/handler/events.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/session/src/gb/handler/events.rs -------------------------------------------------------------------------------- /session/src/gb/handler/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod requester; 2 | mod events; 3 | mod builder; 4 | pub mod parser; 5 | pub mod cmd; -------------------------------------------------------------------------------- /session/src/gb/handler/parser.rs: -------------------------------------------------------------------------------- 1 | pub mod header { 2 | use rsip::headers::Via; 3 | use rsip::prelude::{HasHeaders, HeadersExt}; 4 | use rsip::{Header, Request, Response}; 5 | use common::anyhow::anyhow; 6 | use common::exception::{GlobalResult, TransError}; 7 | use common::exception::GlobalError::{SysErr}; 8 | use common::log::{warn}; 9 | 10 | pub fn get_device_id_by_request(req: &Request) -> GlobalResult { 11 | let from_user = req.from_header() 12 | .hand_log(|msg| warn!("{msg}"))? 13 | .uri().hand_log(|msg| warn!("{msg}"))? 14 | .auth.ok_or(SysErr(anyhow!("user is none"))) 15 | .hand_log(|msg| warn!("{msg}"))? 16 | .user; 17 | Ok(from_user) 18 | } 19 | 20 | pub fn get_device_id_by_response(req: &Response) -> GlobalResult { 21 | let from_user = req.to_header() 22 | .hand_log(|msg| warn!("{msg}"))? 23 | .uri().hand_log(|msg| warn!("{msg}"))? 24 | .auth.ok_or(SysErr(anyhow!("user is none"))) 25 | .hand_log(|msg| warn!("{msg}"))? 26 | .user; 27 | Ok(from_user) 28 | } 29 | 30 | pub fn get_via_header(req: &Request) -> GlobalResult<&Via> { 31 | let via = req.via_header().hand_log(|msg| warn!("{msg}"))?; 32 | Ok(via) 33 | } 34 | 35 | pub fn get_transport(req: &Request) -> GlobalResult { 36 | let transport = get_via_header(req)?.trasnport().hand_log(|msg| warn!("{msg}"))?.to_string(); 37 | Ok(transport) 38 | } 39 | 40 | pub fn get_local_addr(req: &Request) -> GlobalResult { 41 | let local_addr = get_via_header(req)?.uri().hand_log(|msg| warn!("{msg}"))?.host_with_port.to_string(); 42 | Ok(local_addr) 43 | } 44 | 45 | pub fn get_from(req: &Request) -> GlobalResult { 46 | let from = req.from_header().hand_log(|msg| warn!("{msg}"))?.uri().hand_log(|msg| warn!("{msg}"))?.to_string(); 47 | Ok(from) 48 | } 49 | 50 | pub fn get_to(req: &Request) -> GlobalResult { 51 | let to = req.to_header().hand_log(|msg| warn!("{msg}"))?.uri().hand_log(|msg| warn!("{msg}"))?.to_string(); 52 | Ok(to) 53 | } 54 | 55 | pub fn get_expires(req: &Request) -> GlobalResult { 56 | let expires = req.expires_header() 57 | .ok_or(SysErr(anyhow!("无参数expires"))) 58 | .hand_log(|msg| warn!("{msg}"))? 59 | .seconds().hand_log(|msg| warn!("{msg}"))?; 60 | Ok(expires) 61 | } 62 | 63 | pub fn get_domain(req: &Request) -> GlobalResult { 64 | let to_uri = req.to_header().hand_log(|msg| warn!("{msg}"))?.uri().hand_log(|msg| warn!("{msg}"))?; 65 | Ok(to_uri.host_with_port.to_string()) 66 | } 67 | 68 | pub fn get_gb_version(req: &Request) -> Option { 69 | for header in req.headers().iter() { 70 | match header { 71 | Header::Other(key, val) => { 72 | if key.eq("X-GB-Ver") { 73 | return Some(val.to_string()); 74 | // return match &val[..] { 75 | // "1.0" => Some("GB/T 28181—2011".to_string()), 76 | // "1.1" => Some("GB/T 28181—2011-1".to_string()), 77 | // "2.0" => Some("GB/T 28181—2016".to_string()), 78 | // "3.0" => Some("GB/T 28181—2022".to_string()), 79 | // &_ => Some(val.to_string()) 80 | // }; 81 | } 82 | } 83 | _ => { continue; } 84 | }; 85 | } 86 | None 87 | } 88 | } 89 | 90 | pub mod xml { 91 | use std::ops::Deref; 92 | use std::str::from_utf8; 93 | use encoding_rs::GB18030; 94 | use common::log::{debug, error}; 95 | use quick_xml::events::Event; 96 | use quick_xml::{encoding, Reader}; 97 | use common::anyhow::{anyhow}; 98 | use common::exception::{GlobalResult, TransError}; 99 | use common::exception::GlobalError::SysErr; 100 | 101 | pub const MESSAGE_TYPE: [&'static str; 4] = ["Query,CmdType", "Control,CmdType", "Response,CmdType", "Notify,CmdType"]; 102 | pub const MESSAGE_KEEP_ALIVE: &str = "Keepalive"; 103 | pub const MESSAGE_CONFIG_DOWNLOAD: &str = "ConfigDownload"; 104 | pub const MESSAGE_NOTIFY_CATALOG: &str = "Catalog"; 105 | pub const MESSAGE_DEVICE_INFO: &str = "DeviceInfo"; 106 | pub const MESSAGE_ALARM: &str = "Alarm"; 107 | pub const MESSAGE_RECORD_INFO: &str = "RecordInfo"; 108 | pub const MESSAGE_MEDIA_STATUS: &str = "MediaStatus"; 109 | pub const MESSAGE_BROADCAST: &str = "Broadcast"; 110 | pub const MESSAGE_DEVICE_STATUS: &str = "DeviceStatus"; 111 | pub const MESSAGE_DEVICE_CONTROL: &str = "DeviceControl"; 112 | pub const MESSAGE_DEVICE_CONFIG: &str = "DeviceConfig"; 113 | pub const MESSAGE_PRESET_QUERY: &str = "PresetQuery"; 114 | pub const RESPONSE_DEVICE_ID: &str = "Response,DeviceID"; 115 | pub const RESPONSE_MANUFACTURER: &str = "Response,Manufacturer"; 116 | pub const RESPONSE_MODEL: &str = "Response,Model"; 117 | pub const RESPONSE_FIRMWARE: &str = "Response,Firmware"; 118 | pub const RESPONSE_DEVICE_TYPE: &str = "Response,DeviceType"; 119 | pub const RESPONSE_MAX_CAMERA: &str = "Response,MaxCamera"; 120 | pub const RESPONSE_DEVICE_LIST_ITEM_DEVICE_ID: &str = "Response,DeviceList,Item,DeviceID"; 121 | pub const RESPONSE_DEVICE_LIST_ITEM_NAME: &str = "Response,DeviceList,Item,Name"; 122 | pub const RESPONSE_DEVICE_LIST_ITEM_MANUFACTURER: &str = "Response,DeviceList,Item,Manufacturer"; 123 | pub const RESPONSE_DEVICE_LIST_ITEM_MODEL: &str = "Response,DeviceList,Item,Model"; 124 | pub const RESPONSE_DEVICE_LIST_ITEM_OWNER: &str = "Response,DeviceList,Item,Owner"; 125 | pub const RESPONSE_DEVICE_LIST_ITEM_CIVIL_CODE: &str = "Response,DeviceList,Item,CivilCode"; 126 | pub const RESPONSE_DEVICE_LIST_ITEM_BLOCK: &str = "Response,DeviceList,Item,Block"; 127 | pub const RESPONSE_DEVICE_LIST_ITEM_ADDRESS: &str = "Response,DeviceList,Item,Address"; 128 | pub const RESPONSE_DEVICE_LIST_ITEM_PARENTAL: &str = "Response,DeviceList,Item,Parental"; 129 | pub const RESPONSE_DEVICE_LIST_ITEM_PARENT_ID: &str = "Response,DeviceList,Item,ParentID"; 130 | pub const RESPONSE_DEVICE_LIST_ITEM_LONGITUDE: &str = "Response,DeviceList,Item,Longitude"; 131 | pub const RESPONSE_DEVICE_LIST_ITEM_LATITUDE: &str = "Response,DeviceList,Item,Latitude"; 132 | pub const RESPONSE_DEVICE_LIST_ITEM_PTZ_TYPE: &str = "Response,DeviceList,Item,Info,PTZType"; 133 | pub const RESPONSE_DEVICE_LIST_ITEM_SUPPLY_LIGHT_TYPE: &str = "Response,DeviceList,Item,SupplyLightType"; 134 | pub const RESPONSE_DEVICE_LIST_ITEM_IP_ADDRESS: &str = "Response,DeviceList,Item,IPAddress"; 135 | pub const RESPONSE_DEVICE_LIST_ITEM_PORT: &str = "Response,DeviceList,Item,Port"; 136 | pub const RESPONSE_DEVICE_LIST_ITEM_PASSWORD: &str = "Response,DeviceList,Item,Password"; 137 | pub const RESPONSE_DEVICE_LIST_ITEM_STATUS: &str = "Response,DeviceList,Item,Status"; 138 | pub const SPLIT_CLASS: &str = "?<-0_0->?"; 139 | pub const NOTIFY_DEVICE_ID: &str = "Notify,DeviceID"; 140 | pub const NOTIFY_STATUS: &str = "Notify,Status"; 141 | pub const NOTIFY_TYPE: &str = "Notify,NotifyType"; 142 | 143 | 144 | pub const NOTIFY_ALARM_PRIORITY: &str = "Notify,AlarmPriority"; 145 | pub const NOTIFY_ALARM_TIME: &str = "Notify,AlarmTime"; 146 | pub const NOTIFY_ALARM_METHOD: &str = "Notify,AlarmMethod"; 147 | pub const NOTIFY_INFO_ALARM_TYPE: &str = "Notify,Info,AlarmType"; 148 | 149 | pub fn parse_xlm_to_vec(xml: &[u8]) -> GlobalResult> { 150 | let mut xml_reader = Reader::from_reader(xml); 151 | xml_reader.trim_text(true); 152 | xml_reader.expand_empty_elements(true); 153 | let mut vec: Vec<(String, String)> = Vec::new(); 154 | let mut tag: String = String::new(); 155 | let mut k = 0; 156 | let mut j = false; 157 | let mut b = false; 158 | loop { 159 | match xml_reader.read_event() { 160 | Ok(Event::Start(ref e)) => { 161 | let start_tag = from_utf8(e.name().0).hand_log(|msg| error!("{msg}"))?; 162 | tag.push_str(&*format!("{},", start_tag)); 163 | b = false; 164 | } 165 | Ok(Event::Text(e)) => { 166 | //此处使用GB18030进行解析,兼容新版本要求 167 | let val = encoding::decode(e.deref(), GB18030).hand_log(|msg| error!("{msg}"))?; 168 | let len = tag.split(",").collect::>().len() - 1; 169 | if k != len || j { 170 | k = len; 171 | vec.push(("?<-0_0->?".to_string(), k.to_string())); 172 | } 173 | let key = tag[..tag.len() - 1].to_string(); 174 | vec.push((key, val.to_string())); 175 | b = false; 176 | } 177 | Ok(Event::End(ref e)) => { 178 | let end = tag.len() - e.len() - 1; 179 | tag = tag[0..end].parse().hand_log(|msg| error!("{msg}"))?; 180 | j = b; 181 | b = true; 182 | } 183 | Err(e) => { 184 | Err(SysErr(anyhow!("Error at position {}: {:?}", xml_reader.buffer_position(), e)))? 185 | } 186 | Ok(Event::Eof) => break, 187 | _ => (), 188 | } 189 | } 190 | debug!("{:?}", &vec); 191 | Ok(vec) 192 | } 193 | 194 | pub trait KV2Model { 195 | fn kv_to_model(arr: Vec<(String, String)>) -> GlobalResult 196 | where 197 | Self: Sized; 198 | } 199 | } -------------------------------------------------------------------------------- /session/src/gb/io.rs: -------------------------------------------------------------------------------- 1 | use encoding_rs::GB18030; 2 | use rsip::message::HeadersExt; 3 | use rsip::SipMessage; 4 | use common::tokio::sync::mpsc::{Receiver, Sender}; 5 | 6 | use common::exception::{TransError}; 7 | use common::log::{debug, error, info}; 8 | use common::net::state::{Package, Zip}; 9 | use crate::gb::handler; 10 | 11 | use crate::gb::handler::parser; 12 | use crate::gb::shared::event::EventSession; 13 | pub use crate::gb::shared::rw::RWSession; 14 | 15 | pub async fn read(mut input: Receiver, output_tx: Sender) { 16 | while let Some(zip) = input.recv().await { 17 | match zip { 18 | Zip::Data(Package { association, data }) => { 19 | match SipMessage::try_from(data) { 20 | Ok(msg) => { 21 | match msg { 22 | SipMessage::Request(req) => { 23 | info!("接收:{:?}\nRequest:\n{} {} {}\n{}\n{}",&association,&req.method,&req.uri,&req.version,&req.headers,GB18030.decode(&req.body).0); 24 | let _ = handler::requester::hand_request(req, output_tx.clone(), &association).await; 25 | } 26 | SipMessage::Response(res) => { 27 | info!("接收:{:?}\nResponse:\n{} {}\n{}\n{}",&association,&res.version,&res.status_code,&res.headers,GB18030.decode(&res.body).0); 28 | match (res.call_id_header(), res.cseq_header(), parser::header::get_device_id_by_response(&res)) { 29 | (Ok(call_id), Ok(cs_eq), Ok(to_device_id)) => { 30 | let _ = EventSession::handle_response(to_device_id, call_id.clone().into(), cs_eq.clone().into(), res).await; 31 | } 32 | (call_res, cseq_res, device_id_res) => { 33 | error!("call={:?},call={:?},call={:?}",call_res,cseq_res,device_id_res); 34 | } 35 | } 36 | } 37 | } 38 | } 39 | Err(err) => { 40 | debug!("接收:invalid data {err:?}"); 41 | } 42 | } 43 | } 44 | Zip::Event(event) => { 45 | info!("接收:event code={},from={:?}",event.type_code,event.association); 46 | if event.get_type_code() == &0u8 { 47 | RWSession::clean_rw_session_by_bill(event.get_association()); 48 | } 49 | } 50 | } 51 | } 52 | info!("gb read exit"); 53 | } 54 | 55 | pub async fn write(mut output_rx: Receiver, output: Sender) { 56 | while let Some(zip) = output_rx.recv().await { 57 | match &zip { 58 | Zip::Data(pkg) => { 59 | info!("发送:{:?}\n负载:\n{}",pkg.get_association(),GB18030.decode(pkg.get_data()).0); 60 | } 61 | Zip::Event(ent) => { 62 | info!("发送:{:?}\n事件code={}",ent.get_association(),ent.get_type_code()); 63 | } 64 | } 65 | let _ = output.send(zip).await.hand_log(|msg| error!("数据发送失败:{msg}")); 66 | } 67 | 68 | info!("gb write exit"); 69 | } -------------------------------------------------------------------------------- /session/src/gb/mod.rs: -------------------------------------------------------------------------------- 1 | use std::net::{Ipv4Addr, SocketAddr, TcpListener, UdpSocket}; 2 | use std::str::FromStr; 3 | 4 | use common::serde::Deserialize; 5 | use common::tokio::sync::mpsc; 6 | use common::cfg_lib::conf; 7 | use common::constructor::Get; 8 | 9 | use common::exception::{GlobalResult, TransError}; 10 | use common::log::{error, info}; 11 | use common::net; 12 | use common::net::state::{CHANNEL_BUFFER_SIZE}; 13 | 14 | pub use crate::gb::shared::rw::RWSession; 15 | 16 | mod shared; 17 | pub mod handler; 18 | mod io; 19 | 20 | #[derive(Debug, Get, Deserialize)] 21 | #[serde(crate = "common::serde")] 22 | #[conf(prefix = "server.session")] 23 | pub struct SessionConf { 24 | lan_ip: Ipv4Addr, 25 | wan_ip: Ipv4Addr, 26 | lan_port: u16, 27 | wan_port: u16, 28 | } 29 | 30 | impl SessionConf { 31 | pub fn get_session_by_conf() -> Self { 32 | SessionConf::conf() 33 | } 34 | 35 | pub fn listen_gb_server(&self) -> GlobalResult<(Option, Option)> { 36 | let socket_addr = SocketAddr::from_str(&format!("0.0.0.0:{}", self.get_wan_port())).hand_log(|msg| error! {"{msg}"})?; 37 | let res = net::sdx::listen(net::state::Protocol::ALL, socket_addr); 38 | info!("Listen to gb28181 session over tcp and udp,listen: 0.0.0.0:{}; wan ip: {}", self.get_wan_port(), self.get_wan_ip()); 39 | res 40 | } 41 | 42 | pub async fn run(tu: (Option, Option)) -> GlobalResult<()> { 43 | let (output, input) = net::sdx::run_by_tokio(tu).await?; 44 | let (output_tx, output_rx) = mpsc::channel(CHANNEL_BUFFER_SIZE); 45 | let read_task = common::tokio::spawn(async move { 46 | io::read(input, output_tx).await; 47 | }); 48 | let write_task = common::tokio::spawn(async move { 49 | io::write(output_rx, output).await; 50 | }); 51 | read_task.await.hand_log(|msg| error!("读取数据异常:{msg}"))?; 52 | write_task.await.hand_log(|msg| error!("写出数据异常:{msg}"))?; 53 | Ok(()) 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /session/src/general/http.rs: -------------------------------------------------------------------------------- 1 | use poem::http::Method; 2 | use poem::listener::{TcpAcceptor}; 3 | use poem::middleware::Cors; 4 | use poem::{EndpointExt, Route, Server}; 5 | use poem_openapi::OpenApiService; 6 | use common::serde::{Deserialize}; 7 | use common::cfg_lib::conf; 8 | use common::log::{error, info}; 9 | use common::exception::{GlobalResult, TransError}; 10 | use common::serde_default; 11 | use crate::{web}; 12 | 13 | #[derive(Debug, Deserialize)] 14 | #[serde(crate = "common::serde")] 15 | #[conf(prefix = "http")] 16 | pub struct Http { 17 | #[serde(default = "default_port")] 18 | pub port: u16, 19 | #[serde(default = "default_timeout")] 20 | pub timeout: u16, 21 | #[serde(default = "default_prefix")] 22 | pub prefix: String, 23 | #[serde(default = "default_server_name")] 24 | pub server_name: String, 25 | #[serde(default = "default_version")] 26 | pub version: String, 27 | } 28 | serde_default!(default_port, u16, 8080); 29 | serde_default!(default_timeout, u16, 30); 30 | serde_default!(default_prefix, String, "/gmv".to_string()); 31 | serde_default!(default_server_name, String, "web-server".to_string()); 32 | serde_default!(default_version, String, "v0.1".to_string()); 33 | impl Http { 34 | pub fn get_http_by_conf() -> Self { 35 | Http::conf() 36 | } 37 | pub fn listen_http_server(&self) -> GlobalResult { 38 | let listener = std::net::TcpListener::bind(format!("0.0.0.0:{}", self.port)).hand_log(|msg| error!("{msg}"))?; 39 | info!("Listen to http web addr = 0.0.0.0:{} ...", self.port); 40 | Ok(listener) 41 | } 42 | 43 | pub async fn run(&self, listener: std::net::TcpListener) -> GlobalResult<()> { 44 | let service = OpenApiService::new((web::api::RestApi, web::hook::HookApi, web::se::SeApi), &self.server_name, &self.version) 45 | .server(format!("http://0.0.0.0:{}{}", &self.port, &self.prefix)); 46 | let ui = service.swagger_ui(); 47 | let route = Route::new() 48 | .nest(&self.prefix, service 49 | .with(Cors::new().allow_methods([Method::GET, Method::POST]))) 50 | .nest("/docs", ui); 51 | listener.set_nonblocking(true).hand_log(|msg| error!("{msg}"))?; 52 | let acceptor = TcpAcceptor::from_std(listener).hand_log(|msg| error!("{msg}"))?; 53 | Server::new_with_acceptor(acceptor).run(route).await.hand_log(|msg| error!("{msg}"))?; 54 | error!("http server exception:exited"); 55 | Ok(()) 56 | } 57 | } -------------------------------------------------------------------------------- /session/src/general/mod.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashMap}; 2 | use std::fs; 3 | use std::net::Ipv4Addr; 4 | use std::sync::OnceLock; 5 | use common::{serde_default}; 6 | use common::cfg_lib::conf; 7 | use common::cfg_lib::conf::{CheckFromConf, FieldCheckError}; 8 | use common::constructor::Get; 9 | use common::once_cell::sync::OnceCell; 10 | use common::serde::{Deserialize}; 11 | use url::Url; 12 | 13 | pub mod model; 14 | pub mod cache; 15 | pub mod http; 16 | mod schedule; 17 | pub mod runner; 18 | 19 | #[derive(Debug, Deserialize)] 20 | #[serde(crate = "common::serde")] 21 | #[conf(prefix = "server.alarm", check)] 22 | pub struct AlarmConf { 23 | pub enable: bool, 24 | pub push_url: Option, 25 | #[serde(default = "default_priority")] 26 | pub priority: u8, 27 | } 28 | serde_default!(default_priority, u8, 4); 29 | static ALARM_CONF: OnceLock = OnceLock::new(); 30 | 31 | impl AlarmConf { 32 | pub fn get_alarm_conf() -> &'static Self { 33 | ALARM_CONF.get_or_init(|| { 34 | AlarmConf::conf() 35 | }) 36 | } 37 | } 38 | 39 | impl CheckFromConf for AlarmConf { 40 | fn _field_check(&self) -> Result<(), FieldCheckError> { 41 | if self.enable { 42 | if self.push_url.is_none() || self.push_url.as_ref().unwrap().is_empty() { 43 | return Err(FieldCheckError::BizError("server.alarm.push_url不能为空".to_string())); 44 | } 45 | 46 | if Url::parse(self.push_url.as_ref().unwrap()).is_err() { 47 | return Err(FieldCheckError::BizError("server.alarm.push_url非有效的url地址".to_string())); 48 | } 49 | } 50 | 51 | if self.priority == 0 || self.priority > 4 { 52 | return Err(FieldCheckError::BizError("server.alarm.priority必须为1|2|3|4".to_string())); 53 | } 54 | Ok(()) 55 | } 56 | } 57 | 58 | #[derive(Debug, Get, Deserialize)] 59 | #[serde(crate = "common::serde")] 60 | #[conf(prefix = "server.stream")] 61 | pub struct StreamConf { 62 | pub proxy_enable: bool, 63 | pub proxy_addr: Option, 64 | #[serde(default = "default_node_map")] 65 | pub node_map: HashMap, 66 | pub nodes: Vec, 67 | } 68 | serde_default!(default_node_map, HashMap, HashMap::new()); 69 | #[derive(Debug, Get, Deserialize, Clone)] 70 | #[serde(crate = "common::serde")] 71 | pub struct StreamNode { 72 | pub name: String, 73 | pub local_ip: Ipv4Addr, 74 | pub local_port: u16, 75 | pub pub_ip: Ipv4Addr, 76 | pub pub_port: u16, 77 | } 78 | 79 | static CELL: OnceCell = OnceCell::new(); 80 | 81 | impl StreamConf { 82 | pub fn get_stream_conf() -> &'static Self { 83 | CELL.get_or_init(|| { 84 | let mut conf: Self = StreamConf::conf(); 85 | for node in &conf.nodes { 86 | if let Some(old) = conf.node_map.insert(node.name.clone(), node.clone()) { 87 | panic!("配置server.stream.nodes.name重复:{}:,建议使用s1,s2,s3等连续编号", old.name); 88 | } 89 | } 90 | if conf.node_map.is_empty() { 91 | panic!("未配置流媒体信息") 92 | } 93 | conf 94 | }) 95 | } 96 | } 97 | 98 | #[derive(Debug, Deserialize, Clone)] 99 | #[serde(crate = "common::serde")] 100 | #[conf(prefix = "server.videos", check)] 101 | pub struct DownloadConf { 102 | pub storage_path: String, 103 | } 104 | impl CheckFromConf for DownloadConf { 105 | fn _field_check(&self) -> Result<(), FieldCheckError> { 106 | let dc = DownloadConf::conf(); 107 | fs::create_dir_all(&dc.storage_path).map_err(|e| FieldCheckError::BizError(format!("create download dir failed: {}", e.to_string())))?; 108 | Ok(()) 109 | } 110 | } 111 | 112 | impl DownloadConf { 113 | pub fn get_download_conf() -> Self { 114 | DownloadConf::conf() 115 | } 116 | } 117 | 118 | #[cfg(test)] 119 | mod tests { 120 | 121 | // #[test] 122 | // fn test_map_conf() { 123 | // println!("{:?}", super::StreamConf::get_stream_conf()); 124 | // } 125 | 126 | fn print_banner(c: char) { 127 | let binary = match c { 128 | 'G' => [ 129 | 0b11111, 130 | 0b10000, 131 | 0b10011, 132 | 0b10001, 133 | 0b11111, 134 | ], 135 | 'M' => [ 136 | 0b10001, 137 | 0b11011, 138 | 0b10101, 139 | 0b10001, 140 | 0b10001, 141 | ], 142 | 'V' => [ 143 | 0b10001, 144 | 0b10001, 145 | 0b01010, 146 | 0b00100, 147 | 0b00100, 148 | ], 149 | _ => [0; 5], 150 | }; 151 | 152 | for &row in binary.iter() { 153 | for i in (0..5).rev() { 154 | print!("{}", if row & (1 << i) == 0 { ' ' } else { '#' }); 155 | } 156 | println!(); 157 | } 158 | println!(); 159 | } 160 | 161 | #[test] 162 | fn test_banner() { 163 | print_banner('G'); 164 | print_banner('M'); 165 | print_banner('V'); 166 | } 167 | } -------------------------------------------------------------------------------- /session/src/general/model.rs: -------------------------------------------------------------------------------- 1 | use poem_openapi::{self, Object}; 2 | use poem_openapi::types::{ParseFromJSON, ToJSON, Type}; 3 | use common::serde::{Deserialize, Serialize}; 4 | 5 | use common::anyhow::anyhow; 6 | use common::exception::GlobalError::SysErr; 7 | use common::exception::{GlobalResult, TransError}; 8 | use common::constructor::Get; 9 | use common::log::error; 10 | use crate::gb::handler::parser::xml::KV2Model; 11 | 12 | use crate::general; 13 | 14 | pub enum StreamMode { 15 | Udp, 16 | TcpActive, 17 | TcpPassive, 18 | } 19 | 20 | impl StreamMode { 21 | pub fn build(m: u8) -> GlobalResult { 22 | match m { 23 | 0 => { Ok(StreamMode::Udp) } 24 | 1 => { Ok(StreamMode::TcpActive) } 25 | 2 => { Ok(StreamMode::TcpPassive) } 26 | _ => { Err(SysErr(anyhow!("无效流模式"))) } 27 | } 28 | } 29 | } 30 | 31 | #[derive(Debug, Clone, Eq, PartialEq, Object)] 32 | pub struct ResultMessageData { 33 | code: u16, 34 | msg: Option, 35 | data: Option, 36 | } 37 | 38 | impl ResultMessageData { 39 | #[allow(dead_code)] 40 | pub fn build(code: u16, msg: String, data: T) -> Self { 41 | Self { code, msg: Some(msg), data: Some(data) } 42 | } 43 | 44 | pub fn build_success(data: T) -> Self { 45 | Self { code: 200, msg: Some("success".to_string()), data: Some(data) } 46 | } 47 | pub fn build_success_none() -> Self { 48 | Self { code: 200, msg: Some("success".to_string()), data: None } 49 | } 50 | pub fn build_failure() -> Self { 51 | Self { code: 500, msg: Some("failure".to_string()), data: None } 52 | } 53 | pub fn build_failure_msg(msg: String) -> Self { 54 | Self { code: 500, msg: Some(msg), data: None } 55 | } 56 | } 57 | 58 | 59 | #[derive(Object, Serialize, Deserialize, Debug)] 60 | #[serde(crate = "common::serde")] 61 | pub struct StreamNode { 62 | pub stream_id: String, 63 | pub stream_server: String, 64 | } 65 | 66 | #[derive(Debug, Deserialize, Object, Serialize, Get)] 67 | #[serde(crate = "common::serde")] 68 | pub struct PlayLiveModel { 69 | #[oai(validator(min_length = "20", max_length = "20"))] 70 | device_id: String, 71 | #[oai(validator(min_length = "20", max_length = "20"))] 72 | channel_id: Option, 73 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 74 | trans_mode: Option, 75 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 76 | /// 媒体类型,默认flv,hls开启,(todo 2-mp4 3-webrtc ...) 77 | media_type: Option, 78 | } 79 | 80 | #[derive(Debug, Deserialize, Object, Serialize, Get)] 81 | #[serde(crate = "common::serde")] 82 | pub struct PlayBackModel { 83 | #[oai(validator(min_length = "20", max_length = "20"))] 84 | device_id: String, 85 | #[oai(validator(min_length = "20", max_length = "20"))] 86 | channel_id: Option, 87 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 88 | trans_mode: Option, 89 | st: u32, 90 | et: u32, 91 | } 92 | 93 | #[derive(Debug, Deserialize, Object, Serialize, Get)] 94 | #[serde(crate = "common::serde")] 95 | #[allow(non_snake_case)] 96 | pub struct PlaySeekModel { 97 | #[oai(validator(min_length = "24", max_length = "32") 98 | )] 99 | streamId: String, 100 | #[oai(validator(maximum(value = "86400"), minimum(value = "1")))] 101 | seekSecond: u32, 102 | } 103 | 104 | #[derive(Debug, Deserialize, Object, Serialize, Get)] 105 | #[serde(crate = "common::serde")] 106 | #[allow(non_snake_case)] 107 | pub struct PlaySpeedModel { 108 | #[oai(validator(min_length = "24", max_length = "32") 109 | )] 110 | streamId: String, 111 | #[oai(validator(maximum(value = "8"), minimum(value = "0.25")))] 112 | speedRate: f32, 113 | } 114 | 115 | #[derive(Debug, Deserialize, Object, Serialize, Default)] 116 | #[serde(crate = "common::serde")] 117 | #[allow(non_snake_case)] 118 | pub struct PtzControlModel { 119 | #[oai(validator(min_length = "20", max_length = "20"))] 120 | pub deviceId: String, 121 | #[oai(validator(min_length = "20", max_length = "20"))] 122 | pub channelId: String, 123 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 124 | ///镜头左移右移 0:停止 1:左移 2:右移 125 | pub leftRight: u8, 126 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 127 | ///镜头上移下移 0:停止 1:上移 2:下移 128 | pub upDown: u8, 129 | #[oai(validator(maximum(value = "2"), minimum(value = "0")))] 130 | ///镜头放大缩小 0:停止 1:缩小 2:放大 131 | pub inOut: u8, 132 | #[oai(validator(maximum(value = "255"), minimum(value = "0")))] 133 | ///水平移动速度:1-255 134 | pub horizonSpeed: u8, 135 | #[oai(validator(maximum(value = "255"), minimum(value = "0")))] 136 | ///垂直移动速度:0-255 137 | pub verticalSpeed: u8, 138 | #[oai(validator(maximum(value = "15"), minimum(value = "0")))] 139 | ///焦距缩放速度:0-15 140 | pub zoomSpeed: u8, 141 | } 142 | 143 | #[derive(Debug, Deserialize, Object, Serialize)] 144 | #[serde(crate = "common::serde")] 145 | #[allow(non_snake_case)] 146 | pub struct StreamInfo { 147 | streamId: String, 148 | flv: String, 149 | m3u8: String, 150 | } 151 | 152 | impl StreamInfo { 153 | pub fn build(stream_id: String, node_name: String) -> Self { 154 | let stream_conf = general::StreamConf::get_stream_conf(); 155 | match stream_conf.get_proxy_addr() { 156 | None => { 157 | let node_stream = stream_conf.get_node_map().get(&node_name).unwrap(); 158 | Self { 159 | flv: format!("http://{}:{}/{node_name}/play/{stream_id}.flv", node_stream.get_pub_ip(), node_stream.get_local_port()), 160 | m3u8: format!("http://{}:{}/{node_name}/play/{stream_id}.m3u8", node_stream.get_pub_ip(), node_stream.get_local_port()), 161 | streamId: stream_id, 162 | } 163 | } 164 | Some(addr) => { 165 | Self { 166 | flv: format!("{addr}/{node_name}/play/{stream_id}.flv"), 167 | m3u8: format!("{addr}/{node_name}/play/{stream_id}.m3u8"), 168 | streamId: stream_id, 169 | } 170 | } 171 | } 172 | } 173 | } 174 | 175 | #[derive(Debug, Deserialize, Object, Serialize, Default)] 176 | #[serde(crate = "common::serde")] 177 | #[allow(non_snake_case)] 178 | pub struct AlarmInfo { 179 | pub priority: u8, 180 | pub method: u8, 181 | pub alarmType: u8, 182 | pub timeStr: String, 183 | pub deviceId: String, 184 | pub channelId: String, 185 | } 186 | 187 | impl KV2Model for AlarmInfo { 188 | fn kv_to_model(arr: Vec<(String, String)>) -> GlobalResult { 189 | use crate::gb::handler::parser::xml::*; 190 | let mut model = AlarmInfo::default(); 191 | for (k, v) in arr { 192 | match &k[..] { 193 | NOTIFY_DEVICE_ID => { 194 | model.channelId = v; 195 | } 196 | NOTIFY_ALARM_PRIORITY => { 197 | model.priority = v.parse::().hand_log(|msg| error!("{msg}"))?; 198 | } 199 | NOTIFY_ALARM_TIME => { 200 | model.timeStr = v; 201 | } 202 | NOTIFY_ALARM_METHOD => { 203 | model.method = v.parse::().hand_log(|msg| error!("{msg}"))?; 204 | } 205 | NOTIFY_INFO_ALARM_TYPE => { 206 | model.alarmType = v.parse::().hand_log(|msg| error!("{msg}"))?; 207 | } 208 | &_ => {} 209 | } 210 | } 211 | Ok(model) 212 | } 213 | } 214 | 215 | #[cfg(test)] 216 | mod test { 217 | use poem_openapi::payload::Json; 218 | use poem_openapi::types::ToJSON; 219 | 220 | use crate::general::model::{ResultMessageData, StreamInfo}; 221 | 222 | #[test] 223 | fn t1() { 224 | let m = StreamInfo { 225 | streamId: "streamId".to_string(), 226 | flv: "streamId".to_string(), 227 | m3u8: "streamId".to_string(), 228 | }; 229 | let data = ResultMessageData::build_success(m); 230 | println!("{:#?}", Json(data).to_json_string()); 231 | } 232 | } -------------------------------------------------------------------------------- /session/src/general/runner.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | use std::str::FromStr; 3 | use std::sync::Arc; 4 | use std::time::Duration; 5 | use cron::Schedule; 6 | use common::exception::{GlobalResult, TransError}; 7 | use common::log::error; 8 | use common::tokio::time::sleep; 9 | use crate::gb::handler::cmd; 10 | use crate::general::schedule; 11 | use crate::general::schedule::ScheduleTask; 12 | use crate::storage::{mapper}; 13 | use crate::storage::pics::Pics; 14 | use crate::utils::se_token; 15 | 16 | //启动器完成后触发执行 17 | pub trait Runner { 18 | fn next()-> impl Future + Send; 19 | } 20 | 21 | pub struct PicsRunner; 22 | 23 | impl PicsRunner { 24 | pub async fn snapshot(&self) -> GlobalResult<()> { 25 | let pics_conf = Pics::get_pics_by_conf(); 26 | const COUNT: u32 = 50; 27 | let mut start = 0; 28 | let mut size = COUNT; 29 | while size == COUNT { 30 | let arr = mapper::get_snapshot_dc_by_limit(start, COUNT).await?; 31 | size = arr.len() as u32; 32 | start += COUNT; 33 | 34 | for item in arr { 35 | let (token, session_id) = se_token::build_token_session_id(&item.0, &item.1)?; 36 | let url = format!("{}?token={}", pics_conf.push_url.clone().unwrap(), token); 37 | cmd::CmdControl::snapshot_image(&item.0, &item.1, pics_conf.num, pics_conf.interval, &url, &session_id).await?; 38 | } 39 | //图片上传延迟3秒,缓解带宽瓶颈 40 | sleep(Duration::from_secs(3)).await; 41 | } 42 | 43 | Ok(()) 44 | } 45 | } 46 | 47 | impl ScheduleTask for PicsRunner { 48 | fn do_something(&self) -> Pin + Send + '_>> { 49 | Box::pin(async move { 50 | let _ = self.snapshot().await; 51 | }) 52 | } 53 | } 54 | 55 | impl Runner for PicsRunner { 56 | fn next()-> impl Future + Send { 57 | async { 58 | let pics_conf = Pics::get_pics_by_conf(); 59 | if !pics_conf.enable { 60 | return; 61 | } 62 | let cron = &pics_conf.cron_cycle; 63 | let schedule = Schedule::from_str(cron).unwrap(); // 服务启动:连接代码段时已检查cron表达式 - 正确 64 | let tx = schedule::get_schedule_tx(); 65 | let _ = tx.send((schedule, Arc::new(PicsRunner))).await.hand_log(|msg| error!("{msg}")); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /session/src/general/schedule.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | use std::sync::Arc; 3 | use std::thread; 4 | 5 | use cron::Schedule; 6 | 7 | use common::chrono::{Local}; 8 | use common::log::error; 9 | use common::once_cell::sync::Lazy; 10 | use common::tokio; 11 | use common::tokio::sync::mpsc; 12 | use common::tokio::sync::mpsc::{Receiver, Sender}; 13 | 14 | pub trait ScheduleTask: Send + Sync + 'static { 15 | fn do_something(&self) -> Pin + Send + '_>>; 16 | } 17 | 18 | static SENDER: Lazy)>> = Lazy::new(|| { 19 | let (tx, rx) = mpsc::channel(100); 20 | 21 | thread::Builder::new() 22 | .name("Schedule:Task".to_string()) 23 | .spawn(move || { 24 | let rt = tokio::runtime::Builder::new_multi_thread() 25 | .enable_all() 26 | .build() 27 | .expect("Failed to create Tokio runtime by Schedule:Task"); 28 | 29 | rt.block_on(run_scheduler(rx)); 30 | }) 31 | .expect("Failed to spawn thread"); 32 | tx 33 | }); 34 | 35 | /// 任务调度器 36 | async fn run_scheduler(mut rx: Receiver<(Schedule, Arc)>) { 37 | while let Some((schedule, task)) = rx.recv().await { 38 | tokio::spawn(run_task(schedule, task)); 39 | } 40 | } 41 | 42 | /// 运行任务 43 | async fn run_task(schedule: Schedule, task: Arc) { 44 | loop { 45 | let now = Local::now(); 46 | if let Some(next_time) = schedule.upcoming(Local).next() { 47 | if let Ok(delay) = (next_time - now).to_std() { 48 | tokio::time::sleep(delay).await; 49 | task.do_something().await; 50 | } 51 | } else { 52 | error!("No upcoming schedule time found, exiting task."); 53 | break; 54 | } 55 | } 56 | } 57 | 58 | pub fn get_schedule_tx() -> Sender<(Schedule, Arc)> { 59 | SENDER.clone() 60 | } 61 | 62 | #[cfg(test)] 63 | mod test { 64 | use std::pin::Pin; 65 | use std::str::FromStr; 66 | use std::sync::Arc; 67 | use std::thread::sleep; 68 | use std::time::Duration; 69 | 70 | use cron::Schedule; 71 | 72 | use common::chrono::Local; 73 | 74 | use crate::general::schedule::{get_schedule_tx, ScheduleTask}; 75 | 76 | struct MyTask; 77 | 78 | impl ScheduleTask for MyTask { 79 | fn do_something(&self) -> Pin + Send>> { 80 | Box::pin(async move { 81 | println!("Task executed at {:?}", Local::now()); 82 | }) 83 | } 84 | } 85 | 86 | // #[test] 87 | fn test() { 88 | let schedule = Schedule::from_str("*/5 * * * * *").unwrap(); // 每 5 秒执行一次 89 | let sender = get_schedule_tx(); 90 | 91 | let task = Arc::new(MyTask); 92 | let _ = sender.try_send((schedule, task)); 93 | 94 | sleep(Duration::from_secs(30)); 95 | // 保持主线程运行 96 | // std::thread::park(); 97 | } 98 | } -------------------------------------------------------------------------------- /session/src/main.rs: -------------------------------------------------------------------------------- 1 | // #![allow(warnings)] 2 | use common::daemon; 3 | use crate::app::AppInfo; 4 | pub mod storage; 5 | pub mod gb; 6 | pub mod general; 7 | mod web; 8 | mod service; 9 | mod utils; 10 | mod app; 11 | 12 | fn main() { 13 | daemon::run::(); 14 | } 15 | -------------------------------------------------------------------------------- /session/src/service/biz.rs: -------------------------------------------------------------------------------- 1 | /* 2 | 存储: 3 | 1.原始图片存储 4 | 2.生成缩略图存储 5 | 3.持久化2/3地址索引到数据库建立设备时间关系 6 | */ 7 | 8 | use std::fs; 9 | use std::path::{Path, PathBuf}; 10 | use poem::Body; 11 | use poem_openapi::payload::Binary; 12 | use common::chrono::Local; 13 | use common::exception::{GlobalError, GlobalResult, TransError}; 14 | use common::log::error; 15 | use common::tokio::io::AsyncReadExt; 16 | use crate::storage::entity::{GmvFileInfo, GmvRecord}; 17 | use crate::storage::pics::{Pics}; 18 | use crate::utils::se_token; 19 | 20 | pub async fn upload(data: Binary, session_id: String, file_id: Option, snap_shot_file_id: Option) -> GlobalResult<()> { 21 | let id = snap_shot_file_id.or(file_id); 22 | let (device_id, channel_id) = se_token::split_dc(&session_id)?; 23 | let file_name = match id { 24 | None => { 25 | se_token::build_file_name(&device_id, &channel_id)? 26 | } 27 | Some(id) => { 28 | id 29 | } 30 | }; 31 | 32 | let mut info = GmvFileInfo::default(); 33 | let now = Local::now().naive_local(); 34 | info.biz_time = Some(now); 35 | info.create_time = Some(now); 36 | info.file_type = Some(0); 37 | info.is_del = Some(0); 38 | 39 | info.device_id = device_id; 40 | info.channel_id = channel_id; 41 | info.biz_id = session_id; 42 | let pics_conf = Pics::get_pics_by_conf(); 43 | let storage_path_str = &pics_conf.storage_path; 44 | let relative_path = Path::new(storage_path_str); 45 | let date_str = Local::now().format("%Y%m%d").to_string(); 46 | let final_dir = relative_path.join(date_str); 47 | fs::create_dir_all(&final_dir).hand_log(|msg| error!("create pics dir failed: {msg}"))?; 48 | let abs_final_dir = std::fs::canonicalize(&final_dir).hand_log(|msg| error!("create pics dir failed: {msg}"))?; 49 | info.abs_path = abs_final_dir.to_str().ok_or_else(|| GlobalError::new_sys_error("文件存储路径错误", |msg| error!("{msg}")))?.to_string(); 50 | let dir_path = final_dir.to_str().ok_or_else(|| GlobalError::new_sys_error("文件存储路径错误", |msg| error!("{msg}")))?; 51 | info.dir_path = dir_path.to_string(); 52 | 53 | let file_name = Path::new(&file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string(); 54 | let save_path = final_dir.join(format!("{}.{}", file_name, pics_conf.storage_format.to_ascii_lowercase())); 55 | info.file_name = file_name; 56 | info.file_format = Some(pics_conf.storage_format.to_ascii_lowercase()); 57 | 58 | let mut reader = data.0.into_async_read(); 59 | let mut bytes = Vec::new(); 60 | reader.read_to_end(&mut bytes).await.hand_log(|msg| error!("read pics bytes failed: {msg}"))?; 61 | let img = image::load_from_memory(&bytes).hand_log(|msg| error!("{msg}"))?; 62 | img.save(&save_path).hand_log(|msg| error!("{msg}"))?; 63 | let size = fs::metadata(save_path).hand_log(|msg| error!("{msg}"))?.len(); 64 | info.file_size = Some(size); 65 | GmvFileInfo::insert_gmv_file_info(vec![info]).await?; 66 | Ok(()) 67 | } 68 | 69 | pub async fn rm_file(file_id: i64) -> GlobalResult<()> { 70 | if let Ok(file_info) = GmvFileInfo::query_gmv_file_info_by_id(file_id).await { 71 | let mut file = file_info.file_name.clone(); 72 | if let Some(ext) = &file_info.file_format { 73 | file = format!("{}.{}", file, ext); 74 | } 75 | let path_buf = PathBuf::from(&file_info.dir_path).join(file); 76 | if path_buf.exists() { 77 | fs::remove_file(path_buf).hand_log(|msg| error!("{msg}"))?; 78 | GmvFileInfo::rm_gmv_file_info_by_id(file_id).await?; 79 | GmvRecord::rm_gmv_record_by_biz_id(&file_info.biz_id).await?; 80 | } 81 | } 82 | Ok(()) 83 | } 84 | 85 | mod test { 86 | #[test] 87 | fn test_path() { 88 | // use common::exception::{GlobalError, GlobalResult}; 89 | // use common::log::error; 90 | // use crate::general::DownloadConf; 91 | // use std::{env, fs}; 92 | // use std::path::{Path, PathBuf}; 93 | // let relative_path = Path::new("./storage/pics/"); 94 | // let final_dir = relative_path.join("2025"); 95 | // let abs_final_dir = env::current_dir().unwrap().join(&final_dir); 96 | // println!("{:?}", abs_final_dir); 97 | // fs::create_dir_all(&final_dir).unwrap(); 98 | // let abs_final_dir = std::fs::canonicalize(&final_dir).unwrap(); 99 | // println!("{}", abs_final_dir.to_str().unwrap()); 100 | 101 | 102 | // fn get_path(path_file_name: &String) -> GlobalResult<(String, String, String, String)> { 103 | // let path = Path::new(&path_file_name); 104 | // let dir_path = DownloadConf::get_download_conf().storage_path; 105 | // let biz_id = path.file_stem().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_str().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_string(); 106 | // let extension = path.extension().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_str().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_string(); 107 | // let abs_path = path.parent().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_str().ok_or_else(|| GlobalError::new_sys_error("文件名错误", |msg| error!("{msg}")))?.to_string(); 108 | // Ok((abs_path, dir_path, biz_id, extension)) 109 | // } 110 | } 111 | } -------------------------------------------------------------------------------- /session/src/service/callback.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::net::Ipv4Addr; 3 | use std::time::Duration; 4 | 5 | use common::anyhow::anyhow; 6 | use common::exception::{GlobalError, GlobalResult, TransError}; 7 | use common::exception::GlobalError::SysErr; 8 | use common::log::error; 9 | use common::serde::{Deserialize, Serialize}; 10 | use reqwest::header; 11 | use reqwest::header::HeaderMap; 12 | 13 | use crate::general::AlarmConf; 14 | use crate::general::model::AlarmInfo; 15 | use crate::service::{EXPIRES, ResMsg, StreamRecordInfo}; 16 | 17 | #[allow(dead_code)] 18 | const DROP_SSRC: &str = "/drop/ssrc"; 19 | #[allow(dead_code)] 20 | const LISTEN_SSRC: &str = "/listen/ssrc"; 21 | #[allow(dead_code)] 22 | const START_RECORD: &str = "/start/record"; 23 | #[allow(dead_code)] 24 | const ON_RECORD: &str = "/on/record"; 25 | #[allow(dead_code)] 26 | const START_PLAY: &str = "/start/play"; 27 | #[allow(dead_code)] 28 | const STOP_PLAY: &str = "/stop/play"; 29 | #[allow(dead_code)] 30 | const QUERY_STREAM_COUNT: &str = "/query/stream/count"; 31 | #[allow(dead_code)] 32 | const RTP_MEDIA: &str = "/rtp/media"; 33 | 34 | fn build_uri_header(gmv_token: &String, local_ip: &Ipv4Addr, local_port: &u16) -> GlobalResult<(String, HeaderMap)> { 35 | let uri = format!("http://{}:{}", local_ip.to_string(), local_port); 36 | let mut headers = HeaderMap::new(); 37 | headers.insert("gmv-token", header::HeaderValue::from_str(gmv_token).hand_log(|msg| error!("{msg}"))?); 38 | Ok((uri, headers)) 39 | } 40 | 41 | pub async fn get_stream_count(opt_stream_id: Option<&String>, gmv_token: &String, local_ip: &Ipv4Addr, local_port: &u16) -> GlobalResult { 42 | let (mut uri, headers) = build_uri_header(gmv_token, local_ip, local_port)?; 43 | if let Some(stream_id) = opt_stream_id { 44 | uri = format!("{uri}{QUERY_STREAM_COUNT}?stream_id={stream_id}"); 45 | } else { 46 | uri = format!("{uri}{QUERY_STREAM_COUNT}"); 47 | } 48 | 49 | let res = reqwest::Client::builder() 50 | .timeout(Duration::from_secs(EXPIRES)) 51 | .default_headers(headers) 52 | .build() 53 | .hand_log(|msg| error!("{msg}"))? 54 | .get(&uri) 55 | .send() 56 | .await 57 | .hand_log(|msg| error!("{msg}"))?; 58 | return if res.status().is_success() { 59 | let body = res.json::>() 60 | .await 61 | .hand_log(|msg| error!("{msg}"))?; 62 | if body.code == 200 { 63 | if let Some(data) = body.data { 64 | return Ok(data); 65 | } 66 | } 67 | Err(SysErr(anyhow!("{}",body.msg))).hand_log(|msg| error!("{msg}"))? 68 | } else { 69 | Err(SysErr(anyhow!("{}",res.status().to_string()))).hand_log(|msg| error!("{msg}"))? 70 | }; 71 | } 72 | 73 | #[derive(Clone, Deserialize, Serialize, Debug, Default)] 74 | #[serde(crate = "common::serde")] 75 | pub struct HlsPiece { 76 | //片时间长度 S 77 | pub duration: u8, 78 | pub live: bool, 79 | } 80 | 81 | #[derive(Clone, Serialize, Deserialize, Debug)] 82 | #[serde(crate = "common::serde")] 83 | pub enum Download { 84 | //录像 filename,type 85 | Mp4(String, Option), 86 | //截图 filename 87 | Picture(String, Option), 88 | } 89 | 90 | #[derive(Clone, Serialize, Deserialize, Debug)] 91 | #[serde(crate = "common::serde")] 92 | pub enum Play { 93 | Flv, 94 | Hls(HlsPiece), 95 | FlvHls(HlsPiece), 96 | } 97 | 98 | #[derive(Clone, Serialize, Deserialize, Debug)] 99 | #[serde(crate = "common::serde")] 100 | pub enum MediaAction { 101 | //点播 102 | Play(Play), 103 | //下载 104 | Download(Download), 105 | } 106 | 107 | #[derive(Deserialize, Serialize, Debug)] 108 | #[serde(crate = "common::serde")] 109 | pub struct SsrcLisDto { 110 | pub ssrc: u32, 111 | pub stream_id: String, 112 | //当为None时,默认配置,负数-立马关闭 113 | pub expires: Option, 114 | pub media_action: MediaAction, 115 | // pub flv: bool, 116 | // pub hls: Option, 117 | //MP4录像保存,filename 118 | // pub mp4: Option 119 | } 120 | 121 | pub async fn call_listen_ssrc(stream_id: String, ssrc: &String, gmv_token: &String, local_ip: &Ipv4Addr, local_port: &u16, media_action: MediaAction) -> GlobalResult { 122 | let ssrc = ssrc.parse::().hand_log(|msg| error!("{msg}"))?; 123 | let ssrc_lis_dto = SsrcLisDto { 124 | ssrc, 125 | stream_id, 126 | media_action, 127 | expires: None, 128 | }; 129 | let (mut uri, headers) = build_uri_header(gmv_token, local_ip, local_port)?; 130 | uri = format!("{uri}{LISTEN_SSRC}"); 131 | let res = reqwest::Client::builder() 132 | .timeout(Duration::from_secs(EXPIRES)) 133 | .default_headers(headers) 134 | .build() 135 | .hand_log(|msg| error!("{msg}"))? 136 | .post(&uri) 137 | .json(&ssrc_lis_dto) 138 | .send() 139 | .await 140 | .hand_log(|msg| error!("{msg}"))?; 141 | return if res.status().is_success() { 142 | let body = res.json::>() 143 | .await 144 | .hand_log(|msg| error!("{msg}"))?; 145 | Ok(body.code == 200) 146 | } else { 147 | Err(SysErr(anyhow!("{}",res.status().to_string()))).hand_log(|msg| error!("{msg}"))? 148 | }; 149 | } 150 | 151 | #[derive(Serialize, Deserialize, Debug)] 152 | #[serde(crate = "common::serde")] 153 | struct RtpMap { 154 | ssrc: u32, 155 | map: HashMap, 156 | } 157 | 158 | pub async fn ident_rtp_media_info(ssrc: &String, map: HashMap, gmv_token: &String, local_ip: &Ipv4Addr, local_port: &u16) -> GlobalResult { 159 | let ssrc = ssrc.parse::().hand_log(|msg| error!("{msg}"))?; 160 | let rtp_map = RtpMap { ssrc, map }; 161 | let (uri, headers) = build_uri_header(gmv_token, local_ip, local_port)?; 162 | let res = reqwest::Client::builder() 163 | .timeout(Duration::from_secs(EXPIRES)) 164 | .default_headers(headers) 165 | .build() 166 | .hand_log(|msg| error!("{msg}"))? 167 | .post(format!("{uri}{RTP_MEDIA}")) 168 | .json(&rtp_map) 169 | .send() 170 | .await 171 | .hand_log(|msg| error!("{msg}"))?; 172 | return if res.status().is_success() { 173 | let body = res.json::>() 174 | .await 175 | .hand_log(|msg| error!("{msg}"))?; 176 | Ok(body.code == 200) 177 | } else { 178 | Err(SysErr(anyhow!("{}",res.status().to_string()))).hand_log(|msg| error!("{msg}"))? 179 | }; 180 | } 181 | 182 | 183 | pub async fn get_stream_record_info_by_biz_id(stream_id: &String, gmv_token: &String, local_ip: &Ipv4Addr, local_port: &u16) -> GlobalResult { 184 | let (uri, headers) = build_uri_header(gmv_token, local_ip, local_port)?; 185 | let res = reqwest::Client::builder() 186 | .timeout(Duration::from_secs(EXPIRES)) 187 | .default_headers(headers) 188 | .build() 189 | .hand_log(|msg| error!("{msg}"))? 190 | .get(format!("{}{}?stream_id={}", uri, ON_RECORD, stream_id)) 191 | .send() 192 | .await 193 | .hand_log(|msg| error!("{msg}"))?; 194 | return if res.status().is_success() { 195 | let body = res.json::>() 196 | .await 197 | .hand_log(|msg| error!("{msg}"))?; 198 | body.data.ok_or_else(|| GlobalError::new_sys_error("record info 为空", |msg| error!("{msg}"))) 199 | } else { 200 | Err(SysErr(anyhow!("{}",res.status().to_string()))).hand_log(|msg| error!("{msg}"))? 201 | }; 202 | } 203 | 204 | pub async fn call_alarm_info(info: &AlarmInfo) -> GlobalResult { 205 | let conf = AlarmConf::get_alarm_conf(); 206 | let res = reqwest::Client::builder() 207 | .timeout(Duration::from_secs(EXPIRES)) 208 | .build() 209 | .hand_log(|msg| error!("{msg}"))? 210 | .post(conf.push_url.as_ref().unwrap()) 211 | .json(info) 212 | .send() 213 | .await 214 | .hand_log(|msg| error!("{msg}"))?; 215 | return if res.status().is_success() { 216 | let body = res.json::>() 217 | .await 218 | .hand_log(|msg| error!("{msg}"))?; 219 | Ok(body.code == 200) 220 | } else { 221 | Err(SysErr(anyhow!("{}",res.status().to_string()))).hand_log(|msg| error!("{msg}"))? 222 | }; 223 | } 224 | 225 | -------------------------------------------------------------------------------- /session/src/service/mod.rs: -------------------------------------------------------------------------------- 1 | use poem_openapi::{Enum, Object}; 2 | use common::serde::{Deserialize, Serialize}; 3 | 4 | use common::constructor::{Get, New}; 5 | 6 | pub mod handler; 7 | pub mod callback; 8 | pub mod biz; 9 | 10 | pub const EXPIRES: u64 = 8; 11 | pub const RELOAD_EXPIRES: u64 = 2; 12 | 13 | #[derive(Clone, Copy, Serialize, Deserialize, Debug, Enum)] 14 | #[serde(crate = "common::serde")] 15 | pub enum PlayType { 16 | Flv, 17 | Hls, 18 | } 19 | 20 | #[derive(Serialize, Deserialize, Debug, Object)] 21 | #[serde(crate = "common::serde")] 22 | pub struct ResMsg { 23 | code: u16, 24 | msg: String, 25 | data: Option, 26 | } 27 | 28 | #[derive(New, Serialize, Object, Deserialize, Get, Debug)] 29 | #[serde(crate = "common::serde")] 30 | pub struct StreamState { 31 | base_stream_info: BaseStreamInfo, 32 | user_count: u32, 33 | // record_name: Option, 34 | } 35 | 36 | #[derive(New, Serialize, Object, Deserialize, Get, Debug)] 37 | #[serde(crate = "common::serde")] 38 | pub struct BaseStreamInfo { 39 | rtp_info: RtpInfo, 40 | stream_id: String, 41 | in_time: u32, 42 | } 43 | 44 | #[derive(New, Serialize, Get, Deserialize, Object, Debug)] 45 | #[serde(crate = "common::serde")] 46 | pub struct NetSource { 47 | remote_addr: String, 48 | protocol: String, 49 | } 50 | 51 | #[derive(New, Object, Serialize, Deserialize, Get, Debug)] 52 | #[serde(crate = "common::serde")] 53 | pub struct RtpInfo { 54 | ssrc: u32, 55 | //媒体流源地址,tcp/udp 56 | origin_trans: Option, 57 | // //tcp/udp 58 | // protocol: Option, 59 | // //媒体流源地址 60 | // origin_addr: Option, 61 | server_name: String, 62 | } 63 | 64 | #[derive(New, Object, Serialize, Deserialize, Get, Debug)] 65 | #[serde(crate = "common::serde")] 66 | pub struct StreamPlayInfo { 67 | base_stream_info: BaseStreamInfo, 68 | remote_addr: String, 69 | token: String, 70 | play_type: PlayType, 71 | //当前观看人数 72 | user_count: u32, 73 | } 74 | 75 | #[derive(Object, Serialize, Deserialize, Debug)] 76 | #[serde(crate = "common::serde")] 77 | pub struct StreamRecordInfo { 78 | pub file_name: Option, 79 | //单位kb,录制完成时统计文件大小 80 | pub file_size: Option, 81 | //媒体流原始时间,方便计算进度 82 | pub timestamp: u32, 83 | //每秒录制字节数 84 | pub bytes_sec: usize, 85 | } 86 | -------------------------------------------------------------------------------- /session/src/storage/mapper.rs: -------------------------------------------------------------------------------- 1 | use common::chrono::NaiveDateTime; 2 | use common::dbx::mysqlx::get_conn_by_pool; 3 | use common::exception::{GlobalResult, TransError}; 4 | use common::log::error; 5 | use common::sqlx; 6 | 7 | pub async fn get_device_channel_status(device_id: &String, channel_id: &String) -> GlobalResult> { 8 | let pool = get_conn_by_pool()?; 9 | let res: Option<(String,)> = sqlx::query_as( 10 | "SELECT IFNULL(c.`STATUS`,'ONLY') FROM GMV_DEVICE d LEFT JOIN GMV_DEVICE_CHANNEL c on d.DEVICE_ID=c.DEVICE_ID and c.CHANNEL_ID=? WHERE d.DEVICE_ID=?" 11 | ) 12 | .bind(channel_id) 13 | .bind(device_id) 14 | .fetch_optional(pool).await.hand_log(|msg| error!("{msg}"))?; 15 | Ok(res.map(|(v, )| v)) 16 | } 17 | 18 | pub async fn get_device_status_info(device_id: &String) -> GlobalResult> { 19 | let pool = get_conn_by_pool()?; 20 | let res = sqlx::query_as::<_, (u8, u8, u32, NaiveDateTime, u8)>( 21 | "SELECT o.HEARTBEAT_SEC,o.`STATUS`,d.REGISTER_EXPIRES,d.REGISTER_TIME,d.`STATUS` FROM GMV_OAUTH o INNER JOIN GMV_DEVICE d ON o.DEVICE_ID = d.DEVICE_ID where d.device_id=?", 22 | ).bind(device_id).fetch_optional(pool).await.hand_log(|msg| error!("{msg}"))?; 23 | Ok(res) 24 | } 25 | 26 | pub async fn get_snapshot_dc_by_limit(start: u32, count: u32) -> GlobalResult> { 27 | let pool = get_conn_by_pool()?; 28 | let script = r" 29 | SELECT c.DEVICE_ID,c.CHANNEL_ID FROM GMV_OAUTH a 30 | INNER JOIN GMV_DEVICE b ON a.DEVICE_ID = b.DEVICE_ID 31 | INNER JOIN GMV_DEVICE_CHANNEL c ON a.DEVICE_ID=c.DEVICE_ID 32 | WHERE 33 | a.DEL = 0 34 | AND b.`status` = 1 35 | AND DATE_ADD(b.register_time,INTERVAL b.register_expires SECOND)>NOW() 36 | AND LEFT(b.GB_VERSION, 1) >= '3' 37 | AND c.PARENT_ID=c.DEVICE_ID 38 | AND !(c.`status` = 'OFF' OR c.`status` = 'OFFLINE' ) 39 | ORDER BY c.DEVICE_ID,c.CHANNEL_ID limit ?,?"; 40 | let dcs: Vec<(String, String)> = sqlx::query_as(script).bind(start).bind(count).fetch_all(pool).await.hand_log(|msg| error!("{msg}"))?; 41 | Ok(dcs) 42 | } 43 | 44 | #[cfg(test)] 45 | #[allow(dead_code, unused_imports)] 46 | mod test { 47 | use common::cfg_lib::conf::init_cfg; 48 | use common::dbx::mysqlx; 49 | use common::tokio; 50 | use super::*; 51 | 52 | // #[tokio::test] 53 | async fn test_get_snapshot_dc_by_limit() { 54 | init(); 55 | let result = get_snapshot_dc_by_limit(0, 5).await; 56 | println!("{:?}", result); 57 | } 58 | 59 | // #[tokio::test] 60 | async fn test_get_device_channel_status() { 61 | init(); 62 | let result = get_device_channel_status(&"34020000001110000001".to_string(), &"34020000001320000180".to_string()).await; 63 | println!("{:?}", result); 64 | } 65 | 66 | // #[tokio::test] 67 | async fn test_get_device_status_info() { 68 | init(); 69 | let status_info = get_device_status_info(&"34020000001110000001".to_string()).await; 70 | println!("{:?}", status_info); 71 | } 72 | 73 | fn init() { 74 | init_cfg("/home/ubuntu20/code/rs/mv/github/epimore/gmv/session/config.yml".to_string()); 75 | let _ = mysqlx::init_conn_pool(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /session/src/storage/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod mapper; 2 | pub mod entity; 3 | pub mod pics; -------------------------------------------------------------------------------- /session/src/storage/pics.rs: -------------------------------------------------------------------------------- 1 | use std::{fs}; 2 | use std::str::FromStr; 3 | use cron::Schedule; 4 | use url::Url; 5 | 6 | use common::cfg_lib::conf; 7 | use common::cfg_lib::conf::{CheckFromConf, FieldCheckError}; 8 | use common::constructor::{Get}; 9 | use common::once_cell::sync::Lazy; 10 | use common::serde::Deserialize; 11 | use common::serde_default; 12 | 13 | #[derive(Debug, Get, Deserialize)] 14 | #[serde(crate = "common::serde")] 15 | #[conf(prefix = "server.pics", check)] 16 | pub struct Pics { 17 | #[serde(default = "default_enable")] 18 | pub enable: bool, 19 | pub push_url: Option, 20 | #[serde(default = "default_cron_cycle")] 21 | pub cron_cycle: String, 22 | #[serde(default = "default_num")] 23 | pub num: u8, 24 | #[serde(default = "default_interval")] 25 | pub interval: u8, 26 | #[serde(default = "default_storage_path")] 27 | pub storage_path: String, 28 | #[serde(default = "default_storage_format")] 29 | pub storage_format: String, 30 | } 31 | serde_default!(default_enable, bool, false); 32 | serde_default!(default_cron_cycle, String, String::from("0 */5 * * * *")); 33 | serde_default!(default_num, u8, 1); 34 | serde_default!(default_interval, u8, 1); 35 | serde_default!(default_storage_path, String, "./pics/raw".to_string()); 36 | serde_default!(default_storage_format, String, "jpeg".to_string()); 37 | 38 | impl CheckFromConf for Pics { 39 | fn _field_check(&self) -> Result<(), FieldCheckError> { 40 | let pics: Pics = Pics::conf(); 41 | if pics.enable { 42 | let uri = self.push_url.as_ref().ok_or(FieldCheckError::BizError("push_url is required".to_string()))?; 43 | Url::parse(uri).map_err(|e| FieldCheckError::BizError(format!("Invalid push_url: {}", e.to_string())))?; 44 | } 45 | match &*pics.storage_format.to_ascii_lowercase() { 46 | "avif" | "bmp" | "farbfeld" | "gif" | "hdr" | "ico" | "jpeg" | "exr" | "png" | "pnm" | "qoi" | "tga" | "tiff" | "webp" => {} 47 | _ => { 48 | return Err(FieldCheckError::BizError("storage_format must be in [avif,bmp,farbfeld,gif,hdr,ico,jpeg,exr,png,pnm,qoi,tga,tiff,webp]".to_string())); 49 | } 50 | } 51 | Schedule::from_str(&pics.cron_cycle).map_err(|e| FieldCheckError::BizError(format!("Invalid cron expression: {}", e.to_string())))?; 52 | fs::create_dir_all(&pics.storage_path).map_err(|e| FieldCheckError::BizError(format!("create raw_path dir failed: {}", e.to_string())))?; 53 | Ok(()) 54 | } 55 | } 56 | 57 | impl Pics { 58 | pub fn get_pics_by_conf() -> &'static Self { 59 | static INSTANCE: Lazy = Lazy::new(|| { 60 | let pics: Pics = Pics::conf(); 61 | pics 62 | }); 63 | &INSTANCE 64 | } 65 | } 66 | 67 | //file_name:data 68 | // #[derive(New)] 69 | // pub struct ImageInfo { 70 | // session_id: String, 71 | // image_type: Option, 72 | // file_name: String, 73 | // data: Vec, 74 | // } 75 | // 76 | // impl ImageInfo { 77 | // pub fn sender() -> Sender { 78 | // static SENDER: Lazy> = Lazy::new(|| { 79 | // let (tx, rx) = crossbeam_channel::bounded(1000); 80 | // thread::Builder::new().name("Shared:rw".to_string()).spawn(move || { 81 | // let r = rayon::ThreadPoolBuilder::new().build().expect("pics: rayon init failed"); 82 | // r.scope(|s| { 83 | // s.spawn(move |_| { 84 | // rx.iter().for_each(|image_info: ImageInfo| { 85 | // let _ = image_info.hand_pic(); 86 | // }) 87 | // }) 88 | // }) 89 | // }).expect("Storage:pic background thread create failed"); 90 | // tx 91 | // }); 92 | // SENDER.clone() 93 | // } 94 | // 95 | // fn hand_pic(self) -> GlobalResult<()> { 96 | // let mut info = GmvFileInfo::default(); 97 | // let now = Local::now().naive_local(); 98 | // info.biz_time = Some(now); 99 | // info.create_time = Some(now); 100 | // info.file_type = Some(0); 101 | // 102 | // let (device_id, channel_id) = se_token::split_dc(&self.session_id)?; 103 | // info.device_id = device_id; 104 | // info.channel_id = channel_id; 105 | // info.biz_id = self.session_id; 106 | // let pics_conf = Pics::get_pics_by_conf(); 107 | // let storage_path_str = &pics_conf.storage_path; 108 | // let relative_path = Path::new(storage_path_str); 109 | // let absolute_path = fs::canonicalize(relative_path).hand_log(|msg| error!("{msg}"))?; 110 | // let date_str = Local::now().format("%Y%m%d").to_string(); 111 | // let final_dir = absolute_path.join(date_str); 112 | // let dir_path = final_dir.to_str().ok_or_else(|| GlobalError::new_sys_error("文件存储路径错误", |msg| error!("{msg}")))?; 113 | // info.dir_path = dir_path.to_string(); 114 | // 115 | // let file_name = Path::new(&self.file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string(); 116 | // info.file_name = file_name; 117 | // let save_path = final_dir.join(format!("{}.{}", self.file_name, pics_conf.storage_format)); 118 | // info.file_format = Some(pics_conf.storage_format.clone()); 119 | // let img = image::load_from_memory(&self.data).hand_log(|msg| error!("{msg}"))?; 120 | // img.save(&save_path).hand_log(|msg| error!("{msg}"))?; 121 | // let size = fs::metadata(save_path).hand_log(|msg| error!("{msg}"))?.len(); 122 | // info.file_size = Some(size); 123 | // Ok(()) 124 | // } 125 | // 126 | // fn split_file_name(file_path: &PathBuf) -> (String, Option>) { 127 | // // let path = Path::new(file_name); 128 | // let name = file_path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string(); 129 | // let ext = file_path.extension().map(|ext| ext.to_str().map(|ext| ext.to_string())); 130 | // (name, ext) 131 | // } 132 | // } 133 | 134 | // fn print_diff(index: u8, last: i64) -> i64 { 135 | // let current = Local::now().timestamp_millis(); 136 | // println!("{} : {}", index, current - last); 137 | // current 138 | // } 139 | 140 | 141 | #[cfg(test)] 142 | mod test { 143 | use common::chrono::Local; 144 | use image::ImageFormat; 145 | use image::ImageFormat::Jpeg; 146 | use common::cfg_lib::conf::init_cfg; 147 | use crate::storage::pics::Pics; 148 | 149 | #[test] 150 | fn test() { 151 | let content_type = "image/jpeg"; 152 | let format = content_type.split_once('/').map(|(_, fmt)| fmt).unwrap_or(""); 153 | println!("格式: {}", format); 154 | assert_eq!("jpeg", format); 155 | let option = ImageFormat::from_extension(format); 156 | println!("{:?}", option); 157 | assert_eq!(Some(Jpeg), option); 158 | let date_str = Local::now().format("%Y%m%d").to_string(); 159 | println!("{}", date_str); 160 | } 161 | 162 | // #[test] 163 | fn test_pics_conf() { 164 | init_cfg("config.yml".to_string()); 165 | let conf = Pics::get_pics_by_conf(); 166 | println!("{:?}", conf); 167 | } 168 | } -------------------------------------------------------------------------------- /session/src/utils/id_builder.rs: -------------------------------------------------------------------------------- 1 | use std::time::{SystemTime, UNIX_EPOCH}; 2 | use common::log::error; 3 | use common::exception::{GlobalError, GlobalResult}; 4 | use common::utils::dig62; 5 | use crate::storage::entity::GmvOauth; 6 | use crate::storage::mapper; 7 | 8 | //生成stream_id,参数由调用方校验,简单对称加密算法 9 | // device_id 20位十进制纯数字 10 | // channel_id 20位十进制纯数字 11 | // ssrc 10位十进制纯数字 12 | pub fn en_stream_id(device_id: &str, channel_id: &str, ssrc: &str) -> GlobalResult { 13 | //使用纳秒的后两位生成填充字符串,并取7个字符 14 | let now = SystemTime::now(); 15 | let since_the_epoch = now.duration_since(UNIX_EPOCH) 16 | .expect("Time went backwards"); 17 | let secs = since_the_epoch.as_millis(); 18 | let ori_key = format!("{device_id}{channel_id}{ssrc}{secs}"); 19 | dig62::en(&ori_key) 20 | } 21 | 22 | //返回(device_id,channel_id,ssrc) 23 | pub fn de_stream_id(stream_id: &str) -> GlobalResult<(String, String, String)> { 24 | let ori_str = dig62::de(stream_id)?; 25 | Ok((ori_str[0..20].to_string(), ori_str[20..40].to_string(), ori_str[40..50].to_string())) 26 | } 27 | 28 | //为十进制整数字符串,表示SSRC值。格式如下:dddddddddd。其中,第1位为历史或实时 29 | // 媒体流的标识位,0为实时,1为历史;第2位至第6位取20位SIP监控域ID之中的4到8位作为域标 30 | // 识,例如“13010000002000000001”中取数字“10000”;第7位至第10位作为域内媒体流标识,是一个与 31 | // 当前域内产生的媒体流SSRC值后4位不重复的四位十进制整数 32 | // 返回(ssrc,stream_id) 33 | pub async fn build_ssrc_stream_id(device_id: &String, channel_id: &String, num_ssrc: u16, live: bool) -> GlobalResult<(String, String)> { 34 | let gmv_oauth = GmvOauth::read_gmv_oauth_by_device_id(device_id).await? 35 | .ok_or_else(|| GlobalError::new_biz_error(1100, "设备不存在", |msg| error!("{msg}")))?; 36 | //直播:需校验摄像头是否在线;回放:录像机在线即可 37 | let mut front_live_or_back = 1; 38 | if live { 39 | let channel_status = mapper::get_device_channel_status(device_id, channel_id).await? 40 | .ok_or_else(|| GlobalError::new_biz_error(1100, "未知设备", |msg| error!("{msg}")))?; 41 | match &channel_status.to_ascii_uppercase()[..] { 42 | "OK" | "ON" | "ONLINE" | "ONLY" | "" => {} 43 | _ => { 44 | return Err(GlobalError::new_biz_error(1000, "设备已离线", |msg| error!("{msg}"))); 45 | } 46 | } 47 | front_live_or_back = 0; 48 | } 49 | let domain_id = gmv_oauth.get_domain_id(); 50 | let middle_domain_mark = &domain_id[4..=8]; 51 | let ssrc = format!("{front_live_or_back}{middle_domain_mark}{num_ssrc:04}"); 52 | let stream_id = en_stream_id(device_id, channel_id, &ssrc)?; 53 | Ok((ssrc, stream_id)) 54 | } 55 | 56 | #[test] 57 | fn test1() { 58 | let device_id = "34020000001110000001"; 59 | let channel_id = "34020000001320000101"; 60 | let ssrc = "1100000001"; 61 | let stream_id = en_stream_id(device_id, channel_id, ssrc).unwrap(); 62 | println!("stream_id = {}", &stream_id); 63 | let (d_d_id, d_c_id, d_ssrc) = de_stream_id(&stream_id).unwrap(); 64 | assert_eq!(device_id, &d_d_id[..]); 65 | assert_eq!(channel_id, &d_c_id[..]); 66 | assert_eq!(ssrc, &d_ssrc[..]); 67 | } 68 | 69 | #[test] 70 | fn test_ssrc_to_ssrc_num() { 71 | let ssrc1: u32 = 1100009001; 72 | let ssrc_num1 = (ssrc1 % 10000) as u16; 73 | assert_eq!(ssrc_num1, 9001); 74 | let ssrc2: u32 = 1100000001; 75 | let ssrc_num2 = (ssrc2 % 10000) as u16; 76 | assert_eq!(ssrc_num2, 1); 77 | let ssrc3: u32 = 1100000801; 78 | let ssrc_num3 = (ssrc3 % 10000) as u16; 79 | assert_eq!(ssrc_num3, 801); 80 | let ssrc4: u32 = 1100019999; 81 | let ssrc_num4 = (ssrc4 % 10000) as u16; 82 | assert_eq!(ssrc_num4, 9999) 83 | } -------------------------------------------------------------------------------- /session/src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod id_builder; 2 | pub mod se_token; -------------------------------------------------------------------------------- /session/src/utils/se_token.rs: -------------------------------------------------------------------------------- 1 | use std::time::{SystemTime, UNIX_EPOCH}; 2 | use common::exception::{GlobalError, GlobalResult}; 3 | use common::log::error; 4 | use common::utils::{dig62, crypto}; 5 | 6 | const KEY: &str = "GMV:SESSION v1.0"; 7 | 8 | pub fn build_file_name(device_id: &str, channel_id: &str) -> GlobalResult { 9 | let now = SystemTime::now(); 10 | let since_the_epoch = now.duration_since(UNIX_EPOCH) 11 | .expect("Time went backwards"); 12 | let mils = since_the_epoch.as_millis(); 13 | let text = format!("{}{}{}", device_id, channel_id, mils); 14 | dig62::en(&text) 15 | } 16 | 17 | pub fn build_token_session_id(device_id: &str, channel_id: &str) -> GlobalResult<(String, String)> { 18 | let now = SystemTime::now(); 19 | let since_the_epoch = now.duration_since(UNIX_EPOCH) 20 | .expect("Time went backwards"); 21 | let mils = since_the_epoch.as_millis(); 22 | let text = format!("{}{}{}", device_id, channel_id, mils); 23 | let session_id = dig62::en(&text)?; 24 | let input = format!("{}@{}", KEY, session_id); 25 | let token = crypto::generate_token(&input); 26 | Ok((token, session_id)) 27 | } 28 | 29 | //返回(device_id, channel_id) 30 | pub fn split_dc(session_id: &str) -> GlobalResult<(String, String)> { 31 | let dcs = dig62::de(session_id)?; 32 | Ok((dcs[0..20].to_string(), dcs[20..40].to_string())) 33 | } 34 | 35 | pub fn check_token(session_id: &str, token: &str) -> GlobalResult<()> { 36 | let input = format!("{}@{}", KEY, session_id); 37 | let r_token = crypto::generate_token(&input); 38 | if r_token.eq(token) { 39 | return Ok(()); 40 | } 41 | Err(GlobalError::new_sys_error("Invalid token", |msg| error!("{msg}"))) 42 | } 43 | 44 | #[cfg(test)] 45 | mod test { 46 | #[test] 47 | fn t1() { 48 | let device_id = "34020000001110000009"; 49 | let channel_id = "34020000001320000101"; 50 | let (token, session_id) = super::build_token_session_id(device_id, channel_id).unwrap(); 51 | println!("token: {}", token); 52 | println!("session_id: {}", session_id); 53 | let (dc_device_id, dc_channel_id) = super::split_dc(&session_id).unwrap(); 54 | println!("dc_device_id: {}", dc_device_id); 55 | println!("dc_channel_id: {}", dc_channel_id); 56 | super::check_token(&session_id, &token).unwrap(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /session/src/web/api.rs: -------------------------------------------------------------------------------- 1 | use common::log::{error, info}; 2 | use poem_openapi::OpenApi; 3 | use poem_openapi::param::Header; 4 | use poem_openapi::payload::{Json}; 5 | 6 | use common::exception::{GlobalError}; 7 | 8 | use crate::general::model::*; 9 | use crate::service::{biz, handler, StreamRecordInfo}; 10 | use crate::web::SingleParam; 11 | 12 | pub struct RestApi; 13 | 14 | #[OpenApi(prefix_path = "/api")] 15 | impl RestApi { 16 | #[allow(non_snake_case)] 17 | #[oai(path = "/play/live/stream", method = "post")] 18 | /// 点播监控实时画面 transMode 默认0 udp 模式, 1 tcp 被动模式,2 tcp 主动模式 19 | async fn play_live(&self, live: Json, #[oai( 20 | name = "gmv-token" 21 | )] token: Header) -> Json> { 22 | let header = token.0; 23 | let live_model = live.0; 24 | info!("play_live:header = {:?},body = {:?}", &header,&live_model); 25 | match handler::play_live(live_model, header).await { 26 | Ok(data) => { Json(ResultMessageData::build_success(data)) } 27 | Err(err) => { 28 | error!("{}",err.to_string()); 29 | match err { 30 | GlobalError::BizErr(e) => { 31 | Json(ResultMessageData::build_failure_msg(e.msg)) 32 | } 33 | GlobalError::SysErr(_e) => { 34 | Json(ResultMessageData::build_failure()) 35 | } 36 | } 37 | } 38 | } 39 | } 40 | 41 | #[allow(non_snake_case)] 42 | #[oai(path = "/play/back/stream", method = "post")] 43 | /// 点播监控历史画面 transMode 默认0 udp 模式, 1 tcp 被动模式,2 tcp 主动模式 44 | async fn play_back(&self, back: Json, #[oai( 45 | name = "gmv-token" 46 | )] token: Header) -> Json> { 47 | let header = token.0; 48 | let back_model = back.0; 49 | info!("back_model:header = {:?},body = {:?}", &header,&back_model); 50 | match handler::play_back(back_model, header).await { 51 | Ok(data) => { Json(ResultMessageData::build_success(data)) } 52 | Err(err) => { 53 | error!("{}",err.to_string()); 54 | match err { 55 | GlobalError::BizErr(e) => { 56 | Json(ResultMessageData::build_failure_msg(e.msg)) 57 | } 58 | GlobalError::SysErr(_e) => { 59 | Json(ResultMessageData::build_failure()) 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | #[allow(non_snake_case)] 67 | #[oai(path = "/play/back/seek", method = "post")] 68 | /// 拖动播放录像 seek 拖动秒 [1-86400] 69 | async fn playback_seek(&self, 70 | seek: Json, 71 | #[oai(name = "gmv-token")] token: Header) 72 | -> Json> { 73 | let header = token.0; 74 | let seek_model = seek.0; 75 | info!("back-seek:header = {:?},body = {:?}", &header,&seek_model); 76 | match handler::seek(seek_model, header).await { 77 | Err(err) => { 78 | let err_msg = format!("拖动失败;{}", err); 79 | error!("{}",&err_msg); 80 | Json(ResultMessageData::build_failure_msg(err_msg)) 81 | } 82 | Ok(_) => { Json(ResultMessageData::build_success(true)) } 83 | } 84 | } 85 | #[allow(non_snake_case)] 86 | #[oai(path = "/play/back/speed", method = "post")] 87 | /// 倍速播放历史视频 speed [1,2,4] 88 | async fn playback_speed(&self, 89 | speed: Json, 90 | #[oai(name = "gmv-token")] token: Header) 91 | -> Json> { 92 | let header = token.0; 93 | let speed_model = speed.0; 94 | info!("back-speed:header = {:?},body = {:?}", &header,&speed_model); 95 | match handler::speed(speed_model, header).await { 96 | Err(err) => { 97 | let err_msg = format!("倍速播放失败;{}", err); 98 | error!("{}",&err_msg); 99 | Json(ResultMessageData::build_failure_msg(err_msg)) 100 | } 101 | Ok(_) => { Json(ResultMessageData::build_success(true)) } 102 | } 103 | } 104 | 105 | #[allow(non_snake_case)] 106 | #[oai(path = "/control/ptz", method = "post")] 107 | /// 云台控制 108 | async fn control_ptz(&self, 109 | ptz: Json, 110 | #[oai(name = "gmv-token")] token: Header) 111 | -> Json> { 112 | let header = token.0; 113 | let ptz_model = ptz.0; 114 | info!("control_ptz:header = {:?},body = {:?}", &header,&ptz_model); 115 | match handler::ptz(ptz_model, header).await { 116 | Err(err) => { 117 | let err_msg = format!("云台控制失败;{}", err); 118 | error!("{}",&err_msg); 119 | Json(ResultMessageData::build_failure_msg(err_msg)) 120 | } 121 | Ok(_) => { Json(ResultMessageData::build_success(true)) } 122 | } 123 | } 124 | 125 | #[allow(non_snake_case)] 126 | #[oai(path = "/download/mp4", method = "post")] 127 | /// 开始录像 128 | async fn download(&self, back: Json, 129 | #[oai(name = "gmv-token")] token: Header) 130 | -> Json> { 131 | let header = token.0; 132 | let back_model = back.0; 133 | info!("download:header = {:?},body = {:?}", &header,&back_model); 134 | match handler::download(back_model, header).await { 135 | Ok(stream_id) => { Json(ResultMessageData::build_success(stream_id)) } 136 | Err(err) => { 137 | error!("{}",err.to_string()); 138 | match err { 139 | GlobalError::BizErr(e) => { 140 | Json(ResultMessageData::build_failure_msg(e.msg)) 141 | } 142 | GlobalError::SysErr(_e) => { 143 | Json(ResultMessageData::build_failure()) 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | #[allow(non_snake_case)] 151 | #[oai(path = "/download/stop", method = "post")] 152 | /// 提前终止云端录像任务 153 | async fn download_stop(&self, 154 | param_mode: Json>, 155 | #[oai( 156 | name = "gmv-token" 157 | )] token: Header) -> Json> { 158 | let header = token.0; 159 | let param_mode = param_mode.0; 160 | info!("teardown:header = {:?},body = {:?}", &header,¶m_mode); 161 | match handler::download_stop(param_mode.param, header).await { 162 | Err(err) => { 163 | error!("终止失败;{}",err); 164 | Json(ResultMessageData::build_failure()) 165 | } 166 | Ok(_info) => { Json(ResultMessageData::build_success(true)) } 167 | } 168 | } 169 | 170 | #[allow(non_snake_case)] 171 | #[oai(path = "/downing/info", method = "post")] 172 | /// 查看进行中录像信息 173 | async fn down_info(&self, 174 | stream_node: Json, 175 | #[oai( 176 | name = "gmv-token" 177 | )] token: Header) -> Json> { 178 | let header = token.0; 179 | let stream_node = stream_node.0; 180 | let stream_id = stream_node.stream_id; 181 | let stream_server = stream_node.stream_server; 182 | info!("down_info:header = {:?},body = {:?},{:?}", &header,&stream_id,&stream_server); 183 | match handler::download_info_by_stream_id(stream_id, stream_server, header).await { 184 | Err(err) => { 185 | error!("查看录像信息失败;{}",err); 186 | Json(ResultMessageData::build_failure()) 187 | } 188 | Ok(info) => { Json(ResultMessageData::build_success(info)) } 189 | } 190 | } 191 | 192 | #[allow(non_snake_case)] 193 | #[oai(path = "/rm/file", method = "post")] 194 | /// 物理删除文件 195 | async fn rm_file(&self, 196 | param_mode: Json>, 197 | #[oai( 198 | name = "gmv-token" 199 | )] token: Header) -> Json> { 200 | let header = token.0; 201 | let param_mode = param_mode.0; 202 | info!("rm_file:header = {:?},body = {:?}", &header,¶m_mode); 203 | match biz::rm_file(param_mode.param).await { 204 | Err(err) => { 205 | error!("删除失败;{}",err); 206 | Json(ResultMessageData::build_failure()) 207 | } 208 | Ok(_) => { Json(ResultMessageData::build_success(true)) } 209 | } 210 | } 211 | } -------------------------------------------------------------------------------- /session/src/web/hook.rs: -------------------------------------------------------------------------------- 1 | use common::log::info; 2 | use poem_openapi::OpenApi; 3 | use poem_openapi::payload::{Json}; 4 | use crate::general::model::{ResultMessageData}; 5 | use crate::service::{BaseStreamInfo, handler, StreamPlayInfo, StreamState, StreamRecordInfo}; 6 | 7 | 8 | ////callback uri start 9 | // //ssrc流注册 10 | // pub const STREAM_IN: &str = "/stream/in"; 11 | // //ssrc流无操作 12 | // pub const STREAM_IDLE: &str = "/stream/idle"; 13 | // //播放流 14 | // pub const ON_PLAY: &str = "/on/play"; 15 | // //关闭播放 16 | // pub const OFF_PLAY: &str = "/off/play"; 17 | // //录制结束 18 | // pub const END_RECORD: &str = "/end/record"; 19 | // //等待流超时 20 | // pub const STREAM_INPUT_TIMEOUT: &str = "/stream/input/timeout"; 21 | pub struct HookApi; 22 | 23 | #[OpenApi(prefix_path = "/hook")] 24 | impl HookApi { 25 | ///流媒体监听ssrc:接收到流输入,发送一次流注册事件;信令回调/api/play/xxx返回播放流信息 26 | #[oai(path = "/stream/in", method = "post")] 27 | async fn stream_in(&self, base_stream_info: Json) -> Json> { 28 | let info = base_stream_info.0; 29 | info!("stream_in = {:?}", &info); 30 | handler::stream_in(info).await; 31 | Json(ResultMessageData::build_success_none()) 32 | } 33 | ///流媒体监听ssrc:等待流8秒,超时未接收到;发送一次接收流超时事件;信令下发设备取消推流,并清理缓存会话; 34 | /// 【流注册等待超时,信令回调/api/play/xxx返回响应超时信息】 35 | #[oai(path = "/stream/input/timeout", method = "post")] 36 | async fn stream_input_timeout(&self, stream_state: Json) -> Json> { 37 | let info = stream_state.0; 38 | info!("stream_input_timeout = {:?}", &info); 39 | handler::stream_input_timeout(info); 40 | Json(ResultMessageData::build_success_none()) 41 | } 42 | ///流媒体监测到用户点播流:发送一次用户点播流事件,用于鉴权 43 | #[oai(path = "/on/play", method = "post")] 44 | async fn on_play(&self, stream_play_info: Json) -> Json> { 45 | let info = stream_play_info.0; 46 | info!("on_play = {:?}", &info); 47 | Json(ResultMessageData::build_success(handler::on_play(info))) 48 | } 49 | ///流媒体监测到用户断开点播流:发送一次用户关闭流事件: 50 | #[oai(path = "/off/play", method = "post")] 51 | async fn off_play(&self, stream_play_info: Json) -> Json> { 52 | let info = stream_play_info.0; 53 | info!("off_play = {:?}", &info); 54 | Json(ResultMessageData::build_success(handler::off_play(info).await)) 55 | } 56 | ///流媒体监测到无人连接媒体流:发送一次流空闲事件【配置为不关闭流,则不发送】:信令下发设备关闭推流,并清理缓存会话 57 | #[oai(path = "/stream/idle", method = "post")] 58 | async fn stream_idle(&self, stream_play_info: Json) -> Json> { 59 | let info = stream_play_info.0; 60 | info!("stream_idle = {:?}", &info); 61 | Json(ResultMessageData::build_success(handler::stream_idle(info).await)) 62 | } 63 | 64 | ///完成录像 65 | #[oai(path = "/end/record", method = "post")] 66 | async fn end_record(&self, stream_record_info: Json) -> Json> { 67 | let info = stream_record_info.0; 68 | info!("end_record = {:?}", &info); 69 | Json(ResultMessageData::build_success(handler::end_record(info).await)) 70 | } 71 | } -------------------------------------------------------------------------------- /session/src/web/mod.rs: -------------------------------------------------------------------------------- 1 | use common::serde::{Deserialize, Serialize}; 2 | use poem_openapi::Object; 3 | 4 | pub mod api; 5 | pub mod hook; 6 | pub mod se; 7 | 8 | 9 | #[derive(Object, Serialize, Deserialize, Debug)] 10 | #[serde(crate = "common::serde")] 11 | pub struct SingleParam { 12 | pub param: T, 13 | } -------------------------------------------------------------------------------- /session/src/web/se.rs: -------------------------------------------------------------------------------- 1 | use poem_openapi::{OpenApi, param::Query}; 2 | use poem_openapi::payload::Binary; 3 | use crate::service; 4 | use crate::utils::se_token; 5 | use poem::Body; 6 | 7 | pub struct SeApi; 8 | 9 | #[OpenApi(prefix_path = "/es")] 10 | impl SeApi { 11 | #[allow(non_snake_case)] 12 | #[oai(path = "/pic/upload", method = "post", ignore_case)] 13 | async fn pic_upload(&self, 14 | #[oai(name = "token")] token: Query, 15 | #[oai(name = "SessionID")] SessionID: Query, 16 | #[oai(name = "FileID")] FileID: Query>, 17 | #[oai(name = "SnapShotFileID")] SnapShotFileID: Query>, 18 | data: Binary) { 19 | if se_token::check_token(SessionID.0.as_str(), token.0.as_str()).is_ok() { 20 | let _ = service::biz::upload(data, SessionID.0.clone(), FileID.0.clone(), SnapShotFileID.0.clone()).await; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /session/tests/test.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/session/tests/test.rs -------------------------------------------------------------------------------- /sources/c_d_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/c_d_list.png -------------------------------------------------------------------------------- /sources/c_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/c_list.png -------------------------------------------------------------------------------- /sources/c_play.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/c_play.png -------------------------------------------------------------------------------- /sources/d_add.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/d_add.png -------------------------------------------------------------------------------- /sources/d_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/d_list.png -------------------------------------------------------------------------------- /sources/down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/down.png -------------------------------------------------------------------------------- /sources/playback.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/playback.png -------------------------------------------------------------------------------- /sources/swagger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/sources/swagger.png -------------------------------------------------------------------------------- /stream/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "gmv-stream" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | common = { git = "https://github.com/epimore/pigs.git",rev = "8b9fb07c", features = ["net"] } 10 | #common = { path = "../../pigs/common", features = ["net"] } 11 | parking_lot = "0.12" 12 | tokio-util = "0.7" 13 | futures-util = "0.3" 14 | hyper = { version = "0.14.26", features = ["full"] } 15 | http-body-util = "0.1" 16 | reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } 17 | form_urlencoded = "1.2.1" 18 | tokio-stream = { version = "0.1.15", features = ["sync"] } 19 | rtp = "0.11" 20 | webrtc-util = "0.9" 21 | #mpeg2ts = "0.3" 22 | #m3u8-rs = "6.0" 23 | #hls_m3u8 = "0.5" 24 | byteorder = "1" 25 | amf = "1.0" 26 | h264-reader = "=0.7" 27 | memchr = "2.7" 28 | #rayon = "1.10" 29 | crossbeam-channel = "0.5" 30 | mp4 = "0.14" -------------------------------------------------------------------------------- /stream/config.yml: -------------------------------------------------------------------------------- 1 | log: 2 | level: info 3 | prefix: stream 4 | store_path: ./logs 5 | specify: 6 | - crate_name: gmv_stream::biz,gmv_stream::io::http_handler 7 | level: debug 8 | file_name_prefix: biz #日志文件前缀 9 | additivity: false #是否记录到默认日志文件中 10 | 11 | server: 12 | name: s1 #服务标识身份,流媒体集群唯一标识 13 | rtp_port: 18568 #监听rtp媒体流端口; 14 | rtcp_port: 18569 #监听rtcp媒体流端口; 暂未实现 15 | http_port: 18570 #流媒体API端口 16 | hook_uri: http://127.0.0.1:18567/session/hook #信令服务的地址 17 | stream: #开启信令订阅监听时,可自定义修改; 18 | expires: 6 #i32 单位秒;默认无人观看后,6秒关闭流;0为立即关闭;负为永不关闭 19 | # 媒体类型总开关,若信令点播时,指定媒体类型未启用则不可用,常用核心媒体类型 20 | flv: true #默认开启 21 | hls: false #默认开启 22 | 23 | -------------------------------------------------------------------------------- /stream/readme: -------------------------------------------------------------------------------- 1 | 流播放地址: 2 | /flv/{stream_id}/{token} 3 | /hls/{stream_id}/{token} 4 | 5 | ffmpeg -re -i E:\book\mv\st\yddz.mp4 -vcodec copy -f rtp rtp://172.18.38.186:18568 6 | ffmpeg -re -i E:\code\rust\study\media\rsmpeg\tests\assets\vids\big_buck_bunny_1080p_24fps_h264.h264 -vcodec copy -f rtp rtp://172.18.38.186:18568 7 | ffmpeg -protocol_whitelist file,udp,rtp -i ./123.sdp -c:v copy -f flv 1.flv 8 | ffplay -headers "gmv-token: 1243aaa" "http://172.18.38.186:1857" 9 | cd /mnt/e/code/rust/study/media/rsmpeg/tests/assets/vids/ 10 | wget --header="gmv-token: 1243aaa" "http://172.18.38.186:18570/stream-node-1/play/4FEqqz4eqqq0Vzqqq2lsqc4S3Kqqs.flv" 11 | 34020000002000000001s2000012345r34020000001111141016 12 | 13 | 76gujiu04do00 14 | 15 | ffplay -headers "gmv-token: user001-gmv-token"-headers "gmv-token: user001-gmv-token" http://172.18.38.186:18570/s1/4FEqqz1Dqsq0Vzqq3K2m0tqq4Zqq6m0s.flv 16 | http://172.18.38.186:18568/s1/4FEqqz1Dqsq0Vzqq3K2m0tqq4Zqq6m0s.flv 17 | 18 | 19 | Via: SIP/2.0/UDP 10.64.49.44:7100;rport=7100;branch=z9hG4bK1839167633 20 | From: ;tag=868569348 21 | To: ;tag=3330812776 22 | Call-ID: 2074790969 23 | CSeq: 20 INVITE 24 | Contact: 25 | Content-Type: Application/SDP 26 | User-Agent: Hikvision 27 | Content-Length: 162 28 | 29 | 30 | ffmpeg version 4.4.1-full_build-www.gyan.dev Copyright (c) 2000-2021 the FFmpeg developers 31 | built with gcc 11.2.0 (Rev1, Built by MSYS2 project) 32 | configuration: --enable-gpl --enable-version3 --enable-shared --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libdav1d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libglslang --enable-vulkan --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint 33 | libavutil 56. 70.100 / 56. 70.100 34 | libavcodec 58.134.100 / 58.134.100 35 | libavformat 58. 76.100 / 58. 76.100 36 | libavdevice 58. 13.100 / 58. 13.100 37 | libavfilter 7.110.100 / 7.110.100 38 | libswscale 5. 9.100 / 5. 9.100 39 | libswresample 3. 9.100 / 3. 9.100 40 | libpostproc 55. 9.100 / 55. 9.100 41 | Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'E:\book\mv\st\yddz.mp4': 42 | Metadata: 43 | major_brand : isom 44 | minor_version : 512 45 | compatible_brands: isomiso2avc1mp41 46 | creation_time : 2023-06-08T02:34:14.000000Z 47 | Duration: 00:53:42.94, start: 0.000000, bitrate: 982 kb/s 48 | Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1920x1080, 980 kb/s, 24.99 fps, 1k tbr, 1k tbn, 2k tbc (default) 49 | Metadata: 50 | creation_time : 2023-06-08T02:34:14.000000Z 51 | handler_name : VideoHandler 52 | vendor_id : [0][0][0][0] 53 | Output #0, rtp, to 'rtp://172.18.38.186:18568': 54 | Metadata: 55 | major_brand : isom 56 | minor_version : 512 57 | compatible_brands: isomiso2avc1mp41 58 | encoder : Lavf58.76.100 59 | Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1920x1080, q=2-31, 980 kb/s, 24.99 fps, 1k tbr, 90k tbn, 1k tbc (default) 60 | Metadata: 61 | creation_time : 2023-06-08T02:34:14.000000Z 62 | handler_name : VideoHandler 63 | vendor_id : [0][0][0][0] 64 | SDP: 65 | v=0 66 | o=- 0 0 IN IP4 127.0.0.1 67 | s=No Name 68 | c=IN IP4 172.18.38.186 69 | t=0 0 70 | a=tool:libavformat 58.76.100 71 | m=video 18568 RTP/AVP 96 72 | b=AS:980 73 | a=rtpmap:96 H264/90000 74 | a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z00AKpWoHgCJ+VA=,aO48gA==; profile-level-id=4D002A 75 | 76 | Stream mapping: 77 | Stream #0:0 -> #0:0 (copy) 78 | Press [q] to stop, [?] for help 79 | frame= 28 fps= 26 q=-1.0 Lsize= 158kB time=00:00:01.08 bitrate=1191.0kbits/s speed=1.02x 80 | video:156kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 1.034213% 81 | 82 | 83 | 00 5e f8 ff 00 24 40 0e 48 4b 01 00 14 14 40 16 6b bf 00 ff ff ff 41 12 48 4b 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 00 30 1b e0 00 1c 42 0e 07 10 10 ea 05 00 02 d0 11 30 00 00 1c 21 2a 0a 7f ff 00 00 07 08 1f fe a0 5a 90 c0 00 0c 43 0a 01 40 fe 00 7d 03 03 e8 03 ff f6 53 94 03 84 | -------------------------------------------------------------------------------- /stream/src/app.rs: -------------------------------------------------------------------------------- 1 | use std::net::UdpSocket; 2 | use common::log::{error, info}; 3 | use common::daemon::Daemon; 4 | use common::exception::{GlobalError, GlobalResult, TransError}; 5 | use common::{logger, tokio}; 6 | use common::tokio::sync::mpsc; 7 | use crate::general::mode::ServerConf; 8 | use crate::io::{http_handler, rtp_handler}; 9 | use crate::state::cache; 10 | use crate::trans; 11 | 12 | pub struct App { 13 | conf: ServerConf, 14 | } 15 | 16 | impl Daemon<(std::net::TcpListener, (Option, Option))> for App { 17 | fn init_privilege() -> GlobalResult<(Self, (std::net::TcpListener, (Option, Option)))> 18 | where 19 | Self: Sized, 20 | { 21 | let app = App { 22 | conf: cache::get_server_conf().clone() 23 | }; 24 | logger::Logger::init()?; 25 | banner(); 26 | let http_listener = http_handler::listen_http_server(*(app.conf.get_http_port()))?; 27 | let tu = rtp_handler::listen_gb_server(*(app.conf.get_rtp_port()))?; 28 | Ok((app, (http_listener, tu))) 29 | } 30 | 31 | fn run_app(self, t: (std::net::TcpListener, (Option, Option))) -> GlobalResult<()> { 32 | let (http_listener, tu) = t; 33 | let conf = self.conf; 34 | let node_name = conf.get_name().clone(); 35 | let (tx, rx) = mpsc::channel(100); 36 | trans::trans_run(rx); 37 | tokio::runtime::Builder::new_multi_thread() 38 | .enable_all() 39 | .build() 40 | .unwrap() 41 | .block_on(async { 42 | let st = tokio::spawn(async move { 43 | info!("Stream server start running..."); 44 | rtp_handler::run(tu).await?; 45 | error!("Stream server stop"); 46 | Ok::<(), GlobalError>(()) 47 | }); 48 | 49 | let web = tokio::spawn(async move { 50 | info!("Web server start running..."); 51 | http_handler::run(node_name, http_listener, tx).await?; 52 | error!("Web server stop"); 53 | Ok::<(), GlobalError>(()) 54 | }); 55 | st.await.hand_log(|msg| error!("Stream:{msg}"))??; 56 | web.await.hand_log(|msg| error!("WEB:{msg}"))??; 57 | Ok::<(), GlobalError>(()) 58 | })?; 59 | error!("系统异常退出..."); 60 | Ok(()) 61 | } 62 | } 63 | 64 | fn banner() { 65 | let br = r#" 66 | ___ __ __ __ __ _ ___ _____ ___ ___ ___ __ __ 67 | o O O / __| | \/ | \ \ / / (_) / __| |_ _| | _ \ | __| / \ | \/ | 68 | o | (_ | | |\/| | \ V / _ \__ \ | | | / | _| | - | | |\/| | 69 | oO__[O] \___| |_|__|_| _\_/_ _(_)_ |___/ _|_|_ |_|_\ |___| |_|_| |_|__|_| 70 | {======|_|""G""|_|""M""|_|""V""|_|"":""|_|""S""|_|""T""|_|""R""|_|""E""|_|""A""|_|""M""| 71 | ./0--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' 72 | "#; 73 | info!("{}", br); 74 | } -------------------------------------------------------------------------------- /stream/src/biz/call.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use common::constructor::{Get, New}; 4 | use common::exception::TransError; 5 | use common::log::error; 6 | use common::serde::{Deserialize, Serialize}; 7 | 8 | use crate::container::PlayType; 9 | use crate::general::mode; 10 | use crate::general::mode::TIME_OUT; 11 | use crate::state::cache; 12 | 13 | #[derive(Serialize, Deserialize, Debug)] 14 | #[serde(crate = "common::serde")] 15 | pub struct RespBo { 16 | code: u16, 17 | msg: Option, 18 | data: Option, 19 | } 20 | 21 | #[derive(New, Serialize, Get)] 22 | #[serde(crate = "common::serde")] 23 | pub struct NetSource { 24 | remote_addr: String, 25 | protocol: String, 26 | } 27 | 28 | #[derive(New, Serialize, Get)] 29 | #[serde(crate = "common::serde")] 30 | pub struct RtpInfo { 31 | ssrc: u32, 32 | //媒体流源地址,tcp/udp 33 | origin_trans: Option, 34 | server_name: String, 35 | } 36 | 37 | impl RtpInfo { 38 | //未知流,每隔8秒提示一次? 39 | pub async fn stream_unknown(&self) {} 40 | } 41 | 42 | #[derive(New, Serialize, Get)] 43 | #[serde(crate = "common::serde")] 44 | pub struct BaseStreamInfo { 45 | rtp_info: RtpInfo, 46 | stream_id: String, 47 | in_time: u32, 48 | } 49 | 50 | impl BaseStreamInfo { 51 | //当接收到输入流时进行回调 52 | pub async fn stream_in(&self) -> Option { 53 | let client = reqwest::Client::new(); 54 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::STREAM_IN); 55 | let res = client.post(uri) 56 | .timeout(Duration::from_millis(TIME_OUT)) 57 | .json(self).send().await 58 | .hand_log(|msg| error!("{msg}")) 59 | .ok().map(|res| res.status().is_success()); 60 | res 61 | } 62 | // 当流闲置时(无观看、无录制) 63 | pub async fn stream_idle(&self) -> Option { 64 | let client = reqwest::Client::new(); 65 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::STREAM_IDLE); 66 | let res = client.post(uri) 67 | .timeout(Duration::from_millis(TIME_OUT)) 68 | .json(self).send().await 69 | .hand_log(|msg| error!("{msg}")) 70 | .ok().map(|res| res.status().is_success()); 71 | res 72 | } 73 | } 74 | 75 | #[derive(New, Serialize, Get)] 76 | #[serde(crate = "common::serde")] 77 | pub struct StreamPlayInfo { 78 | base_stream_info: BaseStreamInfo, 79 | remote_addr: String, 80 | token: String, 81 | play_type: PlayType, 82 | //当前观看人数 83 | user_count: u32, 84 | } 85 | 86 | impl StreamPlayInfo { 87 | //当用户访问播放流时进行回调(可用于鉴权) 88 | pub async fn on_play(&self) -> Option { 89 | let client = reqwest::Client::new(); 90 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::ON_PLAY); 91 | let res = client.post(uri) 92 | .timeout(Duration::from_millis(TIME_OUT)) 93 | .json(self).send().await 94 | .hand_log(|msg| error!("{msg}")); 95 | match res { 96 | Ok(resp) => { 97 | match (resp.status().is_success(), resp.json::>().await) { 98 | (true, Ok(RespBo { code: 200, msg: _, data: Some(true) })) => { 99 | Some(true) 100 | } 101 | _ => { 102 | Some(false) 103 | } 104 | } 105 | } 106 | Err(_) => { 107 | None 108 | } 109 | } 110 | } 111 | 112 | //当用户断开播放时进行回调 113 | pub async fn off_play(&self) -> Option { 114 | let client = reqwest::Client::new(); 115 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::OFF_PLAY); 116 | let res = client.post(uri) 117 | .timeout(Duration::from_millis(TIME_OUT)) 118 | .json(self).send().await 119 | .hand_log(|msg| error!("{msg}")); 120 | match res { 121 | Ok(resp) => { 122 | match (resp.status().is_success(), resp.json::>().await) { 123 | (true, Ok(RespBo { code: 200, msg: _, data: Some(true) })) => { 124 | Some(true) 125 | } 126 | _ => { 127 | Some(false) 128 | } 129 | } 130 | } 131 | Err(_) => { 132 | None 133 | } 134 | } 135 | } 136 | } 137 | 138 | #[derive(New, Serialize, Clone)] 139 | #[serde(crate = "common::serde")] 140 | pub struct StreamRecordInfo { 141 | pub file_name: Option, 142 | //单位kb,录制完成时统计文件大小 143 | pub file_size: Option, 144 | //媒体流进度时间,方便计算进度,单位秒 145 | pub timestamp: u32, 146 | //每秒录制字节数 147 | pub bytes_sec: usize, 148 | } 149 | 150 | impl StreamRecordInfo { 151 | //当流录制完成时进行回调 152 | pub async fn end_record(&self) -> Option { 153 | let client = reqwest::Client::new(); 154 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::END_RECORD); 155 | let res = client.post(uri) 156 | .timeout(Duration::from_millis(TIME_OUT)) 157 | .json(self).send().await 158 | .hand_log(|msg| error!("{msg}")); 159 | match res { 160 | Ok(resp) => { 161 | match (resp.status().is_success(), resp.json::>().await) { 162 | (true, Ok(_)) => { 163 | Some(true) 164 | } 165 | _ => { 166 | Some(false) 167 | } 168 | } 169 | } 170 | Err(_) => { 171 | None 172 | } 173 | } 174 | } 175 | } 176 | 177 | impl StreamState { 178 | //当等待输入流超时时进行回调 179 | pub async fn stream_input_timeout(&self) -> Option { 180 | let client = reqwest::Client::new(); 181 | let uri = format!("{}{}", cache::get_server_conf().get_hook_uri(), mode::STREAM_INPUT_TIMEOUT); 182 | let res = client.post(uri) 183 | .timeout(Duration::from_millis(TIME_OUT)) 184 | .json(self).send().await 185 | .hand_log(|msg| error!("{msg}")); 186 | match res { 187 | Ok(resp) => { 188 | match (resp.status().is_success(), resp.json::>().await) { 189 | (true, Ok(_)) => { 190 | Some(true) 191 | } 192 | _ => { 193 | Some(false) 194 | } 195 | } 196 | } 197 | Err(_) => { 198 | None 199 | } 200 | } 201 | } 202 | } 203 | 204 | #[derive(New, Serialize)] 205 | #[serde(crate = "common::serde")] 206 | pub struct StreamState { 207 | base_stream_info: BaseStreamInfo, 208 | user_count: u32, 209 | // record_name: Option, 210 | } 211 | -------------------------------------------------------------------------------- /stream/src/biz/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod api; 2 | pub mod call; -------------------------------------------------------------------------------- /stream/src/coder/h264.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Cursor}; 2 | use byteorder::{BigEndian, ByteOrder}; 3 | use h264_reader::{Context, rbsp}; 4 | use h264_reader::nal::pps::PicParameterSet; 5 | use h264_reader::nal::sps::SeqParameterSet; 6 | use common::log::{info}; 7 | use memchr::memmem; 8 | use common::log::{warn}; 9 | use rtp::codecs::h264::H264Packet; 10 | use rtp::packetizer::Depacketizer; 11 | 12 | use common::anyhow::anyhow; 13 | use common::bytes::{Buf, BufMut, Bytes, BytesMut}; 14 | use common::exception::{GlobalError, GlobalResult, TransError}; 15 | use common::exception::GlobalError::SysErr; 16 | use rtp::packet::Packet; 17 | 18 | use crate::coder::{CodecPayload, ToFrame}; 19 | 20 | pub struct H264Context { 21 | h264packet: H264Packet, 22 | } 23 | 24 | impl ToFrame for H264Context { 25 | fn parse(&mut self, pkt: Packet, codec_payload: &mut CodecPayload) -> GlobalResult<()> { 26 | if let Ok(raw_data) = self.h264packet.depacketize(&pkt.payload).hand_log(|msg| warn!("{msg}")) { 27 | let raw_data_len = raw_data.len(); 28 | let nal_data_size_len = 4; 29 | let mut curr_offset = 0; 30 | while curr_offset + nal_data_size_len < raw_data_len { 31 | let size_data = raw_data.slice(curr_offset..curr_offset + nal_data_size_len); 32 | let size_data_len = BigEndian::read_u32(size_data.as_ref()) as usize; 33 | let last_offset = curr_offset + nal_data_size_len + size_data_len; 34 | if last_offset > raw_data_len { 35 | info!("nal size larger than raw buffer"); 36 | break; 37 | } else { 38 | let nal_data = raw_data.slice(curr_offset..last_offset); 39 | codec_payload.video_payload.2 = pkt.header.timestamp; 40 | codec_payload.video_payload.1.push(nal_data); 41 | curr_offset = last_offset; 42 | } 43 | } 44 | } 45 | Ok(()) 46 | } 47 | } 48 | 49 | impl H264Context { 50 | pub fn is_new_access_unit(nal_type: u8, first_mb: u8) -> bool { 51 | if matches!(nal_type,6..=9|14..=18) { 52 | return true; 53 | } 54 | if matches!(nal_type,1|2|5) { 55 | return first_mb != 0; 56 | } 57 | false 58 | } 59 | 60 | pub fn init_annexb() -> Self { 61 | Self { h264packet: H264Packet::default() } 62 | } 63 | pub fn init_avc() -> Self { 64 | let mut h264packet = H264Packet::default(); 65 | h264packet.is_avc = true; 66 | Self { h264packet } 67 | } 68 | 69 | pub fn parse_sps(sps_nal: &Bytes) -> GlobalResult { 70 | let sps_rbsp = rbsp::decode_nal(&sps_nal[..]).hand_log(|msg| warn!("{msg}"))?; 71 | let sps = SeqParameterSet::from_bits(rbsp::BitReader::new(&*sps_rbsp)) 72 | .map_err(|err| SysErr(anyhow!("{:?}",err))) 73 | .hand_log(|msg| warn!("{msg}"))?; 74 | Ok(sps) 75 | } 76 | pub fn parse_sps_pps(pps_nal: &Bytes, sps_nal: &Bytes) -> GlobalResult<(SeqParameterSet, PicParameterSet)> { 77 | let sps_rbsp = rbsp::decode_nal(&sps_nal[..]).hand_log(|msg| warn!("{msg}"))?; 78 | let sps = SeqParameterSet::from_bits(rbsp::BitReader::new(&*sps_rbsp)) 79 | .map_err(|err| SysErr(anyhow!("{:?}",err))) 80 | .hand_log(|msg| warn!("{msg}"))?; 81 | let mut ctx = Context::default(); 82 | ctx.put_seq_param_set(sps.clone()); 83 | let pps_rbsp = rbsp::decode_nal(&pps_nal[..]).hand_log(|msg| warn!("{msg}"))?; 84 | let pps = PicParameterSet::from_bits(&ctx, rbsp::BitReader::new(&*pps_rbsp)) 85 | .map_err(|err| SysErr(anyhow!("{:?}",err))) 86 | .hand_log(|msg| warn!("{msg}"))?; 87 | Ok((sps, pps)) 88 | } 89 | 90 | pub fn get_width_height_frame_rate(sps_nal: &Bytes) -> GlobalResult<(u32, u32, f64)> { 91 | let sps_rbsp = rbsp::decode_nal(&sps_nal[..]).hand_log(|msg| warn!("{msg}"))?; 92 | let sps = SeqParameterSet::from_bits(rbsp::BitReader::new(&*sps_rbsp)) 93 | .map_err(|err| SysErr(anyhow!("{:?}",err))) 94 | .hand_log(|msg| warn!("{msg}"))?; 95 | let (width, height) = sps.pixel_dimensions() 96 | .map_err(|err| SysErr(anyhow!("{:?}",err))) 97 | .hand_log(|msg| warn!("{msg}"))?; 98 | let fps = sps.fps().unwrap_or_else(|| { 99 | warn!("fps 未知;使用默认 25"); 100 | 25.0 101 | }); 102 | Ok((width, height, fps)) 103 | } 104 | 105 | #[allow(non_upper_case_globals)] 106 | pub fn extract_nal_annexb_to_len(nals: &mut Vec, bytes_annexb: Bytes) -> GlobalResult<()> { 107 | if !bytes_annexb.starts_with(&[0]) { 108 | return Err(GlobalError::new_sys_error("h264 invalid start annexb code", |msg| warn!("{msg}"))); 109 | } 110 | const annexb: [u8; 3] = [0x00u8, 00, 01]; 111 | // let mut nals = Vec::new(); 112 | let mut start = 3usize; 113 | let mut iter = memmem::find_iter(&*bytes_annexb, &annexb); 114 | if let Some(index) = iter.next() { 115 | if index == 1 { 116 | start = 4; 117 | } else if index > 1 { 118 | return Err(GlobalError::new_sys_error("h264 invalid start annexb code", |msg| warn!("{msg}"))); 119 | } 120 | } 121 | while let Some(index) = iter.next() { 122 | let mut end = index; 123 | if bytes_annexb[index - 1] == 0 { 124 | end -= 1; 125 | } 126 | let mut nal = BytesMut::new(); 127 | 128 | // info!("nalu type = {:02x},scope = {:02x?}",bytes_annexb[start],bytes_annexb[start-3..start+10].to_vec()); 129 | 130 | nal.put_u32((end - start) as u32); 131 | nal.put_slice(&bytes_annexb[start..end]); 132 | // let nal = Bytes::copy_from_slice(&bytes_annexb[start..end]); 133 | nals.push(nal.freeze()); 134 | start = index + 3; 135 | } 136 | 137 | // info!("nalu type = {:02x},scope = {:02x?}",bytes_annexb[start],bytes_annexb[start-3..start+10].to_vec()); 138 | 139 | let mut nal = BytesMut::new(); 140 | nal.put_u32((bytes_annexb.len() - start) as u32); 141 | nal.put_slice(&bytes_annexb[start..bytes_annexb.len()]); 142 | // let nal = Bytes::copy_from_slice(&bytes_annexb[start..bytes_annexb.len()]); 143 | nals.push(nal.freeze()); 144 | Ok(()) 145 | } 146 | 147 | pub fn extract_nal_by_annexb1(bytes_annexb: Bytes) -> Vec { 148 | let len = bytes_annexb.len() as u64; 149 | let mut nals = Vec::new(); 150 | let mut nal = BytesMut::new(); 151 | let mut cursor = Cursor::new(bytes_annexb); 152 | let mut count_zero = 0u8; 153 | while cursor.position() < len { 154 | let val = cursor.get_u8(); 155 | match val { 156 | 0 => { 157 | if count_zero == 3 { 158 | nal.put_u8(val); 159 | } else { 160 | count_zero += 1; 161 | } 162 | } 163 | 1 => { 164 | match count_zero { 165 | 0 => { 166 | nal.put_u8(val); 167 | } 168 | 1 => { 169 | nal.put_u8(0); 170 | nal.put_u8(val); 171 | count_zero = 0; 172 | } 173 | _ => { 174 | if nal.len() > 0 { 175 | let bytes_mut = std::mem::take(&mut nal); 176 | nals.push(bytes_mut.freeze()); 177 | } 178 | count_zero = 0; 179 | } 180 | } 181 | } 182 | _ => { 183 | while count_zero > 0 { 184 | nal.put_u8(0); 185 | count_zero -= 1; 186 | } 187 | nal.put_u8(val); 188 | } 189 | } 190 | } 191 | while count_zero > 0 { 192 | nal.put_u8(0); 193 | count_zero -= 1; 194 | } 195 | if nal.len() > 0 { 196 | nals.push(nal.freeze()); 197 | } 198 | nals 199 | } 200 | } 201 | 202 | #[cfg(test)] 203 | mod test { 204 | use common::bytes::Bytes; 205 | 206 | use crate::coder::h264::H264Context; 207 | 208 | #[test] 209 | fn test_sps() { 210 | let sps = [ 211 | 0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0, 212 | 0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 213 | 0x00, 0x03, 0x00, 0x3d, 0x08, 214 | ]; 215 | println!("{:?}", H264Context::get_width_height_frame_rate(&Bytes::from(sps.to_vec()))); 216 | 217 | let sps = [ 218 | 0x67, 0x64, 0x00, 0x1f, 0xac, 0xd9, 0x40, 0x50, 219 | 0x05, 0xbb, 0x01, 0x6c, 0x80, 0x00, 0x00, 0x03, 220 | 0x00, 0x80, 0x00, 0x00, 0x1e, 0x07, 0x8c, 0x18, 221 | 0xcb, 222 | ]; 223 | println!("{:?}", H264Context::get_width_height_frame_rate(&Bytes::from(sps.to_vec()))); 224 | 225 | let sps = [ 226 | 0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, 227 | 0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, 228 | 0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20, 229 | ]; 230 | println!("{:?}", H264Context::get_width_height_frame_rate(&Bytes::from(sps.to_vec()))); 231 | 232 | let sps = [ 233 | 0x67, 0x64, 0x00, 0x28, 0xac, 0xd9, 0x40, 0x78, 234 | 0x02, 0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 235 | 0x04, 0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 236 | 0xc6, 0x58, 237 | ]; 238 | println!("{:?}", H264Context::get_width_height_frame_rate(&Bytes::from(sps.to_vec()))); 239 | } 240 | 241 | #[test] 242 | fn test_if_else() { 243 | let a = 2; 244 | let b = true; 245 | if a == 2 { 246 | println!("a==2"); 247 | } else if b { 248 | println!("a != 2 and b is true"); 249 | } 250 | println!("end"); 251 | } 252 | 253 | #[test] 254 | fn test_extract_nal_by_annexb() { 255 | let bytes_annexb = Bytes::from_static(&[ 256 | 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e, 257 | 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x06, 0xf2, 258 | 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x0a, 0x02, 259 | 0x00, 0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x0a, 0x00, 260 | ]); 261 | 262 | let mut vec = Vec::new(); 263 | H264Context::extract_nal_annexb_to_len(&mut vec, bytes_annexb).unwrap(); 264 | vec.iter().map(|iter| println!("{:02x?}", iter.to_vec())).count(); 265 | } 266 | 267 | #[test] 268 | fn test_extract_nal_by_annexb1() { 269 | let bytes_annexb = Bytes::from_static(&[ 270 | 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1e, 271 | 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x06, 0xf2, 272 | 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x0a, 0x02, 273 | 0x00, 0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x0a, 0x00, 274 | ]); 275 | let vec = H264Context::extract_nal_by_annexb1(bytes_annexb); 276 | vec.iter().map(|iter| println!("{:02x?}", iter.to_vec())).count(); 277 | } 278 | 279 | // #[test] 280 | // fn test_es() { 281 | // let input = include_bytes!("/mnt/e/code/rust/study/media/rsmpeg/tests/assets/vids/es1.dump"); 282 | // let bytes = Bytes::copy_from_slice(input); 283 | // let mut vec = Vec::new(); 284 | // H264::extract_nal_annexb_to_len(&mut vec, bytes).unwrap(); 285 | // println!("vec len = {}", vec.len()); 286 | // vec.iter().map(|iter| { 287 | // if iter.len() <= 2 { 288 | // println!("1111"); 289 | // } 290 | // } 291 | // ).count(); 292 | // } 293 | } -------------------------------------------------------------------------------- /stream/src/coder/mod.rs: -------------------------------------------------------------------------------- 1 | use common::bytes::Bytes; 2 | use common::exception::GlobalResult; 3 | use rtp::packet::Packet; 4 | 5 | use crate::general::mode::Coder; 6 | 7 | pub mod h264; 8 | 9 | 10 | pub enum VideoCodec { 11 | H264, 12 | H265, 13 | } 14 | 15 | pub enum AudioCodec { 16 | G711, 17 | // SVAC_A, 18 | // G723_1, 19 | // G729, 20 | // G722_1, 21 | // AAC, 22 | } 23 | 24 | #[derive(Clone)] 25 | pub struct FrameData { 26 | pub pay_type: Coder, 27 | pub timestamp: u32, 28 | pub data: Bytes, 29 | } 30 | 31 | pub type HandleFrameDataFn = Box GlobalResult<()> + Send + Sync>; 32 | 33 | #[derive(Default)] 34 | pub struct CodecPayload { 35 | //codec,data,timestamp 36 | pub video_payload: (Option, Vec, u32), 37 | pub audio_payload: (Option, Vec, u32), 38 | // pub other_payload:(Vec,u32),#字幕/私有信息... 39 | } 40 | 41 | 42 | pub trait ToFrame { 43 | fn parse(&mut self, pkt: Packet, codec_payload: &mut CodecPayload) -> GlobalResult<()>; 44 | } -------------------------------------------------------------------------------- /stream/src/comm/mod.rs: -------------------------------------------------------------------------------- 1 | mod valid; -------------------------------------------------------------------------------- /stream/src/comm/valid.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/epimore/gmv/2131fe15bf7f8d9346a6ec6adcfc84368679a9ed/stream/src/comm/valid.rs -------------------------------------------------------------------------------- /stream/src/container/hls.rs: -------------------------------------------------------------------------------- 1 | use common::serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Deserialize, Serialize, Debug, Default,Copy, Clone)] 4 | #[serde(crate = "common::serde")] 5 | pub struct HlsPiece { 6 | //片时间长度 S 7 | pub duration: u8, 8 | pub live: bool, 9 | } -------------------------------------------------------------------------------- /stream/src/container/mod.rs: -------------------------------------------------------------------------------- 1 | use common::bytes::Bytes; 2 | use common::exception::GlobalResult; 3 | use common::serde::{Deserialize, Serialize}; 4 | 5 | pub mod rtp; 6 | pub mod flv; 7 | pub mod ps; 8 | pub mod hls; 9 | pub mod mp4; 10 | 11 | ///rtp /flv等容器封装h264时,需剔除0000000001/000001开始符 12 | pub type HandleMuxerDataFn = Box GlobalResult<()> + Send + Sync>; 13 | 14 | #[derive(Clone, Copy, Serialize, Deserialize, Debug)] 15 | #[serde(crate = "common::serde")] 16 | pub enum PlayType { 17 | Flv, 18 | Hls, 19 | } 20 | 21 | pub trait PacketWriter { 22 | fn packet(&mut self, vec_frame: &mut Vec, timestamp: u32); 23 | 24 | fn packet_end(&mut self); 25 | } -------------------------------------------------------------------------------- /stream/src/container/mp4.rs: -------------------------------------------------------------------------------- 1 | pub mod mp4_h264 { 2 | use crate::biz::call::StreamRecordInfo; 3 | use crate::coder::h264::H264Context; 4 | use crate::container::PacketWriter; 5 | use crate::io::hook_handler::OutEvent; 6 | use crate::state::cache; 7 | use common::bytes::Bytes; 8 | use common::exception::{GlobalResult, TransError}; 9 | use common::log::{error}; 10 | use common::tokio::sync::broadcast; 11 | use mp4::{MediaConfig, Mp4Config, Mp4Sample, Mp4Writer, TrackConfig, TrackType}; 12 | use std::fs; 13 | use std::fs::File; 14 | use std::io::{Seek, Write}; 15 | use std::time::Instant; 16 | 17 | const H264_NAL_SPS_TYPE: u8 = 0x07; 18 | const H264_NAL_PPS_TYPE: u8 = 0x08; 19 | const H264_NAL_IDR_TYPE: u8 = 0x05; 20 | 21 | 22 | pub struct MediaMp4Context { 23 | pub first_frame_next: bool, 24 | //单轨道 25 | pub track_init: bool, 26 | pub seq_param_set: Option>, 27 | pub pic_param_set: Option>, 28 | pub timestamp: u32, 29 | pub last_ts: Instant, 30 | pub last_frame_timestamp: u32, 31 | pub file_name: String, 32 | pub writer: Mp4Writer, 33 | pub down_tx: broadcast::Sender, 34 | } 35 | 36 | impl MediaMp4Context { 37 | pub fn register(down_tx: broadcast::Sender, file_name: String) -> GlobalResult { 38 | let file = File::create(&file_name).hand_log(|msg| error!("{msg}"))?; 39 | let config = Mp4Config { 40 | major_brand: str::parse("isom").unwrap(), 41 | minor_version: 512, 42 | compatible_brands: vec![ 43 | str::parse("isom").unwrap(), 44 | str::parse("iso2").unwrap(), 45 | str::parse("avc1").unwrap(), 46 | str::parse("mp41").unwrap(), 47 | ], 48 | timescale: 90000, 49 | }; 50 | let writer = Mp4Writer::write_start(file, &config).hand_log(|msg| error!("{msg}"))?; 51 | Ok(Self { first_frame_next: false, track_init: false, seq_param_set: None, pic_param_set: None, timestamp: 0, last_ts: Instant::now(), last_frame_timestamp: 0, file_name, writer, down_tx }) 52 | } 53 | } 54 | 55 | impl PacketWriter for MediaMp4Context { 56 | fn packet(&mut self, vec_frame: &mut Vec, timestamp: u32) { 57 | let mut bytes_len = 0; 58 | while let Some(frame) = vec_frame.pop() { 59 | let mut is_sync = false; 60 | let nal_type = frame[4] & 0x1F; 61 | match nal_type { 62 | H264_NAL_SPS_TYPE => { 63 | if self.first_frame_next { 64 | continue; 65 | } 66 | if self.seq_param_set.is_none() { 67 | self.seq_param_set = Some(frame.to_vec()); 68 | } 69 | if !self.track_init && self.pic_param_set.is_some() { 70 | if let Ok((width, height, _fps)) = H264Context::get_width_height_frame_rate(&frame.slice(4..)) { 71 | let track_config = TrackConfig { 72 | track_type: mp4::TrackType::Video, 73 | timescale: 90000, 74 | language: "und".to_string(), // 未指定语言 75 | media_conf: MediaConfig::AvcConfig(mp4::AvcConfig { 76 | width: width as u16, 77 | height: height as u16, 78 | seq_param_set: frame[4..].to_vec(), 79 | pic_param_set: self.pic_param_set.clone().unwrap()[4..].to_vec(), 80 | }), 81 | }; 82 | if let Ok(_) = self.writer.add_track(&track_config).hand_log(|msg| error!("{msg}")) { 83 | self.track_init = true; 84 | }; 85 | } 86 | } 87 | } 88 | H264_NAL_PPS_TYPE => { 89 | if self.first_frame_next { 90 | continue; 91 | } 92 | if self.pic_param_set.is_none() { 93 | self.pic_param_set = Some(frame.to_vec()); 94 | } 95 | if !self.track_init && self.seq_param_set.is_some() { 96 | if let Ok((width, height, _fps)) = H264Context::get_width_height_frame_rate(&frame.slice(4..)) { 97 | let track_config = TrackConfig { 98 | track_type: TrackType::Video, 99 | timescale: 90000, 100 | language: "und".to_string(), // 未指定语言 101 | media_conf: MediaConfig::AvcConfig(mp4::AvcConfig { 102 | width: width as u16, 103 | height: height as u16, 104 | seq_param_set: self.seq_param_set.clone().unwrap()[4..].to_vec(), 105 | pic_param_set: frame[4..].to_vec(), 106 | }), 107 | }; 108 | if let Ok(_) = self.writer.add_track(&track_config).hand_log(|msg| error!("{msg}")) { 109 | self.track_init = true; 110 | }; 111 | } 112 | } 113 | } 114 | H264_NAL_IDR_TYPE => { 115 | is_sync = true; 116 | } 117 | _ => {} 118 | } 119 | 120 | if !self.track_init { continue; } 121 | let size = frame.len(); 122 | if self.first_frame_next { 123 | let sample = Mp4Sample { 124 | start_time: (timestamp - self.timestamp) as u64, 125 | duration: timestamp - self.last_frame_timestamp, 126 | rendering_offset: 0, 127 | is_sync, 128 | bytes: frame, 129 | }; 130 | if let Ok(_) = self.writer.write_sample(1, &sample).hand_log(|msg| error!("{msg}")) { 131 | bytes_len += size; 132 | }; 133 | } else { 134 | if is_sync { 135 | self.first_frame_next = true; 136 | let sample = Mp4Sample { 137 | start_time: 0, 138 | duration: timestamp - self.last_frame_timestamp, 139 | rendering_offset: 0, 140 | is_sync, 141 | bytes: frame, 142 | }; 143 | if let Ok(_) = self.writer.write_sample(1, &sample).hand_log(|msg| error!("{msg}")) { 144 | bytes_len += size; 145 | }; 146 | self.timestamp = timestamp; 147 | } 148 | } 149 | } 150 | let now = Instant::now(); 151 | let unit_sec = now.duration_since(self.last_ts).as_millis() as usize; 152 | if self.first_frame_next && unit_sec >= 1000 { 153 | let bytes_sec = bytes_len * 1000 / unit_sec; 154 | let info = StreamRecordInfo { file_name: None, file_size: None, timestamp: timestamp / 90000, bytes_sec }; 155 | //不监听是否发送成功,接收端是http随机访问 156 | let _ = self.down_tx.send(info); 157 | self.last_ts = now; 158 | } 159 | self.last_frame_timestamp = timestamp; 160 | } 161 | fn packet_end(&mut self) { 162 | if let Ok(_) = self.writer.write_end().hand_log(|msg| error!("{msg}")) { 163 | if let Ok(m) = fs::metadata(&self.file_name) { 164 | let info = StreamRecordInfo { file_name: Some(self.file_name.clone()), file_size: Some(m.len()), timestamp: self.timestamp / 90000, bytes_sec: 0 }; 165 | let sender = cache::get_event_tx(); 166 | let _ = sender.try_send((OutEvent::EndRecord(info), None)).hand_log(|msg| error!("{}; MP4录制完成事件推送失败:{}",self.file_name,msg)); 167 | } 168 | } 169 | } 170 | } 171 | } 172 | 173 | 174 | -------------------------------------------------------------------------------- /stream/src/container/rtp.rs: -------------------------------------------------------------------------------- 1 | use std::collections::hash_map::Entry; 2 | use std::collections::HashMap; 3 | use std::net::SocketAddr; 4 | use common::bytes::{Buf, BufMut, Bytes, BytesMut}; 5 | 6 | pub struct TcpRtpBuffer { 7 | //AHashMap ? 8 | inner: HashMap<(SocketAddr, SocketAddr), BytesMut>, 9 | } 10 | 11 | impl TcpRtpBuffer { 12 | pub fn register_buffer() -> Self { 13 | Self { inner: Default::default() } 14 | } 15 | 16 | pub fn fresh_data(&mut self, local_addr: SocketAddr, remote_addr: SocketAddr, data: Bytes) -> Vec { 17 | match self.inner.entry((local_addr, remote_addr)) { 18 | Entry::Occupied(mut occ) => { 19 | let buffer = occ.get_mut(); 20 | buffer.put(data); 21 | Self::split_data(buffer) 22 | } 23 | Entry::Vacant(vac) => { 24 | let mut buffer = BytesMut::with_capacity(10240); 25 | buffer.put(data); 26 | let vec = Self::split_data(&mut buffer); 27 | vac.insert(buffer); 28 | vec 29 | } 30 | } 31 | } 32 | const TCP_RTP_DATA_LEN: usize = 2; 33 | //tcp封装的Rtp包:2 bytes Data_len + N bytes Rtp_data(rtp_base_header_len = 12) 34 | const TCP_DATA_BASE_LEN: usize = 14; 35 | fn split_data(buffer: &mut BytesMut) -> Vec { 36 | let mut vec = Vec::new(); 37 | loop { 38 | let buffer_len = buffer.len(); 39 | if buffer_len < Self::TCP_DATA_BASE_LEN { 40 | break; 41 | } 42 | let split_len = buffer.get_u16() as usize + Self::TCP_RTP_DATA_LEN; 43 | if buffer_len < split_len { 44 | break; 45 | } 46 | let mut split_data = buffer.split_to(split_len); 47 | let rtp_data = split_data.split_off(Self::TCP_RTP_DATA_LEN).freeze(); 48 | vec.push(rtp_data); 49 | } 50 | vec 51 | } 52 | 53 | pub fn remove_map(&mut self, local_addr: SocketAddr, remote_addr: SocketAddr) { 54 | self.inner.remove(&(local_addr, remote_addr)); 55 | } 56 | } 57 | 58 | #[cfg(test)] 59 | mod test { 60 | use std::collections::VecDeque; 61 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; 62 | use common::bytes::{Buf, BytesMut}; 63 | 64 | #[test] 65 | fn test_deque_vec() { 66 | let mut d = VecDeque::new(); 67 | d.push_back(1); 68 | d.push_back(2); 69 | d.push_back(3); 70 | d.push_back(4); 71 | d.push_back(5); 72 | d.push_back(6); 73 | d.push_back(7); 74 | d.push_back(8); 75 | assert_eq!(d.pop_front(), Some(1)); 76 | d.push_back(1); 77 | assert_eq!(d.pop_front(), Some(2)); 78 | d.push_back(1); 79 | assert_eq!(d.pop_front(), Some(3)); 80 | d.push_back(1); 81 | d.insert(0, 444); 82 | assert_eq!(d.pop_front(), Some(444)); 83 | d.push_back(1); 84 | } 85 | 86 | #[test] 87 | fn test_socket_addr_to_string() { 88 | let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); 89 | println!("{}", socket.to_string()); 90 | } 91 | 92 | #[test] 93 | fn test_tcp_rtp_buffer() { 94 | let mut buffer = BytesMut::with_capacity(2048); 95 | buffer.extend_from_slice(&[0x00, 0x10]); // 长度字段:16 96 | buffer.extend_from_slice(&[0x90, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00]); // RTP 数据示例 97 | let data_len = buffer.get_u16() as usize; 98 | let rtp_data = buffer.split_to(data_len).freeze(); 99 | println!("{:02x?}", rtp_data.to_vec()); 100 | println!("buffer len: {}, data: {:02x?}", buffer.len(), buffer.to_vec()); 101 | } 102 | } -------------------------------------------------------------------------------- /stream/src/general/cfg.rs: -------------------------------------------------------------------------------- 1 | use common::cfg_lib::conf; 2 | use common::constructor::Get; 3 | use common::serde::Deserialize; 4 | use common::serde_default; 5 | use common::cfg_lib::conf::{CheckFromConf, FieldCheckError}; 6 | 7 | #[derive(Debug, Get, Clone, Deserialize)] 8 | #[serde(crate = "common::serde")] 9 | #[conf(prefix = "stream", check)] 10 | pub struct StreamConf { 11 | expires: i32, 12 | flv: bool, 13 | hls: bool, 14 | } 15 | serde_default!(default_expires, i32, 6); 16 | serde_default!(default_flv, bool, true); 17 | serde_default!(default_hls, bool, true); 18 | impl StreamConf { 19 | pub fn init_by_conf() -> Self { 20 | StreamConf::conf() 21 | } 22 | } 23 | 24 | impl CheckFromConf for StreamConf { 25 | fn _field_check(&self) -> Result<(), FieldCheckError> { 26 | if !self.hls && !self.flv { 27 | return Err(FieldCheckError::BizError("HLS/FLV未启用,请至少开启一个媒体输出".to_string())); 28 | } 29 | Ok(()) 30 | } 31 | } 32 | 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use common::cfg_lib::conf::init_cfg; 37 | use crate::general::cfg::StreamConf; 38 | 39 | // hls 与 flv: 都为false时,触发panic 40 | #[test] 41 | fn test_check_init_conf() { 42 | init_cfg("config.yml".to_string()); 43 | let cf: StreamConf = StreamConf::conf(); 44 | println!("{:?}", cf); 45 | } 46 | } -------------------------------------------------------------------------------- /stream/src/general/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod mode; 2 | pub mod util; 3 | pub mod cfg; -------------------------------------------------------------------------------- /stream/src/general/mode.rs: -------------------------------------------------------------------------------- 1 | use common::serde::{Deserialize, Serialize}; 2 | use common::bytes::Bytes; 3 | use common::cfg_lib::conf; 4 | use common::exception::{GlobalError, GlobalResult, TransError}; 5 | use common::log::{error, warn}; 6 | use common::constructor::{Get}; 7 | use common::serde_default; 8 | 9 | //统一响应超时:单位毫秒 10 | pub const TIME_OUT: u64 = 8000; 11 | pub const HALF_TIME_OUT: u64 = 4000; 12 | //数据通道缓存大小 13 | pub const BUFFER_SIZE: usize = 64; 14 | //API接口根信息 15 | pub const INDEX: &str = r#" 16 |