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