Repository: Monibuca/plugin-gb28181 Branch: v4 Commit: f00a5b11e9b3 Files: 23 Total size: 154.1 KB Directory structure: gitextract_ukye42pp/ ├── .gitignore ├── LICENSE ├── README.md ├── channel.go ├── const.go ├── device.go ├── go.mod ├── go.sum ├── handle.go ├── inviteoption.go ├── link.go ├── main.go ├── manscdp.go ├── portmanager.go ├── ptz.go ├── restful.go ├── server.go └── utils/ ├── buffer.go ├── bufferpool.go ├── log.go ├── rtp_sort.go ├── sip.go └── string.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules .vscode .idea ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # GB28181插件 该插件提供SIP server的服务,以及流媒体服务器能力,可以将NVR和摄像头的流抓到m7s中,可获取的设备的录像数据以及访问录像视频。也可以控制摄像头的旋转、缩放等。 ## 插件地址 github.com/Monibuca/plugin-gb28181 ## 插件引入 ```go import ( _ "m7s.live/plugin/gb28181/v4" ) ``` ## 默认插件配置 ```yaml gb28181: invitemode: 1 #0、手动invite 1、表示自动发起invite,当Server(SIP)接收到设备信息时,立即向设备发送invite命令获取流,2、按需拉流,既等待订阅者触发 position: autosubposition: false #是否自动订阅定位 expires: 3600s #订阅周期(单位:秒),默认3600 interval: 6s #订阅间隔(单位:秒),默认6 sipip: "" #sip服务器地址 默认 自动适配设备网段 serial: "34020000002000000001" realm: "3402000000" username: "" password: "" registervalidity: 60s #注册有效期 mediaip: "" #媒体服务器地址 默认 自动适配设备网段 port: sip: udp:5060 #sip服务器端口 media: tcp:58200-59200 #媒体服务器端口,用于接收设备的流 fdm: false #端口复用,单端口默认多路复用,多端口多路复用根据这个 removebaninterval: 10m #定时移除注册失败的设备黑名单,单位秒,默认10分钟(600秒) loglevel: info ``` **如果配置了端口范围(默认为范围端口),将采用范围端口机制,每一个流对应一个端口 **注意某些摄像机没有设置用户名的地方,摄像机会以自身的国标id作为用户名,这个时候m7s会忽略使用摄像机的用户名,忽略配置的用户名** 如果设备配置了错误的用户名和密码,连续三次上报错误后,m7s会记录设备id,并在10分钟内禁止设备注册 ## 插件功能 ### 使用SIP协议接受NVR或其他GB28181设备的注册 - 服务器启动时自动监听SIP协议端口,当有设备注册时,会记录该设备信息,可以从UI的列表中看到设备 - 定时发送Catalog命令查询设备的目录信息,可获得通道数据或者子设备 - 发送RecordInfo命令查询设备对录像数据 - 发送Invite命令获取设备的实时视频或者录像视频 - 发送PTZ命令来控制摄像头云台 - 自动同步设备位置 ### 作为GB28281的流媒体服务器接受设备的媒体流 - 当invite设备的**实时**视频流时,会在m7s中创建对应的流,StreamPath由设备编号和通道编号组成,即[设备编号]/[通道编号],如果有多个层级,通道编号是最后一个层级的编号 - 当invite设备的**录像**视频流时,StreamPath由设备编号和通道编号以及录像的起止时间拼接而成即[设备编号]/[通道编号]/[开始时间]-[结束时间] ## 接口API ### 罗列所有的gb28181协议的设备 `/gb28181/api/list` 设备的结构体如下 ```go type Device struct { ID string Name string Manufacturer string Model string Owner string RegisterTime time.Time UpdateTime time.Time LastKeepaliveAt time.Time Status string Channels []*Channel NetAddr string } ``` > 根据golang的规则,小写字母开头的变量不会被序列化 ### 从设备拉取视频流 `/gb28181/api/invite` | 参数名 | 必传 | 含义 | | --------- | ---- | ---------------------------- | | id | 是 | 设备ID | | channel | 是 | 通道编号 | | startTime | 否 | 开始时间(纯数字Unix时间戳) | | endTime | 否 | 结束时间(纯数字Unix时间戳) | 返回200代表成功, 304代表已经在拉取中,不能重复拉(仅仅针对直播流) ### 停止从设备拉流 `/gb28181/api/bye` | 参数名 | 必传 | 含义 | | ------- | ---- | -------- | | id | 是 | 设备ID | | channel | 是 | 通道编号 | http 200 表示成功,404流不存在 ### 发送控制命令 `/gb28181/api/control` | 参数名 | 必传 | 含义 | | ------- | ---- | ----------- | | id | 是 | 设备ID | | channel | 是 | 通道编号 | | ptzcmd | 是 | PTZ控制指令 | ### 查询录像 `/gb28181/api/records` | 参数名 | 必传 | 含义 | | --------- | ---- | -------------------------------------------- | | id | 是 | 设备ID | | channel | 是 | 通道编号 | | startTime | 否 | 开始时间(Unix时间戳) | | endTime | 否 | 结束时间(Unix时间戳) | ### 移动位置订阅 `/gb28181/api/position` | 参数名 | 必传 | 含义 | | -------- | ---- | -------------- | | id | 是 | 设备ID | | expires | 是 | 订阅周期(秒) | | interval | 是 | 订阅间隔(秒) | ### 预置位列表查询 `/gb28181/api/preset/list` | 参数名 | 必传 | 含义 | | -------- | ---- | -------------- | | id | 是 | 设备ID | | channel | 是 | 通道编号 | ### 预置位操作 `/gb28181/api/preset/control` | 参数名 | 必传 | 含义 | | -------- | ---- |---------------------| | id | 是 | 设备ID | | channel | 是 | 通道编号 | | cmd | 是 | 操作指令 0=新增,1=删除,2=调用 | | point | 是 | 预置点位1-255 | ================================================ FILE: channel.go ================================================ package gb28181 import ( "fmt" "net/http" "strconv" "strings" "time" "sync/atomic" "github.com/ghettovoice/gosip/sip" "github.com/goccy/go-json" "go.uber.org/zap" . "m7s.live/engine/v4" "m7s.live/engine/v4/log" "m7s.live/plugin/gb28181/v4/utils" "m7s.live/plugin/ps/v4" ) var QUERY_RECORD_TIMEOUT = time.Second * 5 type PullStream struct { opt *InviteOptions channel *Channel inviteRes sip.Response } func (p *PullStream) CreateRequest(method sip.RequestMethod) (req sip.Request) { res := p.inviteRes req = p.channel.CreateRequst(method) from, _ := res.From() to, _ := res.To() callId, _ := res.CallID() req.ReplaceHeaders(from.Name(), []sip.Header{from}) req.ReplaceHeaders(to.Name(), []sip.Header{to}) req.ReplaceHeaders(callId.Name(), []sip.Header{callId}) return } func (p *PullStream) Bye() int { req := p.CreateRequest(sip.BYE) resp, err := p.channel.Device.SipRequestForResponse(req) if p.opt.IsLive() { p.channel.State.Store(0) } if p.opt.recyclePort != nil { p.opt.recyclePort(p.opt.MediaPort) } if err != nil { return http.StatusInternalServerError } return int(resp.StatusCode()) } func (p *PullStream) info(body string) int { d := p.channel.Device req := p.CreateRequest(sip.INFO) contentType := sip.ContentType("Application/MANSRTSP") req.AppendHeader(&contentType) req.SetBody(body, true) resp, err := d.SipRequestForResponse(req) if err != nil { log.Warnf("Send info to stream error: %v, stream=%s, body=%s", err, p.opt.StreamPath, body) return getSipRespErrorCode(err) } return int(resp.StatusCode()) } // 暂停播放 func (p *PullStream) Pause() int { body := fmt.Sprintf(`PAUSE RTSP/1.0 CSeq: %d PauseTime: now `, p.channel.Device.SN) return p.info(body) } // 恢复播放 func (p *PullStream) Resume() int { d := p.channel.Device body := fmt.Sprintf(`PLAY RTSP/1.0 CSeq: %d Range: npt=now- `, d.SN) return p.info(body) } // 跳转到播放时间 // second: 相对于起始点调整到第 sec 秒播放 func (p *PullStream) PlayAt(second uint) int { d := p.channel.Device body := fmt.Sprintf(`PLAY RTSP/1.0 CSeq: %d Range: npt=%d- `, d.SN, second) return p.info(body) } // 快进/快退播放 // speed 取值: 0.25 0.5 1 2 4 或者其对应的负数表示倒放 func (p *PullStream) PlayForward(speed float32) int { d := p.channel.Device body := fmt.Sprintf(`PLAY RTSP/1.0 CSeq: %d Scale: %0.6f `, d.SN, speed) return p.info(body) } type Channel struct { Device *Device `json:"-" yaml:"-"` // 所属设备 State atomic.Int32 `json:"-" yaml:"-"` // 通道状态,0:空闲,1:正在invite,2:正在播放/对讲 LiveSubSP string // 实时子码流,通过rtsp GpsTime time.Time // gps时间 Longitude string // 经度 Latitude string // 纬度 *log.Logger `json:"-" yaml:"-"` ChannelInfo } type PresetInfo struct { PresetID int `json:"-" yaml:"-"` // PresetName string `json:"-" yaml:"-"` // } func (c *Channel) MarshalJSON() ([]byte, error) { m := map[string]any{ "DeviceID": c.DeviceID, "ParentID": c.ParentID, "Name": c.Name, "Manufacturer": c.Manufacturer, "Model": c.Model, "Owner": c.Owner, "CivilCode": c.CivilCode, "Address": c.Address, "Port": c.Port, "Parental": c.Parental, "SafetyWay": c.SafetyWay, "RegisterWay": c.RegisterWay, "Secrecy": c.Secrecy, "Status": c.Status, "Longitude": c.Longitude, "Latitude": c.Latitude, "GpsTime": c.GpsTime, "LiveSubSP": c.LiveSubSP, "LiveStatus": c.State.Load(), } return json.Marshal(m) } // Channel 通道 type ChannelInfo struct { DeviceID string // 通道ID ParentID string Name string Manufacturer string Model string Owner string CivilCode string Address string Port int Parental int SafetyWay int RegisterWay int Secrecy int Status ChannelStatus } type ChannelStatus string const ( ChannelOnStatus = "ON" ChannelOffStatus = "OFF" ) func (channel *Channel) CreateRequst(Method sip.RequestMethod) (req sip.Request) { d := channel.Device d.SN++ callId := sip.CallID(utils.RandNumString(10)) userAgent := sip.UserAgentHeader("Monibuca") maxForwards := sip.MaxForwards(70) //增加max-forwards为默认值 70 cseq := sip.CSeq{ SeqNo: uint32(d.SN), MethodName: Method, } port := sip.Port(conf.SipPort) serverAddr := sip.Address{ //DisplayName: sip.String{Str: d.serverConfig.Serial}, Uri: &sip.SipUri{ FUser: sip.String{Str: conf.Serial}, FHost: d.SipIP, FPort: &port, }, Params: sip.NewParams().Add("tag", sip.String{Str: utils.RandNumString(9)}), } //非同一域的目标地址需要使用@host host := conf.Realm if channel.DeviceID[0:10] != host { if channel.Port != 0 { deviceIp := d.NetAddr deviceIp = deviceIp[0:strings.LastIndex(deviceIp, ":")] host = fmt.Sprintf("%s:%d", deviceIp, channel.Port) } else { host = d.NetAddr } } channelAddr := sip.Address{ //DisplayName: sip.String{Str: d.serverConfig.Serial}, Uri: &sip.SipUri{FUser: sip.String{Str: channel.DeviceID}, FHost: host}, } req = sip.NewRequest( "", Method, channelAddr.Uri, "SIP/2.0", []sip.Header{ serverAddr.AsFromHeader(), channelAddr.AsToHeader(), &callId, &userAgent, &cseq, &maxForwards, serverAddr.AsContactHeader(), }, "", nil, ) req.SetTransport(conf.SipNetwork) req.SetDestination(d.NetAddr) return req } func (channel *Channel) QueryRecord(startTime, endTime string) ([]*Record, error) { d := channel.Device request := d.CreateRequest(sip.MESSAGE) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) // body := fmt.Sprintf(` // // RecordInfo // %d // %s // %s // %s // 0 // all // `, d.sn, channel.DeviceID, startTime, endTime) start, _ := strconv.ParseInt(startTime, 10, 0) end, _ := strconv.ParseInt(endTime, 10, 0) body := BuildRecordInfoXML(d.SN, channel.DeviceID, start, end) request.SetBody(body, true) resultCh := RecordQueryLink.WaitResult(d.ID, channel.DeviceID, d.SN, QUERY_RECORD_TIMEOUT) resp, err := d.SipRequestForResponse(request) if err != nil { return nil, fmt.Errorf("query error: %s", err) } if resp.StatusCode() != http.StatusOK { return nil, fmt.Errorf("query error, status=%d", resp.StatusCode()) } // RecordQueryLink 中加了超时机制,该结果一定会返回 // 所以此处不用再增加超时等保护机制 r := <-resultCh return r.list, r.err } func (channel *Channel) QueryPresetList() (sip.Response, error) { d := channel.Device request := d.CreateRequest(sip.MESSAGE) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) body := BuildPresetListXML(100, channel.DeviceID) request.SetBody(body, true) resp, err := d.SipRequestForResponse(request) if err != nil { return nil, fmt.Errorf("query error: %s", err) } if resp.StatusCode() != http.StatusOK { return nil, fmt.Errorf("query error, status=%d", resp.StatusCode()) } return resp, nil } func (channel *Channel) PresetControl(ptzCode int, point byte) int { cmd := byte(PresetSet) switch ptzCode { case PresetAddPoint: cmd = PresetSet case PresetDelPoint: cmd = PresetDel case PresetCallPoint: cmd = PresetCall default: } PTZCmd := Pack(cmd, point) return channel.Control(PTZCmd) } func (channel *Channel) Control(PTZCmd string) int { d := channel.Device request := d.CreateRequest(sip.MESSAGE) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) body := fmt.Sprintf(` DeviceControl %d %s %s `, d.SN, channel.DeviceID, PTZCmd) request.SetBody(body, true) resp, err := d.SipRequestForResponse(request) if err != nil { return http.StatusRequestTimeout } return int(resp.StatusCode()) } // Invite 发送Invite报文 invites a channel to play // 注意里面的锁保证不同时发送invite报文,该锁由channel持有 /*** f字段: f = v/编码格式/分辨率/帧率/码率类型/码率大小a/编码格式/码率大小/采样率 各项具体含义: v:后续参数为视频的参数;各参数间以 “/”分割; 编码格式:十进制整数字符串表示 1 –MPEG-4 2 –H.264 3 – SVAC 4 –3GP 分辨率:十进制整数字符串表示 1 – QCIF 2 – CIF 3 – 4CIF 4 – D1 5 –720P 6 –1080P/I 帧率:十进制整数字符串表示 0~99 码率类型:十进制整数字符串表示 1 – 固定码率(CBR) 2 – 可变码率(VBR) 码率大小:十进制整数字符串表示 0~100000(如 1表示1kbps) a:后续参数为音频的参数;各参数间以 “/”分割; 编码格式:十进制整数字符串表示 1 – G.711 2 – G.723.1 3 – G.729 4 – G.722.1 码率大小:十进制整数字符串 音频编码码率: 1 — 5.3 kbps (注:G.723.1中使用) 2 — 6.3 kbps (注:G.723.1中使用) 3 — 8 kbps (注:G.729中使用) 4 — 16 kbps (注:G.722.1中使用) 5 — 24 kbps (注:G.722.1中使用) 6 — 32 kbps (注:G.722.1中使用) 7 — 48 kbps (注:G.722.1中使用) 8 — 64 kbps(注:G.711中使用) 采样率:十进制整数字符串表示 1 — 8 kHz(注:G.711/ G.723.1/ G.729中使用) 2—14 kHz(注:G.722.1中使用) 3—16 kHz(注:G.722.1中使用) 4—32 kHz(注:G.722.1中使用) 注1:字符串说明 本节中使用的“十进制整数字符串”的含义为“0”~“4294967296” 之间的十进制数字字符串。 注2:参数分割标识 各参数间以“/”分割,参数间的分割符“/”不能省略; 若两个分割符 “/”间的某参数为空时(即两个分割符 “/”直接将相连时)表示无该参数值; 注3:f字段说明 使用f字段时,应保证视频和音频参数的结构完整性,即在任何时候,f字段的结构都应是完整的结构: f = v/编码格式/分辨率/帧率/码率类型/码率大小a/编码格式/码率大小/采样率 若只有视频时,音频中的各参数项可以不填写,但应保持 “a///”的结构: f = v/编码格式/分辨率/帧率/码率类型/码率大小a/// 若只有音频时也类似处理,视频中的各参数项可以不填写,但应保持 “v/”的结构: f = v/a/编码格式/码率大小/采样率 f字段中视、音频参数段之间不需空格分割。 可使用f字段中的分辨率参数标识同一设备不同分辨率的码流。 */ func (channel *Channel) Invite(opt *InviteOptions) (code int, err error) { if opt.IsLive() { if !channel.State.CompareAndSwap(0, 1) { return 304, nil } defer func() { if err != nil { GB28181Plugin.Error("InviteRetryInit", zap.Error(err)) channel.State.Store(0) if conf.InviteMode == 1 { // 5秒后重试 time.AfterFunc(time.Second*5, func() { channel.Invite(opt) }) } } else { channel.State.Store(2) } }() } d := channel.Device streamPath := fmt.Sprintf("%s/%s", d.ID, channel.DeviceID) s := "Play" opt.CreateSSRC() if opt.Record() { s = "Playback" streamPath = fmt.Sprintf("%s/%s/%d-%d", d.ID, channel.DeviceID, opt.Start, opt.End) } if opt.StreamPath != "" { streamPath = opt.StreamPath } else if channel.DeviceID == "" { streamPath = "gb28181/" + d.ID } else { opt.StreamPath = streamPath } if opt.dump == "" { opt.dump = conf.DumpPath } protocol := "" networkType := "udp" // 根据配置文件判断是否多路复用 reusePort := conf.Port.Fdm if conf.IsMediaNetworkTCP() { networkType = "tcp" protocol = "TCP/" if conf.tcpPorts.Valid { opt.MediaPort, err = conf.tcpPorts.GetPort() opt.recyclePort = conf.tcpPorts.Recycle } } else { if conf.udpPorts.Valid { opt.MediaPort, err = conf.udpPorts.GetPort() opt.recyclePort = conf.udpPorts.Recycle } } if err != nil { return http.StatusInternalServerError, err } if opt.MediaPort == 0 { opt.MediaPort = conf.MediaPort // 单端口默认多路复用 reusePort = true } sdpInfo := []string{ "v=0", fmt.Sprintf("o=%s 0 0 IN IP4 %s", channel.DeviceID, d.MediaIP), "s=" + s, "u=" + channel.DeviceID + ":0", "c=IN IP4 " + d.MediaIP, opt.String(), fmt.Sprintf("m=video %d %sRTP/AVP 96", opt.MediaPort, protocol), "a=recvonly", "a=rtpmap:96 PS/90000", } if conf.IsMediaNetworkTCP() { sdpInfo = append(sdpInfo, "a=setup:passive", "a=connection:new") } sdpInfo = append(sdpInfo, "y="+opt.ssrc) invite := channel.CreateRequst(sip.INVITE) contentType := sip.ContentType("application/sdp") invite.AppendHeader(&contentType) invite.SetBody(strings.Join(sdpInfo, "\r\n")+"\r\n", true) subject := sip.GenericHeader{ HeaderName: "Subject", Contents: fmt.Sprintf("%s:%s,%s:0", channel.DeviceID, opt.ssrc, conf.Serial), } invite.AppendHeader(&subject) inviteRes, err := d.SipRequestForResponse(invite) if err != nil { if opt.recyclePort != nil { opt.recyclePort(opt.MediaPort) } channel.Error("inviteRequestError", zap.Error(err), zap.String("msg", invite.String())) return http.StatusInternalServerError, err } code = int(inviteRes.StatusCode()) channel.Info("invite response", zap.Int("status code", code)) if code == http.StatusOK { ds := strings.Split(inviteRes.Body(), "\r\n") for _, l := range ds { if ls := strings.Split(l, "="); len(ls) > 1 { if ls[0] == "y" && len(ls[1]) > 0 { if _ssrc, err := strconv.ParseInt(ls[1], 10, 0); err == nil { opt.SSRC = uint32(_ssrc) } else { channel.Error("read invite response y ", zap.Error(err)) } // break } if ls[0] == "m" && len(ls[1]) > 0 { netinfo := strings.Split(ls[1], " ") if strings.ToUpper(netinfo[2]) == "TCP/RTP/AVP" { channel.Debug("Device support tcp") } else { channel.Debug("Device not support tcp") networkType = "udp" } } } } var psPuber ps.PSPublisher err = psPuber.Receive(streamPath, opt.dump, fmt.Sprintf("%s:%d", networkType, opt.MediaPort), opt.SSRC, reusePort) if err != nil { if opt.recyclePort != nil { opt.recyclePort(opt.MediaPort) } channel.Error("inviteTcpCreateError", zap.Error(err)) return http.StatusInternalServerError, err } if !opt.IsLive() { // 10秒无数据关闭 if psPuber.Stream.DelayCloseTimeout == 0 { psPuber.Stream.DelayCloseTimeout = time.Second * 10 } if psPuber.Stream.IdleTimeout == 0 { psPuber.Stream.IdleTimeout = time.Second * 10 } } PullStreams.Store(streamPath, &PullStream{ opt: opt, channel: channel, inviteRes: inviteRes, }) err = srv.Send(sip.NewAckRequest("", invite, inviteRes, "", nil)) } else { if opt.recyclePort != nil { opt.recyclePort(opt.MediaPort) } } return } func (channel *Channel) Bye(streamPath string) int { d := channel.Device if streamPath == "" { streamPath = fmt.Sprintf("%s/%s", d.ID, channel.DeviceID) } if s, loaded := PullStreams.LoadAndDelete(streamPath); loaded { s.(*PullStream).Bye() if s := Streams.Get(streamPath); s != nil { s.Close() } return http.StatusOK } return http.StatusNotFound } func (channel *Channel) Pause(streamPath string) int { if s, loaded := PullStreams.Load(streamPath); loaded { r := s.(*PullStream).Pause() if s := Streams.Get(streamPath); s != nil { s.Pause() } return r } return http.StatusNotFound } func (channel *Channel) Resume(streamPath string) int { if s, loaded := PullStreams.Load(streamPath); loaded { r := s.(*PullStream).Resume() if s := Streams.Get(streamPath); s != nil { s.Resume() } return r } return http.StatusNotFound } func (channel *Channel) PlayAt(streamPath string, second uint) int { if s, loaded := PullStreams.Load(streamPath); loaded { r := s.(*PullStream).PlayAt(second) if s := Streams.Get(streamPath); s != nil { s.Resume() } return r } return http.StatusNotFound } func (channel *Channel) PlayForward(streamPath string, speed float32) int { if s, loaded := PullStreams.Load(streamPath); loaded { return s.(*PullStream).PlayForward(speed) } if s := Streams.Get(streamPath); s != nil { s.Resume() } return http.StatusNotFound } func (channel *Channel) TryAutoInvite(opt *InviteOptions) { condition := !opt.IsLive() || channel.CanInvite() channel.Debug("TryAutoInvite", zap.Any("opt", opt), zap.Bool("condition", condition)) if condition { go channel.Invite(opt) } } func (channel *Channel) CanInvite() bool { if channel.State.Load() != 0 || len(channel.DeviceID) != 20 || channel.Status == ChannelOffStatus { return false } if conf.InviteIDs == "" { return true } // 11~13位是设备类型编码 typeID := channel.DeviceID[10:13] // format: start-end,type1,type2 tokens := strings.Split(conf.InviteIDs, ",") for _, tok := range tokens { if first, second, ok := strings.Cut(tok, "-"); ok { if typeID >= first && typeID <= second { return true } } else { if typeID == first { return true } } } return false } func getSipRespErrorCode(err error) int { if re, ok := err.(*sip.RequestError); ok { return int(re.Code) } else { return http.StatusInternalServerError } } ================================================ FILE: const.go ================================================ package gb28181 var reasons = map[int]string{ 100: "Trying", 180: "Ringing", 181: "Call Is Being Forwarded", 182: "Queued", 183: "Session Progress", 200: "OK", 202: "Accepted", 300: "Multiple Choices", 301: "Moved Permanently", 302: "Moved Temporarily", 305: "Use Proxy", 380: "Alternative Service", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 410: "Gone", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Unsupported URI Scheme", 420: "Bad Extension", 421: "Extension Required", 423: "Interval Too Brief", 480: "Temporarily Unavailable", 481: "Call transaction Does Not Exist", 482: "Loop Detected", 483: "Too Many Hops", 484: "Address Incomplete", 485: "Ambiguous", 486: "Busy Here", 487: "Request Terminated", 488: "Not Acceptable Here", 489: "Bad Event", 491: "Request Pending", 493: "Undecipherable", 500: "Server Internal Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Server Tim", 505: "Version Not Supported", 513: "message Too Large", 600: "Busy Everywhere", 603: "Decline", 604: "Does Not Exist Anywhere", 606: "SESSION NOT ACCEPTABLE", } func Explain(statusCode int) string { return reasons[statusCode] } const ( INVIDE_MODE_MANUAL = iota INVIDE_MODE_AUTO INVIDE_MODE_ONSUBSCRIBE ) ================================================ FILE: device.go ================================================ package gb28181 import ( "context" "encoding/json" "fmt" "net/http" "os" "strings" "sync" "time" "go.uber.org/zap" "m7s.live/engine/v4" "m7s.live/engine/v4/log" "m7s.live/plugin/gb28181/v4/utils" "github.com/ghettovoice/gosip/sip" myip "github.com/husanpao/ip" ) const TIME_LAYOUT = "2006-01-02T15:04:05" // Record 录像 type Record struct { DeviceID string Name string FilePath string Address string StartTime string EndTime string Secrecy int Type string } func (r *Record) GetPublishStreamPath() string { return fmt.Sprintf("%s/%s", r.DeviceID, r.StartTime) } var ( Devices sync.Map DeviceNonce sync.Map //保存nonce防止设备伪造 DeviceRegisterCount sync.Map //设备注册次数 ) type DeviceStatus string const ( DeviceRegisterStatus = "REGISTER" DeviceRecoverStatus = "RECOVER" DeviceOnlineStatus = "ONLINE" DeviceOfflineStatus = "OFFLINE" DeviceAlarmedStatus = "ALARMED" ) type Device struct { ID string Name string Manufacturer string Model string Owner string RegisterTime time.Time UpdateTime time.Time LastKeepaliveAt time.Time Status DeviceStatus SN int Addr sip.Address `json:"-" yaml:"-"` SipIP string //设备对应网卡的服务器ip MediaIP string //设备对应网卡的服务器ip NetAddr string channelMap sync.Map subscriber struct { CallID string Timeout time.Time } lastSyncTime time.Time GpsTime time.Time //gps时间 Longitude string //经度 Latitude string //纬度 *log.Logger `json:"-" yaml:"-"` } func (d *Device) MarshalJSON() ([]byte, error) { type Alias Device data := &struct { Channels []*Channel *Alias }{ Alias: (*Alias)(d), } d.channelMap.Range(func(key, value interface{}) bool { data.Channels = append(data.Channels, value.(*Channel)) return true }) return json.Marshal(data) } func (c *GB28181Config) RecoverDevice(d *Device, req sip.Request) { from, _ := req.From() d.Addr = sip.Address{ DisplayName: from.DisplayName, Uri: from.Address, } deviceIp := req.Source() servIp := req.Recipient().Host() //根据网卡ip获取对应的公网ip sipIP := c.routes[servIp] //如果相等,则服务器是内网通道.海康摄像头不支持...自动获取 if strings.LastIndex(deviceIp, ".") != -1 && strings.LastIndex(servIp, ".") != -1 { if servIp[0:strings.LastIndex(servIp, ".")] == deviceIp[0:strings.LastIndex(deviceIp, ".")] || sipIP == "" { sipIP = servIp } } //如果用户配置过则使用配置的 if c.SipIP != "" { sipIP = c.SipIP } else if sipIP == "" { sipIP = myip.InternalIPv4() } mediaIp := sipIP if c.MediaIP != "" { mediaIp = c.MediaIP } d.Info("RecoverDevice", zap.String("deviceIp", deviceIp), zap.String("servIp", servIp), zap.String("sipIP", sipIP), zap.String("mediaIp", mediaIp)) d.Status = DeviceRegisterStatus d.SipIP = sipIP d.MediaIP = mediaIp d.NetAddr = deviceIp d.UpdateTime = time.Now() } func (c *GB28181Config) StoreDevice(id string, req sip.Request) (d *Device) { from, _ := req.From() deviceAddr := sip.Address{ DisplayName: from.DisplayName, Uri: from.Address, } deviceIp := req.Source() if _d, loaded := Devices.Load(id); loaded { d = _d.(*Device) d.UpdateTime = time.Now() d.NetAddr = deviceIp d.Addr = deviceAddr d.Debug("UpdateDevice", zap.String("netaddr", d.NetAddr)) } else { servIp := req.Recipient().Host() //根据网卡ip获取对应的公网ip sipIP := c.routes[servIp] //如果相等,则服务器是内网通道.海康摄像头不支持...自动获取 if strings.LastIndex(deviceIp, ".") != -1 && strings.LastIndex(servIp, ".") != -1 { if servIp[0:strings.LastIndex(servIp, ".")] == deviceIp[0:strings.LastIndex(deviceIp, ".")] || sipIP == "" { sipIP = servIp } } //如果用户配置过则使用配置的 if c.SipIP != "" { sipIP = c.SipIP } else if sipIP == "" { sipIP = myip.InternalIPv4() } mediaIp := sipIP if c.MediaIP != "" { mediaIp = c.MediaIP } d = &Device{ ID: id, RegisterTime: time.Now(), UpdateTime: time.Now(), Status: DeviceRegisterStatus, Addr: deviceAddr, SipIP: sipIP, MediaIP: mediaIp, NetAddr: deviceIp, Logger: GB28181Plugin.With(zap.String("id", id)), } d.Info("StoreDevice", zap.String("deviceIp", deviceIp), zap.String("servIp", servIp), zap.String("sipIP", sipIP), zap.String("mediaIp", mediaIp)) Devices.Store(id, d) c.SaveDevices() } return } func (c *GB28181Config) ReadDevices() { if f, err := os.OpenFile("devices.json", os.O_RDONLY, 0644); err == nil { defer f.Close() var items []*Device if err = json.NewDecoder(f).Decode(&items); err == nil { for _, item := range items { if time.Since(item.UpdateTime) < conf.RegisterValidity { item.Status = "RECOVER" item.Logger = GB28181Plugin.With(zap.String("id", item.ID)) Devices.Store(item.ID, item) } } } } } func (c *GB28181Config) SaveDevices() { var item []any Devices.Range(func(key, value any) bool { item = append(item, value) return true }) if f, err := os.OpenFile("devices.json", os.O_WRONLY|os.O_CREATE, 0644); err == nil { defer f.Close() encoder := json.NewEncoder(f) encoder.SetIndent("", " ") encoder.Encode(item) } } func (d *Device) addOrUpdateChannel(info ChannelInfo) (c *Channel) { if old, ok := d.channelMap.Load(info.DeviceID); ok { c = old.(*Channel) c.ChannelInfo = info } else { c = &Channel{ Device: d, ChannelInfo: info, Logger: d.Logger.With(zap.String("channel", info.DeviceID)), } if s := engine.Streams.Get(fmt.Sprintf("%s/%s/rtsp", c.Device.ID, c.DeviceID)); s != nil { c.LiveSubSP = s.Path } else { c.LiveSubSP = "" } d.channelMap.Store(info.DeviceID, c) } return } func (d *Device) deleteChannel(DeviceID string) { d.channelMap.Delete(DeviceID) } func (d *Device) UpdateChannels(list ...ChannelInfo) { for _, c := range list { if _, ok := conf.ignores[c.DeviceID]; ok { continue } //当父设备非空且存在时、父设备节点增加通道 if c.ParentID != "" { path := strings.Split(c.ParentID, "/") parentId := path[len(path)-1] //如果父ID并非本身所属设备,一般情况下这是因为下级设备上传了目录信息,该信息通常不需要处理。 // 暂时不考虑级联目录的实现 if d.ID != parentId { if v, ok := Devices.Load(parentId); ok { parent := v.(*Device) parent.addOrUpdateChannel(c) continue } else { c.Model = "Directory " + c.Model c.Status = "NoParent" } } } //本设备增加通道 channel := d.addOrUpdateChannel(c) if conf.InviteMode == INVIDE_MODE_AUTO { channel.TryAutoInvite(&InviteOptions{}) } if s := engine.Streams.Get("sub/" + c.DeviceID); s != nil { channel.LiveSubSP = s.Path } else { channel.LiveSubSP = "" } } } func (d *Device) CreateRequest(Method sip.RequestMethod) (req sip.Request) { d.SN++ callId := sip.CallID(utils.RandNumString(10)) userAgent := sip.UserAgentHeader("Monibuca") maxForwards := sip.MaxForwards(70) //增加max-forwards为默认值 70 cseq := sip.CSeq{ SeqNo: uint32(d.SN), MethodName: Method, } port := sip.Port(conf.SipPort) serverAddr := sip.Address{ //DisplayName: sip.String{Str: d.config.Serial}, Uri: &sip.SipUri{ FUser: sip.String{Str: conf.Serial}, FHost: d.SipIP, FPort: &port, }, Params: sip.NewParams().Add("tag", sip.String{Str: utils.RandNumString(9)}), } req = sip.NewRequest( "", Method, d.Addr.Uri, "SIP/2.0", []sip.Header{ serverAddr.AsFromHeader(), d.Addr.AsToHeader(), &callId, &userAgent, &cseq, &maxForwards, serverAddr.AsContactHeader(), }, "", nil, ) req.SetTransport(conf.SipNetwork) req.SetDestination(d.NetAddr) //fmt.Printf("构建请求参数:%s", *&req) // requestMsg.DestAdd, err2 = d.ResolveAddress(requestMsg) // if err2 != nil { // return nil // } //intranet ip , let's resolve it with public ip // var deviceIp, deviceSourceIP net.IP // switch addr := requestMsg.DestAdd.(type) { // case *net.UDPAddr: // deviceIp = addr.IP // case *net.TCPAddr: // deviceIp = addr.IP // } // switch addr2 := d.SourceAddr.(type) { // case *net.UDPAddr: // deviceSourceIP = addr2.IP // case *net.TCPAddr: // deviceSourceIP = addr2.IP // } // if deviceIp.IsPrivate() && !deviceSourceIP.IsPrivate() { // requestMsg.DestAdd = d.SourceAddr // } return } func (d *Device) Subscribe() int { request := d.CreateRequest(sip.SUBSCRIBE) if d.subscriber.CallID != "" { callId := sip.CallID(utils.RandNumString(10)) request.AppendHeader(&callId) } expires := sip.Expires(3600) d.subscriber.Timeout = time.Now().Add(time.Second * time.Duration(expires)) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) request.AppendHeader(&expires) request.SetBody(BuildCatalogXML(d.SN, d.ID), true) response, err := d.SipRequestForResponse(request) if err == nil && response != nil { if response.StatusCode() == http.StatusOK { callId, _ := request.CallID() d.subscriber.CallID = string(*callId) } else { d.subscriber.CallID = "" } return int(response.StatusCode()) } return http.StatusRequestTimeout } func (d *Device) Catalog() int { //os.Stdout.Write(debug.Stack()) request := d.CreateRequest(sip.MESSAGE) expires := sip.Expires(3600) d.subscriber.Timeout = time.Now().Add(time.Second * time.Duration(expires)) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) request.AppendHeader(&expires) request.SetBody(BuildCatalogXML(d.SN, d.ID), true) // 输出Sip请求设备通道信息信令 GB28181Plugin.Sugar().Debugf("SIP->Catalog:%s", request) resp, err := d.SipRequestForResponse(request) if err == nil && resp != nil { GB28181Plugin.Sugar().Debugf("SIP<-Catalog Response: %s", resp.String()) return int(resp.StatusCode()) } else if err != nil { GB28181Plugin.Error("SIP<-Catalog error:", zap.Error(err)) } return http.StatusRequestTimeout } func (d *Device) QueryDeviceInfo() { for i := time.Duration(5); i < 100; i++ { time.Sleep(time.Second * i) request := d.CreateRequest(sip.MESSAGE) contentType := sip.ContentType("Application/MANSCDP+xml") request.AppendHeader(&contentType) request.SetBody(BuildDeviceInfoXML(d.SN, d.ID), true) response, _ := d.SipRequestForResponse(request) if response != nil { // via, _ := response.ViaHop() // if via != nil && via.Params.Has("received") { // received, _ := via.Params.Get("received") // d.SipIP = received.String() // } d.Info("QueryDeviceInfo", zap.Uint16("status code", uint16(response.StatusCode()))) if response.StatusCode() == http.StatusOK { break } } } } func (d *Device) SipRequestForResponse(request sip.Request) (sip.Response, error) { return srv.RequestWithContext(context.Background(), request) } // MobilePositionSubscribe 移动位置订阅 func (d *Device) MobilePositionSubscribe(id string, expires time.Duration, interval time.Duration) (code int) { mobilePosition := d.CreateRequest(sip.SUBSCRIBE) if d.subscriber.CallID != "" { callId := sip.CallID(utils.RandNumString(10)) mobilePosition.ReplaceHeaders(callId.Name(), []sip.Header{&callId}) } expiresHeader := sip.Expires(expires / time.Second) d.subscriber.Timeout = time.Now().Add(expires) contentType := sip.ContentType("Application/MANSCDP+xml") mobilePosition.AppendHeader(&contentType) mobilePosition.AppendHeader(&expiresHeader) mobilePosition.SetBody(BuildDevicePositionXML(d.SN, id, int(interval/time.Second)), true) response, err := d.SipRequestForResponse(mobilePosition) if err == nil && response != nil { if response.StatusCode() == http.StatusOK { callId, _ := mobilePosition.CallID() d.subscriber.CallID = callId.String() } else { d.subscriber.CallID = "" } return int(response.StatusCode()) } return http.StatusRequestTimeout } // UpdateChannelPosition 更新通道GPS坐标 func (d *Device) UpdateChannelPosition(channelId string, gpsTime string, lng string, lat string) { if v, ok := d.channelMap.Load(channelId); ok { c := v.(*Channel) c.GpsTime = time.Now() //时间取系统收到的时间,避免设备时间和格式问题 c.Longitude = lng c.Latitude = lat c.Debug("update channel position success") } else { //如果未找到通道,则更新到设备上 d.GpsTime = time.Now() //时间取系统收到的时间,避免设备时间和格式问题 d.Longitude = lng d.Latitude = lat d.Debug("update device position success", zap.String("channelId", channelId)) } } // UpdateChannelStatus 目录订阅消息处理:新增/移除/更新通道或者更改通道状态 func (d *Device) UpdateChannelStatus(deviceList []*notifyMessage) { for _, v := range deviceList { switch v.Event { case "ON": d.Debug("receive channel online notify") d.channelOnline(v.DeviceID) case "OFF": d.Debug("receive channel offline notify") d.channelOffline(v.DeviceID) case "VLOST": d.Debug("receive channel video lost notify") d.channelOffline(v.DeviceID) case "DEFECT": d.Debug("receive channel video defect notify") d.channelOffline(v.DeviceID) case "ADD": d.Debug("receive channel add notify") channel := ChannelInfo{ DeviceID: v.DeviceID, ParentID: v.ParentID, Name: v.Name, Manufacturer: v.Manufacturer, Model: v.Model, Owner: v.Owner, CivilCode: v.CivilCode, Address: v.Address, Port: v.Port, Parental: v.Parental, SafetyWay: v.SafetyWay, RegisterWay: v.RegisterWay, Secrecy: v.Secrecy, Status: ChannelStatus(v.Status), } d.addOrUpdateChannel(channel) case "DEL": //删除 d.Debug("receive channel delete notify") d.deleteChannel(v.DeviceID) case "UPDATE": d.Debug("receive channel update notify") // 更新通道 channel := ChannelInfo{ DeviceID: v.DeviceID, ParentID: v.ParentID, Name: v.Name, Manufacturer: v.Manufacturer, Model: v.Model, Owner: v.Owner, CivilCode: v.CivilCode, Address: v.Address, Port: v.Port, Parental: v.Parental, SafetyWay: v.SafetyWay, RegisterWay: v.RegisterWay, Secrecy: v.Secrecy, Status: ChannelStatus(v.Status), } d.UpdateChannels(channel) } } } func (d *Device) channelOnline(DeviceID string) { if v, ok := d.channelMap.Load(DeviceID); ok { c := v.(*Channel) c.Status = ChannelOnStatus c.Debug("channel online", zap.String("channelId", DeviceID)) } else { d.Debug("update channel status failed, not found", zap.String("channelId", DeviceID)) } } func (d *Device) channelOffline(DeviceID string) { if v, ok := d.channelMap.Load(DeviceID); ok { c := v.(*Channel) c.Status = ChannelOffStatus c.Debug("channel offline", zap.String("channelId", DeviceID)) } else { d.Debug("update channel status failed, not found", zap.String("channelId", DeviceID)) } } ================================================ FILE: go.mod ================================================ module m7s.live/plugin/gb28181/v4 go 1.19 require ( github.com/ghettovoice/gosip v0.0.0-20231227123312-6b80e2d3e6f7 github.com/goccy/go-json v0.10.2 github.com/husanpao/ip v0.0.0-20220711082147-73160bb611a8 github.com/logrusorgru/aurora/v4 v4.0.0 github.com/pion/rtp v1.8.3 go.uber.org/zap v1.26.0 golang.org/x/net v0.19.0 golang.org/x/text v0.14.0 m7s.live/engine/v4 v4.15.2 m7s.live/plugin/ps/v4 v4.1.3 ) require ( github.com/bluenviron/gortsplib/v4 v4.6.2 // indirect github.com/bluenviron/mediacommon v1.5.1 // indirect github.com/deepch/vdk v0.0.27 // indirect github.com/denisbrodbeck/machineid v1.0.1 // indirect github.com/discoviking/fsm v0.0.0-20150126104936-f4a273feecca // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/gobwas/httphead v0.1.0 // indirect github.com/gobwas/pool v0.2.1 // indirect github.com/gobwas/ws v1.3.1 // indirect github.com/golang/mock v1.6.0 // indirect github.com/google/pprof v0.0.0-20230912144702-c363fe2c2ed8 // indirect github.com/google/uuid v1.4.0 // indirect github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.19 // indirect github.com/mcuadros/go-defaults v1.2.0 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/onsi/ginkgo/v2 v2.12.1 // indirect github.com/pion/randutil v0.1.0 // indirect github.com/pion/webrtc/v3 v3.2.20 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect github.com/q191201771/naza v0.30.48 // indirect github.com/quic-go/qtls-go1-20 v0.3.3 // indirect github.com/quic-go/quic-go v0.38.1 // indirect github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b // indirect github.com/shirou/gopsutil/v3 v3.23.8 // indirect github.com/shoenig/go-m1cpu v0.1.6 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/tevino/abool v1.2.0 // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect github.com/x-cray/logrus-prefixed-formatter v0.5.2 // indirect github.com/yapingcat/gomedia v0.0.0-20230905155010-55b9713fcec1 // indirect github.com/yusufpapurcu/wmi v1.2.3 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/crypto v0.16.0 // indirect golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect golang.org/x/mod v0.12.0 // indirect golang.org/x/sync v0.3.0 // indirect golang.org/x/sys v0.15.0 // indirect golang.org/x/term v0.15.0 // indirect golang.org/x/tools v0.13.0 // indirect google.golang.org/protobuf v1.31.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: go.sum ================================================ github.com/bluenviron/gortsplib/v4 v4.6.2 h1:CGIsxpnUFvSlIxnSFS0oFSSfwsHMmBCmYcrGAtIcwXc= github.com/bluenviron/gortsplib/v4 v4.6.2/go.mod h1:dN1YjyPNMfy/NwC17Ga6MiIMiUoQfg5GL7LGsVHa0Jo= github.com/bluenviron/mediacommon v1.5.1 h1:yYVF+ebqZOJh8yH+EeuPcAtTmWR66BqbJGmStxkScoI= github.com/bluenviron/mediacommon v1.5.1/go.mod h1:Ij/kE1LEucSjryNBVTyPL/gBI0d6/Css3f5PyrM957w= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/deepch/vdk v0.0.27 h1:j/SHaTiZhA47wRpaue8NRp7P9xwOOO/lunxrDJBwcao= github.com/deepch/vdk v0.0.27/go.mod h1:JlgGyR2ld6+xOIHa7XAxJh+stSDBAkdNvIPkUIdIywk= github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ= github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI= github.com/discoviking/fsm v0.0.0-20150126104936-f4a273feecca h1:cTTdXpkQ1aVbOOmHwdwtYuwUZcQtcMrleD1UXLWhAq8= github.com/discoviking/fsm v0.0.0-20150126104936-f4a273feecca/go.mod h1:W+3LQaEkN8qAwwcw0KC546sUEnX86GIT8CcMLZC4mG0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/ghettovoice/gosip v0.0.0-20231227123312-6b80e2d3e6f7 h1:2ENInMa9XHho+1mUM8RZMZomAnfz+qR5v6AS0+TrM8w= github.com/ghettovoice/gosip v0.0.0-20231227123312-6b80e2d3e6f7/go.mod h1:rlD1yLOErWYohWTryG/2bTTpmzB79p52ntLA/uIFXeI= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.1.0-rc.1/go.mod h1:nzvNcVha5eUziGrbxFCo6qFIojQHjJV5cLYIbezhfL0= github.com/gobwas/ws v1.3.1 h1:Qi34dfLMWJbiKaNbDVzM9x27nZBjmkaW6i4+Ku+pGVU= github.com/gobwas/ws v1.3.1/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/pprof v0.0.0-20230912144702-c363fe2c2ed8 h1:gpptm606MZYGaMHMsB4Srmb6EbW/IVHnt04rcMXnkBQ= github.com/google/pprof v0.0.0-20230912144702-c363fe2c2ed8/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/husanpao/ip v0.0.0-20220711082147-73160bb611a8 h1:4Jk58quTZmzJcTrLlbB5L1Q6qXu49EIjCReWxcBFWKo= github.com/husanpao/ip v0.0.0-20220711082147-73160bb611a8/go.mod h1:medl9/CfYoQlqAXtAARmMW5dAX2UOdwwkhaszYPk0AM= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/logrusorgru/aurora/v4 v4.0.0 h1:sRjfPpun/63iADiSvGGjgA1cAYegEWMPCJdUpJYn9JA= github.com/logrusorgru/aurora/v4 v4.0.0/go.mod h1:lP0iIa2nrnT/qoFXcOZSrZQpJ1o6n2CUf/hyHi2Q4ZQ= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a h1:N9zuLhTvBSRt0gWSiJswwQ2HqDmtX/ZCDJURnKUt1Ik= github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a/go.mod h1:JKx41uQRwqlTZabZc+kILPrO/3jlKnQ2Z8b7YiVw5cE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mcuadros/go-defaults v1.2.0 h1:FODb8WSf0uGaY8elWJAkoLL0Ri6AlZ1bFlenk56oZtc= github.com/mcuadros/go-defaults v1.2.0/go.mod h1:WEZtHEVIGYVDqkKSWBdWKUVdRyKlMfulPaGDWIVeCWY= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.5/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.12.1 h1:uHNEO1RP2SpuZApSkel9nEh1/Mu+hmQe7Q+Pepg5OYA= github.com/onsi/ginkgo/v2 v2.12.1/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.4/go.mod h1:g/HbgYopi++010VEqkFgJHKC09uJiW9UkXvMUuKHUCQ= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/pion/datachannel v1.5.5/go.mod h1:iMz+lECmfdCMqFRhXhcA/219B0SQlbpoR2V118yimL0= github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= github.com/pion/ice/v2 v2.3.11/go.mod h1:hPcLC3kxMa+JGRzMHqQzjoSj3xtE9F+eoncmXLlCL4E= github.com/pion/interceptor v0.1.18/go.mod h1:tpvvF4cPM6NGxFA1DUMbhabzQBxdWMATDGEUYOR9x6I= github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= github.com/pion/mdns v0.0.8/go.mod h1:hYE72WX8WDveIhg7fmXgMKivD3Puklk0Ymzog0lSyaI= github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= github.com/pion/rtcp v1.2.10/go.mod h1:ztfEwXZNLGyF1oQDttz/ZKIBaeeg/oWbRYqzBM9TL1I= github.com/pion/rtp v1.8.1/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= github.com/pion/rtp v1.8.3 h1:VEHxqzSVQxCkKDSHro5/4IUUG1ea+MFdqR2R3xSpNU8= github.com/pion/rtp v1.8.3/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= github.com/pion/sctp v1.8.5/go.mod h1:SUFFfDpViyKejTAdwD1d/HQsCu+V/40cCs2nZIvC3s0= github.com/pion/sctp v1.8.8/go.mod h1:igF9nZBrjh5AtmKc7U30jXltsFHicFCXSmWA2GWRaWs= github.com/pion/sdp/v3 v3.0.6/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw= github.com/pion/srtp/v2 v2.0.17/go.mod h1:y5WSHcJY4YfNB/5r7ca5YjHeIr1H3LM1rKArGGs8jMc= github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8= github.com/pion/transport v0.14.1/go.mod h1:4tGmbk00NeYA3rUa9+n+dzCCoKkcy3YlYb99Jn2fNnI= github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= github.com/pion/transport/v2 v2.2.2/go.mod h1:OJg3ojoBJopjEeECq2yJdXH9YVrUJ1uQ++NjXLOUorc= github.com/pion/transport/v2 v2.2.3/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= github.com/pion/turn/v2 v2.1.3/go.mod h1:huEpByKKHix2/b9kmTAM3YoX6MKP+/D//0ClgUYR2fY= github.com/pion/webrtc/v3 v3.2.20 h1:BQJiXQsJq9LgLp3op7rLy1y8d2WD+LtiS9cpY0uQ22A= github.com/pion/webrtc/v3 v3.2.20/go.mod h1:vVURQTBOG5BpWKOJz3nlr23NfTDeyKVmubRNqzQp+Tg= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig= github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/q191201771/naza v0.30.48 h1:lbYUaa7A15kJKYwOiU4AbFS1Zo8oQwppl2tLEbJTqnw= github.com/q191201771/naza v0.30.48/go.mod h1:n+dpJjQSh90PxBwxBNuifOwQttywvSIN5TkWSSYCeBk= github.com/quic-go/qtls-go1-20 v0.3.3 h1:17/glZSLI9P9fDAeyCHBFSWSqJcwx1byhLwP5eUIDCM= github.com/quic-go/qtls-go1-20 v0.3.3/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k= github.com/quic-go/quic-go v0.38.1 h1:M36YWA5dEhEeT+slOu/SwMEucbYd0YFidxG3KlGPZaE= github.com/quic-go/quic-go v0.38.1/go.mod h1:ijnZM7JsFIkp4cRyjxJNIzdSfCLmUMg9wdyhGmg+SN4= github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b h1:gQZ0qzfKHQIybLANtM3mBXNUtOfsCFXeTsnBqCsx1KM= github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE= github.com/shirou/gopsutil/v3 v3.23.8/go.mod h1:7hmCaBn+2ZwaZOr6jmPBZDfawwMGuo1id3C6aM8EDqQ= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tevino/abool v0.0.0-20170917061928-9b9efcf221b5/go.mod h1:f1SCnEOt6sc3fOJfPQDRDzHOtSXuTtnz0ImG9kPRDV0= github.com/tevino/abool v1.2.0 h1:heAkClL8H6w+mK5md9dzsuohKeXHUpY7Vw0ZCKW+huA= github.com/tevino/abool v1.2.0/go.mod h1:qc66Pna1RiIsPa7O4Egxxs9OqkuxDX55zznh9K07Tzg= github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= github.com/x-cray/logrus-prefixed-formatter v0.5.2 h1:00txxvfBM9muc0jiLIEAkAcIMJzfthRT6usrui8uGmg= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= github.com/yapingcat/gomedia v0.0.0-20230905155010-55b9713fcec1 h1:ilNIuDBR+UKA3qefiyWRoFufIFn3E4tgEXbBM4ILH28= github.com/yapingcat/gomedia v0.0.0-20230905155010-55b9713fcec1/go.mod h1:WSZ59bidJOO40JSJmLqlkBJrjZCtjbKKkygEMfzY/kc= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw= github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ= golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201207223542-d4d67f95c62d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo= golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= m7s.live/engine/v4 v4.15.2 h1:Uws658Ict2B8JojBG7fNmd2G2i63MlomsQ4npgNzF3g= m7s.live/engine/v4 v4.15.2/go.mod h1:uKxjmsjU1WARUNowEkP83BSrJMUjGwkJrX5nPi6DGmE= m7s.live/plugin/ps/v4 v4.1.3 h1:Lbvu3ZlX/s3w9lcOwF0SCOCvxtxongPexCIn6x4yukw= m7s.live/plugin/ps/v4 v4.1.3/go.mod h1:RAb507iNmPG43I5kUA6ewF1fTRHDRsKbIVkIdLdKeeI= ================================================ FILE: handle.go ================================================ package gb28181 import ( "bytes" "crypto/md5" "encoding/xml" "fmt" "strconv" "github.com/ghettovoice/gosip/sip" "go.uber.org/zap" . "m7s.live/engine/v4" "m7s.live/plugin/gb28181/v4/utils" "net/http" "time" "golang.org/x/net/html/charset" ) type Authorization struct { *sip.Authorization } func (a *Authorization) Verify(username, passwd, realm, nonce string) bool { //1、将 username,realm,password 依次组合获取 1 个字符串,并用算法加密的到密文 r1 s1 := fmt.Sprintf("%s:%s:%s", username, realm, passwd) r1 := a.getDigest(s1) //2、将 method,即REGISTER ,uri 依次组合获取 1 个字符串,并对这个字符串使用算法 加密得到密文 r2 s2 := fmt.Sprintf("REGISTER:%s", a.Uri()) r2 := a.getDigest(s2) if r1 == "" || r2 == "" { GB28181Plugin.Error("Authorization algorithm wrong") return false } //3、将密文 1,nonce 和密文 2 依次组合获取 1 个字符串,并对这个字符串使用算法加密,获得密文 r3,即Response s3 := fmt.Sprintf("%s:%s:%s", r1, nonce, r2) r3 := a.getDigest(s3) //4、计算服务端和客户端上报的是否相等 return r3 == a.Response() } func (a *Authorization) getDigest(raw string) string { switch a.Algorithm() { case "MD5": return fmt.Sprintf("%x", md5.Sum([]byte(raw))) default: //如果没有算法,默认使用MD5 return fmt.Sprintf("%x", md5.Sum([]byte(raw))) } } func (c *GB28181Config) OnRegister(req sip.Request, tx sip.ServerTransaction) { from, ok := req.From() if !ok || from.Address == nil || from.Address.User() == nil { GB28181Plugin.Error("OnRegister", zap.String("error", "no id")) return } id := from.Address.User().String() GB28181Plugin.Debug("SIP<-OnMessage", zap.String("id", id), zap.String("source", req.Source()), zap.String("req", req.String())) isUnregister := false if exps := req.GetHeaders("Expires"); len(exps) > 0 { exp := exps[0] expSec, err := strconv.ParseInt(exp.Value(), 10, 32) if err != nil { GB28181Plugin.Info("OnRegister", zap.String("error", fmt.Sprintf("wrong expire header value %q", exp)), zap.String("id", id), zap.String("source", req.Source()), zap.String("destination", req.Destination())) return } if expSec == 0 { isUnregister = true } } else { GB28181Plugin.Info("OnRegister", zap.String("error", "has no expire header"), zap.String("id", id), zap.String("source", req.Source()), zap.String("destination", req.Destination())) return } GB28181Plugin.Info("OnRegister", zap.Bool("isUnregister", isUnregister), zap.String("id", id), zap.String("source", req.Source()), zap.String("destination", req.Destination())) if len(id) != 20 { GB28181Plugin.Info("Wrong GB-28181", zap.String("id", id)) return } passAuth := false // 不需要密码情况 if c.Username == "" && c.Password == "" { passAuth = true } else { // 需要密码情况 设备第一次上报,返回401和加密算法 if hdrs := req.GetHeaders("Authorization"); len(hdrs) > 0 { authenticateHeader := hdrs[0].(*sip.GenericHeader) auth := &Authorization{sip.AuthFromValue(authenticateHeader.Contents)} // 有些摄像头没有配置用户名的地方,用户名就是摄像头自己的国标id var username string if auth.Username() == id { username = id } else { username = c.Username } if dc, ok := DeviceRegisterCount.LoadOrStore(id, 1); ok && dc.(int) > MaxRegisterCount { response := sip.NewResponseFromRequest("", req, http.StatusForbidden, "Forbidden", "") tx.Respond(response) return } else { // 设备第二次上报,校验 _nonce, loaded := DeviceNonce.Load(id) if loaded && auth.Verify(username, c.Password, c.Realm, _nonce.(string)) { passAuth = true } else { DeviceRegisterCount.Store(id, dc.(int)+1) } } } } if passAuth { var d *Device if isUnregister { tmpd, ok := Devices.LoadAndDelete(id) if ok { GB28181Plugin.Info("Unregister Device", zap.String("id", id)) d = tmpd.(*Device) } else { return } } else { if v, ok := Devices.Load(id); ok { d = v.(*Device) c.RecoverDevice(d, req) } else { d = c.StoreDevice(id, req) } } DeviceNonce.Delete(id) DeviceRegisterCount.Delete(id) resp := sip.NewResponseFromRequest("", req, http.StatusOK, "OK", "") to, _ := resp.To() resp.ReplaceHeaders("To", []sip.Header{&sip.ToHeader{Address: to.Address, Params: sip.NewParams().Add("tag", sip.String{Str: utils.RandNumString(9)})}}) resp.RemoveHeader("Allow") expires := sip.Expires(3600) resp.AppendHeader(&expires) resp.AppendHeader(&sip.GenericHeader{ HeaderName: "Date", Contents: time.Now().Format(TIME_LAYOUT), }) _ = tx.Respond(resp) if !isUnregister { //订阅设备更新 go d.syncChannels() } } else { GB28181Plugin.Info("OnRegister unauthorized", zap.String("id", id), zap.String("source", req.Source()), zap.String("destination", req.Destination())) response := sip.NewResponseFromRequest("", req, http.StatusUnauthorized, "Unauthorized", "") _nonce, _ := DeviceNonce.LoadOrStore(id, utils.RandNumString(32)) auth := fmt.Sprintf( `Digest realm="%s",algorithm=%s,nonce="%s"`, c.Realm, "MD5", _nonce.(string), ) response.AppendHeader(&sip.GenericHeader{ HeaderName: "WWW-Authenticate", Contents: auth, }) _ = tx.Respond(response) } } // syncChannels // 同步设备信息、下属通道信息,包括主动查询通道信息,订阅通道变化情况 func (d *Device) syncChannels() { if time.Since(d.lastSyncTime) > 2*conf.HeartbeatInterval { d.lastSyncTime = time.Now() d.Catalog() d.Subscribe() d.QueryDeviceInfo() } } type MessageEvent struct { Type string Device *Device } func (c *GB28181Config) OnMessage(req sip.Request, tx sip.ServerTransaction) { from, ok := req.From() if !ok || from.Address == nil || from.Address.User() == nil { GB28181Plugin.Error("OnMessage", zap.String("error", "no id")) return } id := from.Address.User().String() GB28181Plugin.Debug("SIP<-OnMessage", zap.String("id", id), zap.String("source", req.Source()), zap.String("req", req.String())) if v, ok := Devices.Load(id); ok { d := v.(*Device) switch d.Status { case DeviceOfflineStatus, DeviceRecoverStatus: c.RecoverDevice(d, req) go d.syncChannels() case DeviceRegisterStatus: d.Status = DeviceOnlineStatus } d.UpdateTime = time.Now() temp := &struct { XMLName xml.Name CmdType string SN int // 请求序列号,一般用于对应 request 和 response DeviceID string DeviceName string Manufacturer string Model string Channel string DeviceList []ChannelInfo `xml:"DeviceList>Item"` RecordList []*Record `xml:"RecordList>Item"` SumNum int // 录像结果的总数 SumNum,录像结果会按照多条消息返回,可用于判断是否全部返回 }{} decoder := xml.NewDecoder(bytes.NewReader([]byte(req.Body()))) decoder.CharsetReader = charset.NewReaderLabel err := decoder.Decode(temp) if err != nil { err = utils.DecodeGbk(temp, []byte(req.Body())) if err != nil { GB28181Plugin.Error("decode catelog err", zap.Error(err)) } } var body string switch temp.CmdType { case "Keepalive": d.LastKeepaliveAt = time.Now() //callID !="" 说明是订阅的事件类型信息 if d.lastSyncTime.IsZero() { go d.syncChannels() } else { d.channelMap.Range(func(key, value interface{}) bool { if conf.InviteMode == INVIDE_MODE_AUTO { value.(*Channel).TryAutoInvite(&InviteOptions{}) } return true }) } //在KeepLive 进行位置订阅的处理,如果开启了自动订阅位置,则去订阅位置 if c.Position.AutosubPosition && time.Since(d.GpsTime) > c.Position.Interval*2 { d.MobilePositionSubscribe(d.ID, c.Position.Expires, c.Position.Interval) GB28181Plugin.Debug("Mobile Position Subscribe", zap.String("deviceID", d.ID)) } case "Catalog": d.UpdateChannels(temp.DeviceList...) case "RecordInfo": RecordQueryLink.Put(d.ID, temp.DeviceID, temp.SN, temp.SumNum, temp.RecordList) case "DeviceInfo": // 主设备信息 d.Name = temp.DeviceName d.Manufacturer = temp.Manufacturer d.Model = temp.Model case "Alarm": d.Status = DeviceAlarmedStatus body = BuildAlarmResponseXML(d.ID) case "Broadcast": GB28181Plugin.Info("broadcast message", zap.String("body", req.Body())) case "PresetQuery": GB28181Plugin.Info("PresetQuery message", zap.String("body", req.Body())) default: d.Warn("Not supported CmdType", zap.String("CmdType", temp.CmdType), zap.String("body", req.Body())) response := sip.NewResponseFromRequest("", req, http.StatusBadRequest, "", "") tx.Respond(response) return } EmitEvent(MessageEvent{ Type: temp.CmdType, Device: d, }) tx.Respond(sip.NewResponseFromRequest("", req, http.StatusOK, "OK", body)) } else { GB28181Plugin.Debug("Unauthorized message, device not found", zap.String("id", id)) } } func (c *GB28181Config) OnBye(req sip.Request, tx sip.ServerTransaction) { tx.Respond(sip.NewResponseFromRequest("", req, http.StatusOK, "OK", "")) } type NotifyEvent MessageEvent // OnNotify 订阅通知处理 func (c *GB28181Config) OnNotify(req sip.Request, tx sip.ServerTransaction) { from, ok := req.From() if !ok || from.Address == nil || from.Address.User() == nil { GB28181Plugin.Error("OnMessage", zap.String("error", "no id")) return } id := from.Address.User().String() if v, ok := Devices.Load(id); ok { d := v.(*Device) d.UpdateTime = time.Now() temp := &struct { XMLName xml.Name CmdType string DeviceID string Time string //位置订阅-GPS时间 Longitude string //位置订阅-经度 Latitude string //位置订阅-维度 // Speed string //位置订阅-速度(km/h)(可选) // Direction string //位置订阅-方向(取值为当前摄像头方向与正北方的顺时针夹角,取值范围0°~360°,单位:°)(可选) // Altitude string //位置订阅-海拔高度,单位:m(可选) DeviceList []*notifyMessage `xml:"DeviceList>Item"` //目录订阅 }{} decoder := xml.NewDecoder(bytes.NewReader([]byte(req.Body()))) decoder.CharsetReader = charset.NewReaderLabel err := decoder.Decode(temp) if err != nil { err = utils.DecodeGbk(temp, []byte(req.Body())) if err != nil { GB28181Plugin.Error("decode catelog err", zap.Error(err)) } } var body string switch temp.CmdType { case "Catalog": //目录状态 d.UpdateChannelStatus(temp.DeviceList) case "MobilePosition": //更新channel的坐标 d.UpdateChannelPosition(temp.DeviceID, temp.Time, temp.Longitude, temp.Latitude) case "Alarm": d.Status = DeviceAlarmedStatus default: d.Warn("Not supported CmdType", zap.String("CmdType", temp.CmdType), zap.String("body", req.Body())) response := sip.NewResponseFromRequest("", req, http.StatusBadRequest, "", "") tx.Respond(response) return } EmitEvent(NotifyEvent{ Type: temp.CmdType, Device: d}) tx.Respond(sip.NewResponseFromRequest("", req, http.StatusOK, "OK", body)) } } type notifyMessage struct { DeviceID string ParentID string Name string Manufacturer string Model string Owner string CivilCode string Address string Port int Parental int SafetyWay int RegisterWay int Secrecy int Status string //状态改变事件 ON:上线,OFF:离线,VLOST:视频丢失,DEFECT:故障,ADD:增加,DEL:删除,UPDATE:更新(必选) Event string } ================================================ FILE: inviteoption.go ================================================ package gb28181 import ( "errors" "fmt" "math/rand" "strconv" ) type InviteOptions struct { Start int End int dump string ssrc string SSRC uint32 MediaPort uint16 StreamPath string recyclePort func(p uint16) (err error) } func (o InviteOptions) IsLive() bool { return o.Start == 0 || o.End == 0 } func (o InviteOptions) Record() bool { return !o.IsLive() } func (o *InviteOptions) Validate(start, end string) error { if start != "" { sint, err1 := strconv.ParseInt(start, 10, 0) if err1 != nil { return err1 } o.Start = int(sint) } if end != "" { eint, err2 := strconv.ParseInt(end, 10, 0) if err2 != nil { return err2 } o.End = int(eint) } if o.Start >= o.End { return errors.New("start < end") } return nil } func (o InviteOptions) String() string { return fmt.Sprintf("t=%d %d", o.Start, o.End) } func (o *InviteOptions) CreateSSRC() { ssrc := make([]byte, 10) if o.IsLive() { ssrc[0] = '0' } else { ssrc[0] = '1' } copy(ssrc[1:6], conf.Serial[3:8]) randNum := 1000 + rand.Intn(8999) copy(ssrc[6:], strconv.Itoa(randNum)) o.ssrc = string(ssrc) _ssrc, _ := strconv.ParseInt(o.ssrc, 10, 0) o.SSRC = uint32(_ssrc) } ================================================ FILE: link.go ================================================ package gb28181 import ( "fmt" "sync" "time" "go.uber.org/zap" ) // 对于录像查询,通过 queryKey (即 deviceId + channelId + sn) 唯一区分一次请求和响应 // 并将其关联起来,以实现异步响应的目的 // 提供单例实例供调用 var RecordQueryLink = NewRecordQueryLink(time.Second * 60) type recordQueryLink struct { pendingResult map[string]recordQueryResult // queryKey 查询结果缓存 pendingResp map[string]recordQueryResp // queryKey 待回复的查询请求 timeout time.Duration // 查询结果的过期时间 sync.RWMutex } type recordQueryResult struct { time time.Time err error sum int finished bool list []*Record } type recordQueryResp struct { respChan chan<- recordQueryResult timeout time.Duration startTime time.Time } func NewRecordQueryLink(resultTimeout time.Duration) *recordQueryLink { c := &recordQueryLink{ timeout: resultTimeout, pendingResult: make(map[string]recordQueryResult), pendingResp: make(map[string]recordQueryResp), } return c } // 唯一区分一次录像查询 func recordQueryKey(deviceId, channelId string, sn int) string { return fmt.Sprintf("%s-%s-%d", deviceId, channelId, sn) } // 定期清理过期的查询结果和请求 func (c *recordQueryLink) cleanTimeout() { for k, s := range c.pendingResp { if time.Since(s.startTime) > s.timeout { if r, ok := c.pendingResult[k]; ok { c.notify(k, r) } else { c.notify(k, recordQueryResult{err: fmt.Errorf("query time out")}) } } } for k, r := range c.pendingResult { if time.Since(r.time) > c.timeout { delete(c.pendingResult, k) } } } func (c *recordQueryLink) Put(deviceId, channelId string, sn int, sum int, record []*Record) { key, r := c.doPut(deviceId, channelId, sn, sum, record) if r.finished { c.notify(key, r) } } func (c *recordQueryLink) doPut(deviceId, channelId string, sn, sum int, record []*Record) (key string, r recordQueryResult) { c.Lock() defer c.Unlock() key = recordQueryKey(deviceId, channelId, sn) if v, ok := c.pendingResult[key]; ok { r = v } else { r = recordQueryResult{time: time.Now(), sum: sum, list: make([]*Record, 0)} } r.list = append(r.list, record...) if len(r.list) == sum { r.finished = true } c.pendingResult[key] = r GB28181Plugin.Logger.Debug("put record", zap.String("key", key), zap.Int("sum", sum), zap.Int("count", len(r.list))) return } func (c *recordQueryLink) WaitResult( deviceId, channelId string, sn int, timeout time.Duration) (resultCh <-chan recordQueryResult) { key := recordQueryKey(deviceId, channelId, sn) c.Lock() defer c.Unlock() respCh := make(chan recordQueryResult, 1) resultCh = respCh c.pendingResp[key] = recordQueryResp{startTime: time.Now(), timeout: timeout, respChan: respCh} return } func (c *recordQueryLink) notify(key string, r recordQueryResult) { if s, ok := c.pendingResp[key]; ok { s.respChan <- r } c.Lock() defer c.Unlock() delete(c.pendingResp, key) delete(c.pendingResult, key) GB28181Plugin.Logger.Debug("record notify", zap.String("key", key)) } ================================================ FILE: main.go ================================================ package gb28181 import ( "os" "strings" "sync" "time" "github.com/ghettovoice/gosip/sip" myip "github.com/husanpao/ip" "go.uber.org/zap" . "m7s.live/engine/v4" "m7s.live/engine/v4/util" ) type GB28181PositionConfig struct { AutosubPosition bool `desc:"是否自动订阅定位"` //是否自动订阅定位 Expires time.Duration `default:"3600s" desc:"订阅周期"` //订阅周期 Interval time.Duration `default:"6s" desc:"订阅间隔"` //订阅间隔 } type GB28181Config struct { InviteMode int `default:"1" desc:"拉流模式" enum:"0:手动拉流,1:预拉流,2:按需拉流"` //邀请模式,0:手动拉流,1:预拉流,2:按需拉流 InviteIDs string `default:"131,132" desc:"允许邀请的设备类型( 11~13位是设备类型编码),逗号分割"` //按照国标gb28181协议允许邀请的设备类型:132 摄像机 NVR ListenAddr string `default:"0.0.0.0" desc:"监听IP地址"` //监听地址 //sip服务器的配置 SipNetwork string `default:"udp" desc:"废弃,请使用 Port"` //传输协议,默认UDP,可选TCP SipIP string `desc:"sip 服务IP地址"` //sip 服务器公网IP SipPort sip.Port `default:"5060" desc:"废弃,请使用 Port"` //sip 服务器端口,默认 5060 Serial string `default:"34020000002000000001" desc:"sip 服务 id"` //sip 服务器 id, 默认 34020000002000000001 Realm string `default:"3402000000" desc:"sip 服务域"` //sip 服务器域,默认 3402000000 Username string `desc:"sip 服务账号"` //sip 服务器账号 Password string `desc:"sip 服务密码"` //sip 服务器密码 Port struct { // 新配置方式 Sip string `default:"udp:5060" desc:"sip服务端口号"` Media string `default:"tcp:58200-59200" desc:"媒体服务端口号"` Fdm bool `default:"false" desc:"多路复用"` } RegisterValidity time.Duration `default:"3600s" desc:"注册有效期"` //注册有效期,单位秒,默认 3600 HeartbeatInterval time.Duration `default:"60s" desc:"心跳间隔"` //心跳间隔,单位秒,默认 60 //媒体服务器配置 MediaIP string `desc:"媒体服务IP地址"` //媒体服务器地址 MediaPort uint16 `default:"58200" desc:"废弃,请使用 Port"` //媒体服务器端口 MediaNetwork string `default:"tcp" desc:"废弃,请使用 Port"` //媒体传输协议,默认UDP,可选TCP MediaPortMin uint16 `default:"58200" desc:"废弃,请使用 Port"` MediaPortMax uint16 `default:"59200" desc:"废弃,请使用 Port"` RemoveBanInterval time.Duration `default:"600s" desc:"移除禁止设备间隔"` //移除禁止设备间隔 routes map[string]string DumpPath string `desc:"dump PS流本地文件路径"` //dump PS流本地文件路径 Ignores []string `desc:"忽略的设备ID"` //忽略的设备ID ignores map[string]struct{} tcpPorts PortManager udpPorts PortManager Position GB28181PositionConfig //关于定位的配置参数 } var SipUri *sip.SipUri func (c *GB28181Config) initRoutes() { c.routes = make(map[string]string) tempIps := myip.LocalAndInternalIPs() for k, v := range tempIps { c.routes[k] = v if lastdot := strings.LastIndex(k, "."); lastdot >= 0 { c.routes[k[0:lastdot]] = k } } GB28181Plugin.Info("LocalAndInternalIPs", zap.Any("routes", c.routes)) } func (c *GB28181Config) OnEvent(event any) { switch e := event.(type) { case FirstConfig: if c.Port.Sip != "udp:5060" { protocol, ports := util.Conf2Listener(c.Port.Sip) c.SipNetwork = protocol c.SipPort = sip.Port(ports[0]) } if c.Port.Media != "tcp:58200-59200" { protocol, ports := util.Conf2Listener(c.Port.Media) c.MediaNetwork = protocol if len(ports) > 1 { c.MediaPortMin = ports[0] c.MediaPortMax = ports[1] } else { c.MediaPortMin = 0 c.MediaPortMax = 0 c.MediaPort = ports[0] } } if len(c.Ignores) > 0 { c.ignores = make(map[string]struct{}) for _, v := range c.Ignores { c.ignores[v] = util.Null } } os.MkdirAll(c.DumpPath, 0766) c.ReadDevices() SipUri = &sip.SipUri{ FUser: sip.String{Str: c.Serial}, FHost: c.SipIP, FPort: &conf.SipPort, } go c.initRoutes() c.startServer() case InvitePublish: if c.InviteMode == INVIDE_MODE_ONSUBSCRIBE { //流可能是回放流,stream path是device/channel/start-end形式 streamNames := strings.Split(e.Target, "/") if channel := FindChannel(streamNames[0], streamNames[1]); channel != nil { opt := InviteOptions{} if len(streamNames) > 2 { last := len(streamNames) - 1 timestr := streamNames[last] trange := strings.Split(timestr, "-") if len(trange) == 2 { startTime := trange[0] endTime := trange[1] opt.Validate(startTime, endTime) } } channel.TryAutoInvite(&opt) } } case SEpublish: if channel := FindChannel(e.Target.AppName, strings.TrimSuffix(e.Target.StreamName, "/rtsp")); channel != nil { channel.LiveSubSP = e.Target.Path } case SEclose: if channel := FindChannel(e.Target.AppName, strings.TrimSuffix(e.Target.StreamName, "/rtsp")); channel != nil { channel.LiveSubSP = "" } if v, ok := PullStreams.LoadAndDelete(e.Target.Path); ok { go v.(*PullStream).Bye() } } } func (c *GB28181Config) IsMediaNetworkTCP() bool { return strings.ToLower(c.MediaNetwork) == "tcp" } var conf GB28181Config var GB28181Plugin = InstallPlugin(&conf) var PullStreams sync.Map //拉流 ================================================ FILE: manscdp.go ================================================ package gb28181 import ( "encoding/xml" "fmt" "strconv" "time" ) var ( // 获取预置位列表 PresentListXML = ` PresetQuery %d %s ` // CatalogXML 获取设备列表xml样式 CatalogXML = ` Catalog %d %s ` // RecordInfoXML 获取录像文件列表xml样式 RecordInfoXML = ` RecordInfo %d %s %s %s 0 all ` // DeviceInfoXML 查询设备详情xml样式 DeviceInfoXML = ` DeviceInfo %d %s ` // DevicePositionXML 订阅设备位置 DevicePositionXML = ` MobilePosition %d %s %d ` ) func intTotime(t int64) time.Time { tstr := strconv.FormatInt(t, 10) if len(tstr) == 10 { return time.Unix(t, 0) } if len(tstr) == 13 { return time.UnixMilli(t) } return time.Now() } // BuildDeviceInfoXML 获取设备详情指令 func BuildDeviceInfoXML(sn int, id string) string { return fmt.Sprintf(DeviceInfoXML, sn, id) } // BuildCatalogXML 获取NVR下设备列表指令 func BuildCatalogXML(sn int, id string) string { return fmt.Sprintf(CatalogXML, sn, id) } func BuildPresetListXML(sn int, id string) string { return fmt.Sprintf(PresentListXML, sn, id) } // BuildRecordInfoXML 获取录像文件列表指令 func BuildRecordInfoXML(sn int, id string, start, end int64) string { return fmt.Sprintf(RecordInfoXML, sn, id, intTotime(start).Format("2006-01-02T15:04:05"), intTotime(end).Format("2006-01-02T15:04:05")) } // BuildDevicePositionXML 订阅设备位置 func BuildDevicePositionXML(sn int, id string, interval int) string { return fmt.Sprintf(DevicePositionXML, sn, id, interval) } // AlarmResponseXML alarm response xml样式 var ( AlarmResponseXML = ` Alarm 17430 %s ` ) // BuildRecordInfoXML 获取录像文件列表指令 func BuildAlarmResponseXML(id string) string { return fmt.Sprintf(AlarmResponseXML, id) } func XmlEncode(v interface{}) (string, error) { xmlData, err := xml.MarshalIndent(v, "", " ") if err != nil { return "", err } xml := string(xmlData) xml = `` + "\n" + xml + "\n" return xml, err } ================================================ FILE: portmanager.go ================================================ package gb28181 import ( "errors" ) var ErrNoAvailablePorts = errors.New("no available ports") type PortManager struct { recycle chan uint16 start uint16 max uint16 pos uint16 Valid bool } func (pm *PortManager) Init(start, end uint16) { pm.start = start pm.pos = start - 1 pm.max = end if pm.pos > 0 && pm.max > pm.pos { pm.Valid = true pm.recycle = make(chan uint16, pm.Range()) } } func (pm *PortManager) Range() uint16 { return pm.max - pm.pos } func (pm *PortManager) Recycle(p uint16) (err error) { select { case pm.recycle <- p: return nil default: return ErrNoAvailablePorts } } func (pm *PortManager) GetPort() (p uint16, err error) { select { case p = <-pm.recycle: return default: if pm.Range() > 0 { pm.pos++ p = pm.pos return } else { if conf.Port.Fdm == false { return 0, ErrNoAvailablePorts } pm.pos = pm.start - 1 p = pm.pos return } } } ================================================ FILE: ptz.go ================================================ package gb28181 import ( "encoding/hex" "encoding/xml" "fmt" ) var ( name2code = map[string]uint8{ "stop": 0, "right": 1, "left": 2, "down": 4, "downright": 5, "downleft": 6, "up": 8, "upright": 9, "upleft": 10, "zoomin": 16, "zoomout": 32, } ) type PresetCmd byte const ( PresetAddPoint = 0 PresetDelPoint = 1 PresetCallPoint = 2 ) const DeviceControl = "DeviceControl" const PTZFirstByte = 0xA5 const ( PresetSet = 0x81 PresetCall = 0x82 PresetDel = 0x83 ) type MessagePtz struct { XMLName xml.Name `xml:"Control"` CmdType string `xml:"CmdType"` SN int `xml:"SN"` DeviceID string `xml:"DeviceID"` PTZCmd string `xml:"PTZCmd"` } type Preset struct { CMD byte Point byte } func toPtzStrByCmdName(cmdName string, horizontalSpeed, verticalSpeed, zoomSpeed uint8) (string, error) { c, err := toPtzCode(cmdName) if err != nil { return "", err } return toPtzStr(c, horizontalSpeed, verticalSpeed, zoomSpeed), nil } func toPtzStr(cmdCode, horizontalSpeed, verticalSpeed, zoomSpeed uint8) string { checkCode := uint16(0xA5+0x0F+0x01+cmdCode+horizontalSpeed+verticalSpeed+(zoomSpeed&0xF0)) % 0x100 return fmt.Sprintf("A50F01%02X%02X%02X%01X0%02X", cmdCode, horizontalSpeed, verticalSpeed, zoomSpeed>>4, // 根据 GB28181 协议,zoom 只取 4 bit checkCode, ) } func toPtzCode(cmd string) (uint8, error) { if code, ok := name2code[cmd]; ok { return code, nil } else { return 0, fmt.Errorf("invalid ptz cmd %q", cmd) } } func getVerificationCode(ptz []byte) { sum := uint8(0) for i := 0; i < len(ptz)-1; i++ { sum += ptz[i] } ptz[len(ptz)-1] = sum } func getAssembleCode() uint8 { return (PTZFirstByte>>4 + PTZFirstByte&0xF + 0) % 16 } func Pack(cmd, point byte) string { buf := make([]byte, 8) buf[0] = PTZFirstByte buf[1] = getAssembleCode() buf[2] = 0 buf[3] = cmd buf[4] = 0 buf[5] = point buf[6] = 0 getVerificationCode(buf) return hex.EncodeToString(buf) } ================================================ FILE: restful.go ================================================ package gb28181 import ( "fmt" "net/http" "strconv" "strings" "time" "m7s.live/engine/v4/util" ) var ( playScaleValues = map[float32]bool{0.25: true, 0.5: true, 1: true, 2: true, 4: true} ) func (c *GB28181Config) API_list(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() if query.Get("interval") == "" { query.Set("interval", "5s") } util.ReturnFetchValue(func() (list []*Device) { list = make([]*Device, 0) Devices.Range(func(key, value interface{}) bool { list = append(list, value.(*Device)) return true }) return }, w, r) } func (c *GB28181Config) API_records(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() id := query.Get("id") channel := query.Get("channel") startTime := query.Get("startTime") endTime := query.Get("endTime") trange := strings.Split(query.Get("range"), "-") if len(trange) == 2 { startTime = trange[0] endTime = trange[1] } if c := FindChannel(id, channel); c != nil { res, err := c.QueryRecord(startTime, endTime) if err == nil { util.ReturnValue(res, w, r) } else { util.ReturnError(util.APIErrorInternal, err.Error(), w, r) } } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_control(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") ptzcmd := r.URL.Query().Get("ptzcmd") if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("control code:%d", c.Control(ptzcmd)), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_ptz(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() id := q.Get("id") channel := q.Get("channel") cmd := q.Get("cmd") // 命令名称,见 ptz.go name2code 定义 hs := q.Get("hSpeed") // 水平速度 vs := q.Get("vSpeed") // 垂直速度 zs := q.Get("zSpeed") // 缩放速度 hsN, err := strconv.ParseUint(hs, 10, 8) if err != nil { util.ReturnError(util.APIErrorQueryParse, "hSpeed parameter is invalid", w, r) return } vsN, err := strconv.ParseUint(vs, 10, 8) if err != nil { util.ReturnError(util.APIErrorQueryParse, "vSpeed parameter is invalid", w, r) return } zsN, err := strconv.ParseUint(zs, 10, 8) if err != nil { util.ReturnError(util.APIErrorQueryParse, "zSpeed parameter is invalid", w, r) return } ptzcmd, err := toPtzStrByCmdName(cmd, uint8(hsN), uint8(vsN), uint8(zsN)) if err != nil { util.ReturnError(util.APIErrorQueryParse, err.Error(), w, r) return } if c := FindChannel(id, channel); c != nil { code := c.Control(ptzcmd) util.ReturnError(code, "device received", w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_invite(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() id := query.Get("id") channel := query.Get("channel") streamPath := query.Get("streamPath") port, _ := strconv.Atoi(query.Get("mediaPort")) opt := InviteOptions{ dump: query.Get("dump"), MediaPort: uint16(port), StreamPath: streamPath, } startTime := query.Get("startTime") endTime := query.Get("endTime") trange := strings.Split(query.Get("range"), "-") if len(trange) == 2 { startTime = trange[0] endTime = trange[1] } opt.Validate(startTime, endTime) if c := FindChannel(id, channel); c == nil { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } else if opt.IsLive() && c.State.Load() > 0 { util.ReturnError(util.APIErrorQueryParse, "live stream already exists", w, r) } else if code, err := c.Invite(&opt); err == nil { if code == 200 { util.ReturnOK(w, r) } else { util.ReturnError(util.APIErrorInternal, fmt.Sprintf("invite return code %d", code), w, r) } } else { util.ReturnError(util.APIErrorInternal, err.Error(), w, r) } } func (c *GB28181Config) API_bye(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") streamPath := r.URL.Query().Get("streamPath") if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("bye code:%d", c.Bye(streamPath)), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_play_pause(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") streamPath := r.URL.Query().Get("streamPath") if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("pause code:%d", c.Pause(streamPath)), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_play_resume(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") streamPath := r.URL.Query().Get("streamPath") if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("resume code:%d", c.Resume(streamPath)), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_play_seek(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") streamPath := r.URL.Query().Get("streamPath") secStr := r.URL.Query().Get("second") sec, err := strconv.ParseUint(secStr, 10, 32) if err != nil { util.ReturnError(util.APIErrorQueryParse, "second parameter is invalid: "+err.Error(), w, r) return } if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("play code:%d", c.PlayAt(streamPath, uint(sec))), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_play_forward(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") channel := r.URL.Query().Get("channel") streamPath := r.URL.Query().Get("streamPath") speedStr := r.URL.Query().Get("speed") speed, err := strconv.ParseFloat(speedStr, 32) secondErrMsg := "speed parameter is invalid, should be one of 0.25,0.5,1,2,4" if err != nil || !playScaleValues[float32(speed)] { util.ReturnError(util.APIErrorQueryParse, secondErrMsg, w, r) return } if c := FindChannel(id, channel); c != nil { util.ReturnError(0, fmt.Sprintf("playforward code:%d", c.PlayForward(streamPath, float32(speed))), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_position(w http.ResponseWriter, r *http.Request) { //CORS(w, r) query := r.URL.Query() //设备id id := query.Get("id") //订阅周期(单位:秒) expires := query.Get("expires") //订阅间隔(单位:秒) interval := query.Get("interval") expiresInt, err := time.ParseDuration(expires) if expires == "" || err != nil { expiresInt = c.Position.Expires } intervalInt, err := time.ParseDuration(interval) if interval == "" || err != nil { intervalInt = c.Position.Interval } if v, ok := Devices.Load(id); ok { d := v.(*Device) util.ReturnError(0, fmt.Sprintf("mobileposition code:%d", d.MobilePositionSubscribe(id, expiresInt, intervalInt)), w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q not found", id), w, r) } } func (c *GB28181Config) API_preset_list(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() //设备id id := query.Get("id") //获取通道 channel := query.Get("channel") if c := FindChannel(id, channel); c != nil { res, err := c.QueryPresetList() if err == nil { util.ReturnValue(res, w, r) } else { util.ReturnError(util.APIErrorInternal, err.Error(), w, r) } } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } func (c *GB28181Config) API_preset_control(w http.ResponseWriter, r *http.Request) { //CORS(w, r) query := r.URL.Query() //设备id id := query.Get("id") //获取通道 channel := query.Get("channel") //获取cmd ptzCmd := query.Get("cmd") //获取点 point := query.Get("point") if c := FindChannel(id, channel); c != nil { _ptzCmd, _ := strconv.ParseInt(ptzCmd, 10, 16) _point, _ := strconv.ParseInt(point, 10, 8) code := c.PresetControl(int(_ptzCmd), byte(_point)) util.ReturnError(code, "device received", w, r) } else { util.ReturnError(util.APIErrorNotFound, fmt.Sprintf("device %q channel %q not found", id, channel), w, r) } } type DevicePosition struct { ID string GpsTime time.Time //gps时间 Longitude string //经度 Latitude string //纬度 } func (c *GB28181Config) API_get_position(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() //设备id id := query.Get("id") if query.Get("interval") == "" { query.Set("interval", fmt.Sprintf("%ds", c.Position.Interval.Seconds())) } util.ReturnFetchValue(func() (list []*DevicePosition) { if id == "" { Devices.Range(func(key, value interface{}) bool { d := value.(*Device) if time.Since(d.GpsTime) <= c.Position.Interval { list = append(list, &DevicePosition{ID: d.ID, GpsTime: d.GpsTime, Longitude: d.Longitude, Latitude: d.Latitude}) } return true }) } else if v, ok := Devices.Load(id); ok { d := v.(*Device) list = append(list, &DevicePosition{ID: d.ID, GpsTime: d.GpsTime, Longitude: d.Longitude, Latitude: d.Latitude}) } return }, w, r) } ================================================ FILE: server.go ================================================ package gb28181 import ( "context" "fmt" "strconv" "strings" "time" "github.com/ghettovoice/gosip" "github.com/ghettovoice/gosip/log" "github.com/ghettovoice/gosip/sip" "github.com/logrusorgru/aurora/v4" "go.uber.org/zap" . "m7s.live/engine/v4" "m7s.live/plugin/gb28181/v4/utils" ) var srv gosip.Server const MaxRegisterCount = 3 func FindChannel(deviceId string, channelId string) (c *Channel) { if v, ok := Devices.Load(deviceId); ok { d := v.(*Device) if v, ok := d.channelMap.Load(channelId); ok { return v.(*Channel) } } return } var levelMap = map[string]log.Level{ "trace": log.TraceLevel, "debug": log.DebugLevel, "info": log.InfoLevel, "warn": log.WarnLevel, "error": log.ErrorLevel, "fatal": log.FatalLevel, "panic": log.PanicLevel, } func GetSipServer(transport string) gosip.Server { return srv } var sn = 0 func CreateRequest(exposedId string, Method sip.RequestMethod, recipient *sip.Address, netAddr string) (req sip.Request) { sn++ callId := sip.CallID(utils.RandNumString(10)) userAgent := sip.UserAgentHeader("Monibuca") cseq := sip.CSeq{ SeqNo: uint32(sn), MethodName: Method, } port := sip.Port(conf.SipPort) serverAddr := sip.Address{ //DisplayName: sip.String{Str: d.config.Serial}, Uri: &sip.SipUri{ FUser: sip.String{Str: exposedId}, FHost: conf.SipIP, FPort: &port, }, Params: sip.NewParams().Add("tag", sip.String{Str: utils.RandNumString(9)}), } req = sip.NewRequest( "", Method, recipient.Uri, "SIP/2.0", []sip.Header{ serverAddr.AsFromHeader(), recipient.AsToHeader(), &callId, &userAgent, &cseq, serverAddr.AsContactHeader(), }, "", nil, ) req.SetTransport(conf.SipNetwork) req.SetDestination(netAddr) //fmt.Printf("构建请求参数:%s", *&req) // requestMsg.DestAdd, err2 = d.ResolveAddress(requestMsg) // if err2 != nil { // return nil // } //intranet ip , let's resolve it with public ip // var deviceIp, deviceSourceIP net.IP // switch addr := requestMsg.DestAdd.(type) { // case *net.UDPAddr: // deviceIp = addr.IP // case *net.TCPAddr: // deviceIp = addr.IP // } // switch addr2 := d.SourceAddr.(type) { // case *net.UDPAddr: // deviceSourceIP = addr2.IP // case *net.TCPAddr: // deviceSourceIP = addr2.IP // } // if deviceIp.IsPrivate() && !deviceSourceIP.IsPrivate() { // requestMsg.DestAdd = d.SourceAddr // } return } func RequestForResponse(transport string, request sip.Request, options ...gosip.RequestWithContextOption) (sip.Response, error) { return (GetSipServer(transport)).RequestWithContext(context.Background(), request, options...) } func (c *GB28181Config) startServer() { addr := c.ListenAddr + ":" + strconv.Itoa(int(c.SipPort)) logger := utils.NewZapLogger(GB28181Plugin.Logger, "GB SIP Server", nil) logger.SetLevel(uint32(levelMap[EngineConfig.LogLevel])) // logger := log.NewDefaultLogrusLogger().WithPrefix("GB SIP Server") srvConf := gosip.ServerConfig{} if c.SipIP != "" { srvConf.Host = c.SipIP } srv = gosip.NewServer(srvConf, nil, nil, logger) srv.OnRequest(sip.REGISTER, c.OnRegister) srv.OnRequest(sip.MESSAGE, c.OnMessage) srv.OnRequest(sip.NOTIFY, c.OnNotify) srv.OnRequest(sip.BYE, c.OnBye) err := srv.Listen(strings.ToLower(c.SipNetwork), addr) if err != nil { GB28181Plugin.Logger.Error("gb28181 server listen", zap.Error(err)) } else { GB28181Plugin.Info(fmt.Sprint(aurora.Green("Server gb28181 start at"), aurora.BrightBlue(addr))) } if c.MediaNetwork == "tcp" { c.tcpPorts.Init(c.MediaPortMin, c.MediaPortMax) } else { c.udpPorts.Init(c.MediaPortMin, c.MediaPortMax) } go c.startJob() } // func queryCatalog(config *transaction.Config) { // t := time.NewTicker(time.Duration(config.CatalogInterval) * time.Second) // for range t.C { // Devices.Range(func(key, value interface{}) bool { // device := value.(*Device) // if time.Since(device.UpdateTime) > time.Duration(config.RegisterValidity)*time.Second { // Devices.Delete(key) // } else if device.Channels != nil { // go device.Catalog() // } // return true // }) // } // } // 定时任务 func (c *GB28181Config) startJob() { statusTick := time.NewTicker(c.HeartbeatInterval / 2) banTick := time.NewTicker(c.RemoveBanInterval) linkTick := time.NewTicker(time.Millisecond * 100) GB28181Plugin.Debug("start job") for { select { case <-banTick.C: if c.Username != "" || c.Password != "" { c.removeBanDevice() } case <-statusTick.C: c.statusCheck() case <-linkTick.C: RecordQueryLink.cleanTimeout() } } } func (c *GB28181Config) removeBanDevice() { DeviceRegisterCount.Range(func(key, value interface{}) bool { if value.(int) > MaxRegisterCount { DeviceRegisterCount.Delete(key) } return true }) } // statusCheck // - 当设备超过 3 倍心跳时间未发送过心跳(通过 UpdateTime 判断), 视为离线 // - 当设备超过注册有效期内为发送过消息,则从设备列表中删除 // UpdateTime 在设备发送心跳之外的消息也会被更新,相对于 LastKeepaliveAt 更能体现出设备最会一次活跃的时间 func (c *GB28181Config) statusCheck() { Devices.Range(func(key, value any) bool { d := value.(*Device) if time.Since(d.UpdateTime) > c.RegisterValidity { Devices.Delete(key) GB28181Plugin.Info("Device register timeout", zap.String("id", d.ID), zap.Time("registerTime", d.RegisterTime), zap.Time("updateTime", d.UpdateTime), ) } else if time.Since(d.UpdateTime) > c.HeartbeatInterval*3 { d.Status = DeviceOfflineStatus d.channelMap.Range(func(key, value any) bool { ch := value.(*Channel) ch.Status = ChannelOffStatus return true }) GB28181Plugin.Info("Device offline", zap.String("id", d.ID), zap.Time("updateTime", d.UpdateTime)) } return true }) } ================================================ FILE: utils/buffer.go ================================================ package utils import ( "encoding/binary" "errors" "io" ) type IOBuffer struct { buf []byte // contents are the bytes buf[off : len(buf)] off int // read at &buf[off], write at &buf[len(buf)] } func (b *IOBuffer) Next(n int) []byte { m := b.Len() if n > m { n = m } data := b.buf[b.off : b.off+n] b.off += n return data } func (b *IOBuffer) Uint16() (uint16, error) { if b.Len() > 1 { return binary.BigEndian.Uint16(b.Next(2)), nil } return 0, io.EOF } func (b *IOBuffer) Skip(n int) (err error) { _, err = b.ReadN(n) return } func (b *IOBuffer) Uint32() (uint32, error) { if b.Len() > 3 { return binary.BigEndian.Uint32(b.Next(4)), nil } return 0, io.EOF } func (b *IOBuffer) ReadN(length int) ([]byte, error) { if b.Len() >= length { return b.Next(length), nil } return nil, io.EOF } //func (b *IOBuffer) Read(buf []byte) (n int, err error) { // var ret []byte // ret, err = b.ReadN(len(buf)) // copy(buf, ret) // return len(ret), err //} // empty reports whether the unread portion of the buffer is empty. func (b *IOBuffer) empty() bool { return b.Len() <= b.off } func (b *IOBuffer) ReadByte() (byte, error) { if b.empty() { // Buffer is empty, reset to recover space. b.Reset() return 0, io.EOF } c := b.buf[b.off] b.off++ return c, nil } func (b *IOBuffer) Reset() { b.buf = b.buf[:0] b.off = 0 } func (b *IOBuffer) Len() int { return len(b.buf) - b.off } // tryGrowByReslice is a inlineable version of grow for the fast-case where the // internal buffer only needs to be resliced. // It returns the index where bytes should be written and whether it succeeded. func (b *IOBuffer) tryGrowByReslice(n int) (int, bool) { if l := len(b.buf); n <= cap(b.buf)-l { b.buf = b.buf[:l+n] return l, true } return 0, false } var ErrTooLarge = errors.New("IOBuffer: too large") func (b *IOBuffer) Write(p []byte) (n int, err error) { l := copy(b.buf, b.buf[b.off:]) b.buf = append(b.buf[:l], p...) b.off = 0 // println(b.buf, b.off, b.buf[b.off], b.buf[b.off+1], b.buf[b.off+2], b.buf[b.off+3]) return len(p), nil // defer func() { // if recover() != nil { // panic(ErrTooLarge) // } // }() // l := len(p) // oldLen := len(b.buf) // m, ok := b.tryGrowByReslice(l) // if !ok { // m = oldLen - b.off // buf := append(append(([]byte)(nil), b.buf[b.off:]...), p...) // b.off = 0 // b.buf = buf // } // return copy(b.buf[m:], p), nil } ================================================ FILE: utils/bufferpool.go ================================================ package utils import ( "bytes" "sort" "sync" "sync/atomic" ) const ( minBitSize = 6 // 2**6=64 is a CPU cache line size steps = 20 minSize = 1 << minBitSize maxSize = 1 << (minBitSize + steps - 1) calibrateCallsThreshold = 42000 maxPercentile = 0.95 ) // Pool represents byte buffer pool. // // Distinct pools may be used for distinct types of byte buffers. // Properly determined byte buffer types with their own pools may help reducing // memory waste. type Pool struct { calls [steps]uint64 calibrating uint64 defaultSize uint64 maxSize uint64 pool sync.Pool } var defaultPool Pool // Get returns an empty byte buffer from the pool. // // Got byte buffer may be returned to the pool via Put call. // This reduces the number of memory allocations required for byte buffer // management. func Get() *bytes.Buffer { return defaultPool.Get() } // Get returns new byte buffer with zero length. // // The byte buffer may be returned to the pool via Put after the use // in order to minimize GC overhead. func (p *Pool) Get() *bytes.Buffer { v := p.pool.Get() if v != nil { return v.(*bytes.Buffer) } return bytes.NewBuffer(make([]byte, 0, atomic.LoadUint64(&p.defaultSize))) } // Put returns byte buffer to the pool. // // bytes.Buffer.B mustn't be touched after returning it to the pool. // Otherwise data races will occur. func Put(b *bytes.Buffer) { b.Reset(); defaultPool.Put(b) } // Put releases byte buffer obtained via Get to the pool. // // The buffer mustn't be accessed after returning to the pool. func (p *Pool) Put(b *bytes.Buffer) { idx := index(b.Len()) if atomic.AddUint64(&p.calls[idx], 1) > calibrateCallsThreshold { p.calibrate() } maxSize := int(atomic.LoadUint64(&p.maxSize)) if maxSize == 0 || b.Cap() <= maxSize { b.Reset() p.pool.Put(b) } } func (p *Pool) calibrate() { if !atomic.CompareAndSwapUint64(&p.calibrating, 0, 1) { return } a := make(callSizes, 0, steps) var callsSum uint64 for i := uint64(0); i < steps; i++ { calls := atomic.SwapUint64(&p.calls[i], 0) callsSum += calls a = append(a, callSize{ calls: calls, size: minSize << i, }) } sort.Sort(a) defaultSize := a[0].size maxSize := defaultSize maxSum := uint64(float64(callsSum) * maxPercentile) callsSum = 0 for i := 0; i < steps; i++ { if callsSum > maxSum { break } callsSum += a[i].calls size := a[i].size if size > maxSize { maxSize = size } } atomic.StoreUint64(&p.defaultSize, defaultSize) atomic.StoreUint64(&p.maxSize, maxSize) atomic.StoreUint64(&p.calibrating, 0) } type callSize struct { calls uint64 size uint64 } type callSizes []callSize func (ci callSizes) Len() int { return len(ci) } func (ci callSizes) Less(i, j int) bool { return ci[i].calls > ci[j].calls } func (ci callSizes) Swap(i, j int) { ci[i], ci[j] = ci[j], ci[i] } func index(n int) int { n-- n >>= minBitSize idx := 0 for n > 0 { n >>= 1 idx++ } if idx >= steps { idx = steps - 1 } return idx } ================================================ FILE: utils/log.go ================================================ package utils import ( "encoding/json" "github.com/ghettovoice/gosip/log" "go.uber.org/zap" "go.uber.org/zap/zapcore" m7slog "m7s.live/engine/v4/log" ) type ZapLogger struct { log *m7slog.Logger prefix string fields log.Fields sugared *zap.SugaredLogger level log.Level } func NewZapLogger(log *m7slog.Logger, prefix string, fields log.Fields) (z *ZapLogger) { z = &ZapLogger{ log: log, prefix: prefix, fields: fields, } z.sugared = z.prepareEntry() return } func (l *ZapLogger) Print(args ...interface{}) { if l.level >= log.InfoLevel { l.sugared.Info(args...) } } func (l *ZapLogger) Printf(format string, args ...interface{}) { if l.level >= log.InfoLevel { l.sugared.Infof(format, args...) } } func (l *ZapLogger) Trace(args ...interface{}) { if l.level >= log.TraceLevel { l.sugared.Debug(args...) } } func (l *ZapLogger) Tracef(format string, args ...interface{}) { if l.level >= log.TraceLevel { l.sugared.Debugf(format, args...) } } func (l *ZapLogger) Debug(args ...interface{}) { if l.level >= log.DebugLevel { l.sugared.Debug(args...) } } func (l *ZapLogger) Debugf(format string, args ...interface{}) { if l.level >= log.DebugLevel { l.sugared.Debugf(format, args...) } } func (l *ZapLogger) Info(args ...interface{}) { if l.level >= log.InfoLevel { l.sugared.Info(args...) } } func (l *ZapLogger) Infof(format string, args ...interface{}) { if l.level >= log.InfoLevel { l.sugared.Infof(format, args...) } } func (l *ZapLogger) Warn(args ...interface{}) { if l.level >= log.WarnLevel { l.sugared.Warn(args...) } } func (l *ZapLogger) Warnf(format string, args ...interface{}) { if l.level >= log.WarnLevel { l.sugared.Warnf(format, args...) } } func (l *ZapLogger) Error(args ...interface{}) { if l.level >= log.ErrorLevel { l.sugared.Error(args...) } } func (l *ZapLogger) Errorf(format string, args ...interface{}) { if l.level >= log.ErrorLevel { l.sugared.Errorf(format, args...) } } func (l *ZapLogger) Fatal(args ...interface{}) { if l.level >= log.FatalLevel { l.sugared.Fatal(args...) } } func (l *ZapLogger) Fatalf(format string, args ...interface{}) { if l.level >= log.FatalLevel { l.sugared.Fatalf(format, args...) } } func (l *ZapLogger) Panic(args ...interface{}) { if l.level >= log.PanicLevel { l.sugared.Panic(args...) } } func (l *ZapLogger) Panicf(format string, args ...interface{}) { if l.level >= log.PanicLevel { l.sugared.Panicf(format, args...) } } func (l *ZapLogger) WithPrefix(prefix string) log.Logger { return NewZapLogger(l.log, prefix, l.Fields()) } func (l *ZapLogger) Prefix() string { return l.prefix } func (l *ZapLogger) WithFields(fields map[string]interface{}) log.Logger { return NewZapLogger(l.log, l.Prefix(), l.Fields().WithFields(fields)) } func (l *ZapLogger) Fields() log.Fields { return l.fields } func (l *ZapLogger) prepareEntry() *zap.SugaredLogger { newlog := l.log.With(zap.String("prefix", l.Prefix())) if l.fields != nil { fields := make([]zapcore.Field, len(l.fields)) idx := 0 for k, v := range l.fields { s, _ := json.Marshal(v) fields[idx] = zap.String(k, string(s)) idx++ } newlog = newlog.With(fields...) } return newlog.Sugar() } func (l *ZapLogger) SetLevel(level uint32) { l.level = log.Level(level) } ================================================ FILE: utils/rtp_sort.go ================================================ package utils import ( "container/heap" "errors" "github.com/pion/rtp" ) const MaxRtpDiff = 65000 //相邻两个包之间的最大差值 type PriorityQueueRtp struct { itemHeap *packets current *rtp.Packet priorityMap map[uint16]bool lastPacket *rtp.Packet } func NewPqRtp() *PriorityQueueRtp { return &PriorityQueueRtp{ itemHeap: &packets{}, priorityMap: make(map[uint16]bool), } } func (p *PriorityQueueRtp) Len() int { return p.itemHeap.Len() } func (p *PriorityQueueRtp) Push(v rtp.Packet) { if p.priorityMap[v.SequenceNumber] { return } newItem := &packet{ value: v, priority: v.SequenceNumber, } heap.Push(p.itemHeap, newItem) } func (p *PriorityQueueRtp) Pop() (rtp.Packet, error) { if len(*p.itemHeap) == 0 { return rtp.Packet{}, errors.New("empty queue") } item := heap.Pop(p.itemHeap).(*packet) return item.value, nil } func (p *PriorityQueueRtp) Empty() { old := *p.itemHeap *p.itemHeap = old[:0] } type packets []*packet type packet struct { value rtp.Packet priority uint16 index int } func (p *packets) Len() int { return len(*p) } func (p *packets) Less(i, j int) bool { a, b := (*p)[i].priority, (*p)[j].priority if int(a)-int(b) > MaxRtpDiff || int(b)-int(a) > MaxRtpDiff { if a < b { return false } return true } return a < b } func (p *packets) Swap(i, j int) { (*p)[i], (*p)[j] = (*p)[j], (*p)[i] (*p)[i].index = i (*p)[j].index = j } func (p *packets) Push(x interface{}) { it := x.(*packet) it.index = len(*p) *p = append(*p, it) } func (p *packets) Pop() interface{} { old := *p n := len(old) item := old[n-1] old[n-1] = nil // avoid memory leak item.index = -1 // for safety *p = old[0 : n-1] return item } ================================================ FILE: utils/sip.go ================================================ package utils import ( "errors" "fmt" "math/rand" "net" "runtime" "time" ) func RandNum16String(n int) string { numbers16 := "0123456789abcdef" return randStringBySoure(numbers16, n) } func RandNumString(n int) string { numbers := "0123456789" return randStringBySoure(numbers, n) } func RandString(n int) string { letterBytes := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" return randStringBySoure(letterBytes, n) } // https://github.com/kpbird/golang_random_string func randStringBySoure(src string, n int) string { randomness := make([]byte, n) rand.Seed(time.Now().UnixNano()) _, err := rand.Read(randomness) if err != nil { panic(err) } l := len(src) // fill output output := make([]byte, n) for pos := range output { random := randomness[pos] randomPos := random % uint8(l) output[pos] = src[randomPos] } return string(output) } // Error Error type Error struct { err error params []interface{} } func (err *Error) Error() string { if err == nil { return "" } str := fmt.Sprint(err.params...) if err.err != nil { str += fmt.Sprintf(" err:%s", err.err.Error()) } return str } // NewError NewError func NewError(err error, params ...interface{}) error { return &Error{err, params} } func PrintStack() { var buf [4096]byte n := runtime.Stack(buf[:], false) fmt.Printf("==> %s\n", string(buf[:n])) } // ResolveSelfIP ResolveSelfIP func ResolveSelfIP() (net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { return nil, err } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } return ip, nil } } return nil, errors.New("server not connected to any network") } ================================================ FILE: utils/string.go ================================================ package utils import ( "bytes" "encoding/json" "encoding/xml" "golang.org/x/net/html/charset" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" "io/ioutil" ) func ToJSONString(v interface{}) string { b, _ := json.Marshal(v) return string(b) } func ToPrettyString(v interface{}) string { b, _ := json.MarshalIndent(v, "", " ") return string(b) } func GbkToUtf8(s []byte) ([]byte, error) { reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder()) d, e := ioutil.ReadAll(reader) if e != nil { return s, e } return d, nil } func DecodeGbk(v interface{}, body []byte) error { bodyBytes, err := GbkToUtf8(body) if err != nil { return err } decoder := xml.NewDecoder(bytes.NewReader(bodyBytes)) decoder.CharsetReader = charset.NewReaderLabel err = decoder.Decode(v) return err }