├── AUTHORS ├── COPYING ├── Dockerfile ├── README.md ├── camera ├── camera.go ├── camera_android.go ├── camera_const_cv.go ├── camera_const_linux.go ├── camera_cv2.go ├── camera_cv4.go ├── camera_linux.go ├── camera_test.go └── camera_windows.go ├── cmd └── cam2ip │ └── main.go ├── go.mod ├── go.sum ├── handlers ├── html.go ├── index.go ├── jpeg.go ├── mjpeg.go └── socket.go ├── image ├── base64.go ├── base64_amd64.go ├── decode.go ├── decode_jpeg.go ├── encode.go └── encode_jpeg.go ├── make.bash ├── reader └── reader.go └── server └── server.go /AUTHORS: -------------------------------------------------------------------------------- 1 | Milan Nikolic 2 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine as build 2 | 3 | WORKDIR /build 4 | 5 | RUN apk add --no-cache git 6 | 7 | COPY go.mod go.sum ./ 8 | 9 | RUN go mod download 10 | 11 | COPY . . 12 | 13 | RUN CGO_ENABLED=0 go build -tags jpeg -o cam2ip -ldflags "-s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 14 | 15 | 16 | FROM scratch 17 | 18 | COPY --from=build /build/cam2ip /cam2ip 19 | 20 | EXPOSE 56000 21 | 22 | ENTRYPOINT ["/cam2ip"] 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## cam2ip 2 | 3 | Turn any webcam into an IP camera. 4 | 5 | Example (in web browser): 6 | 7 | http://localhost:56000/html 8 | 9 | or 10 | 11 | http://localhost:56000/mjpeg 12 | 13 | You can also use apps like `ffplay` or `vlc`: 14 | 15 | ffplay -i http://localhost:56000/mjpeg 16 | 17 | ### Requirements 18 | 19 | * On Linux/RPi native Go [V4L](https://github.com/korandiz/v4l) implementation is used to capture images. 20 | * On Windows [Video for Windows (VfW)](https://en.wikipedia.org/wiki/Video_for_Windows) framework is used over win32 API. 21 | 22 | ### Build tags 23 | 24 | * `cv2` - build with `OpenCV` 2.x ([go-opencv](https://github.com/lazywei/go-opencv)) 25 | * `cv4` - build with `OpenCV` 4.x ([gocv](https://github.com/hybridgroup/gocv)) 26 | * `turbo` - build with `libjpeg-turbo` ([libjpeg-turbo](https://www.libjpeg-turbo.org/)) instead of native Go `image/jpeg` 27 | 28 | ### Download 29 | 30 | Binaries are compiled with static OpenCV/libjpeg-turbo libraries, they should just work: 31 | 32 | - [Linux 64bit](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-64bit.tar.gz) 33 | - [Linux 64bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-64bit-cv2.tar.gz) 34 | - [macOS 64bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-darwin-cv2.zip) 35 | - [RPi 32bit](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-RPi.tar.gz) 36 | - [RPi 32bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-RPi-cv2.tar.gz) 37 | - [RPi 32bit Static](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-RPi-nocgo.tar.gz) 38 | - [RPi3 32bit](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-RPi3.tar.gz) 39 | - [RPi3 32bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-RPi3-cv2.tar.gz) 40 | - [Windows 32bit](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-32bit.zip) 41 | - [Windows 32bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-32bit-cv2.zip) 42 | - [Windows 64bit](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-64bit.zip) 43 | - [Windows 64bit OpenCV](https://github.com/gen2brain/cam2ip/releases/download/1.6/cam2ip-1.6-64bit-cv2.zip) 44 | 45 | 46 | ### Installation 47 | 48 | go get -v github.com/gen2brain/cam2ip/cmd/cam2ip 49 | 50 | This will install app in `$GOPATH/bin/cam2ip`. 51 | 52 | ### Run in Docker container 53 | 54 | docker run --device=/dev/video0:/dev/video0 -p56000:56000 -it gen2brain/cam2ip # on RPi use gen2brain/cam2ip:arm 55 | 56 | ### Usage 57 | 58 | ``` 59 | Usage of cam2ip: 60 | -bind-addr string 61 | Bind address [CAM2IP_BIND_ADDR] (default ":56000") 62 | -delay int 63 | Delay between frames, in milliseconds [CAM2IP_DELAY] (default 10) 64 | -height float 65 | Frame height [CAM2IP_HEIGHT] (default 480) 66 | -htpasswd-file string 67 | Path to htpasswd file, if empty auth is disabled [CAM2IP_HTPASSWD_FILE] 68 | -index int 69 | Camera index [CAM2IP_INDEX] 70 | -nowebgl 71 | Disable WebGL drawing of images (html handler) [CAM2IP_NOWEBGL] 72 | -rotate int 73 | Rotate image, valid values are 90, 180, 270 [CAM2IP_ROTATE] 74 | -timestamp 75 | Draws timestamp on images [CAM2IP_TIMESTAMP] 76 | -width float 77 | Frame width [CAM2IP_WIDTH] (default 640) 78 | ``` 79 | 80 | ### Handlers 81 | 82 | * `/html`: HTML handler, frames are pushed to canvas over websocket 83 | * `/jpeg`: Static JPEG handler 84 | * `/mjpeg`: Motion JPEG, supported natively in major web browsers 85 | -------------------------------------------------------------------------------- /camera/camera.go: -------------------------------------------------------------------------------- 1 | package camera 2 | 3 | // Options. 4 | type Options struct { 5 | Index int 6 | Rotate int 7 | Width float64 8 | Height float64 9 | Timestamp bool 10 | } 11 | -------------------------------------------------------------------------------- /camera/camera_android.go: -------------------------------------------------------------------------------- 1 | //go:build android 2 | // +build android 3 | 4 | // Package camera. 5 | package camera 6 | 7 | /* 8 | #include 9 | 10 | #include 11 | 12 | #include 13 | #include 14 | 15 | #define TAG "camera" 16 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) 17 | #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__) 18 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) 19 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) 20 | 21 | AImage *image; 22 | AImageReader *imageReader; 23 | 24 | ANativeWindow *nativeWindow; 25 | 26 | ACameraDevice *cameraDevice; 27 | ACameraManager *cameraManager; 28 | ACameraOutputTarget *cameraOutputTarget; 29 | ACameraCaptureSession *cameraCaptureSession; 30 | 31 | ACaptureRequest *captureRequest; 32 | ACaptureSessionOutput *captureSessionOutput; 33 | ACaptureSessionOutputContainer *captureSessionOutputContainer; 34 | 35 | void device_on_disconnected(void *context, ACameraDevice *device) { 36 | LOGI("camera %s is diconnected.\n", ACameraDevice_getId(device)); 37 | } 38 | 39 | void device_on_error(void *context, ACameraDevice *device, int error) { 40 | LOGE("error %d on camera %s.\n", error, ACameraDevice_getId(device)); 41 | } 42 | 43 | ACameraDevice_stateCallbacks deviceStateCallbacks = { 44 | .context = NULL, 45 | .onDisconnected = device_on_disconnected, 46 | .onError = device_on_error, 47 | }; 48 | 49 | void session_on_ready(void *context, ACameraCaptureSession *session) { 50 | LOGI("session is ready. %p\n", session); 51 | } 52 | 53 | void session_on_active(void *context, ACameraCaptureSession *session) { 54 | LOGI("session is activated. %p\n", session); 55 | } 56 | 57 | void session_on_closed(void *context, ACameraCaptureSession *session) { 58 | LOGI("session is closed. %p\n", session); 59 | } 60 | 61 | ACameraCaptureSession_stateCallbacks captureSessionStateCallbacks = { 62 | .context = NULL, 63 | .onActive = session_on_active, 64 | .onReady = session_on_ready, 65 | .onClosed = session_on_closed, 66 | }; 67 | 68 | void image_callback(void *context, AImageReader *reader) { 69 | LOGD("image_callback"); 70 | 71 | media_status_t status = AImageReader_acquireLatestImage(reader, &image); 72 | if(status != AMEDIA_OK) { 73 | LOGE("failed to acquire next image (reason: %d).\n", status); 74 | } 75 | } 76 | 77 | AImageReader_ImageListener imageListener = { 78 | .context = NULL, 79 | .onImageAvailable = image_callback, 80 | }; 81 | 82 | int openCamera(int index, int width, int height) { 83 | ACameraIdList *cameraIdList; 84 | const char *selectedCameraId; 85 | 86 | camera_status_t status = ACAMERA_OK; 87 | 88 | cameraManager = ACameraManager_create(); 89 | 90 | status = ACameraManager_getCameraIdList(cameraManager, &cameraIdList); 91 | if(status != ACAMERA_OK) { 92 | LOGE("failed to get camera id list (reason: %d).\n", status); 93 | return status; 94 | } 95 | 96 | if(cameraIdList->numCameras < 1) { 97 | LOGE("no camera device detected.\n"); 98 | } 99 | 100 | if(cameraIdList->numCameras < index+1) { 101 | LOGE("no camera at index %d.\n", index); 102 | } 103 | 104 | selectedCameraId = cameraIdList->cameraIds[index]; 105 | LOGI("open camera (id: %s, num of cameras: %d).\n", selectedCameraId, cameraIdList->numCameras); 106 | 107 | status = ACameraManager_openCamera(cameraManager, selectedCameraId, &deviceStateCallbacks, &cameraDevice); 108 | if(status != ACAMERA_OK) { 109 | LOGE("failed to open camera device (id: %s)\n", selectedCameraId); 110 | return status; 111 | } 112 | 113 | status = ACameraDevice_createCaptureRequest(cameraDevice, TEMPLATE_STILL_CAPTURE, &captureRequest); 114 | if(status != ACAMERA_OK) { 115 | LOGE("failed to create snapshot capture request (id: %s)\n", selectedCameraId); 116 | return status; 117 | } 118 | 119 | status = ACaptureSessionOutputContainer_create(&captureSessionOutputContainer); 120 | if(status != ACAMERA_OK) { 121 | LOGE("failed to create session output container (id: %s)\n", selectedCameraId); 122 | return status; 123 | } 124 | 125 | media_status_t mstatus = AImageReader_new(width, height, AIMAGE_FORMAT_YUV_420_888, 2, &imageReader); 126 | if(mstatus != AMEDIA_OK) { 127 | LOGE("failed to create image reader (reason: %d).\n", mstatus); 128 | return mstatus; 129 | } 130 | 131 | mstatus = AImageReader_setImageListener(imageReader, &imageListener); 132 | if(mstatus != AMEDIA_OK) { 133 | LOGE("failed to set image listener (reason: %d).\n", mstatus); 134 | return mstatus; 135 | } 136 | 137 | AImageReader_getWindow(imageReader, &nativeWindow); 138 | ANativeWindow_acquire(nativeWindow); 139 | 140 | ACameraOutputTarget_create(nativeWindow, &cameraOutputTarget); 141 | ACaptureRequest_addTarget(captureRequest, cameraOutputTarget); 142 | 143 | ACaptureSessionOutput_create(nativeWindow, &captureSessionOutput); 144 | ACaptureSessionOutputContainer_add(captureSessionOutputContainer, captureSessionOutput); 145 | 146 | status = ACameraDevice_createCaptureSession(cameraDevice, captureSessionOutputContainer, &captureSessionStateCallbacks, &cameraCaptureSession); 147 | if(status != ACAMERA_OK) { 148 | LOGE("failed to create capture session (reason: %d).\n", status); 149 | return status; 150 | } 151 | 152 | ACameraManager_deleteCameraIdList(cameraIdList); 153 | ACameraManager_delete(cameraManager); 154 | 155 | return ACAMERA_OK; 156 | } 157 | 158 | int captureCamera() { 159 | camera_status_t status = ACameraCaptureSession_capture(cameraCaptureSession, NULL, 1, &captureRequest, NULL); 160 | if(status != ACAMERA_OK) { 161 | LOGE("failed to capture image (reason: %d).\n", status); 162 | } 163 | 164 | return status; 165 | } 166 | 167 | int closeCamera() { 168 | camera_status_t status = ACAMERA_OK; 169 | 170 | if(captureRequest != NULL) { 171 | ACaptureRequest_free(captureRequest); 172 | captureRequest = NULL; 173 | } 174 | 175 | if(cameraOutputTarget != NULL) { 176 | ACameraOutputTarget_free(cameraOutputTarget); 177 | cameraOutputTarget = NULL; 178 | } 179 | 180 | if(cameraDevice != NULL) { 181 | status = ACameraDevice_close(cameraDevice); 182 | 183 | if(status != ACAMERA_OK) { 184 | LOGE("failed to close camera device.\n"); 185 | return status; 186 | } 187 | 188 | cameraDevice = NULL; 189 | } 190 | 191 | if(captureSessionOutput != NULL) { 192 | ACaptureSessionOutput_free(captureSessionOutput); 193 | captureSessionOutput = NULL; 194 | } 195 | 196 | if(captureSessionOutputContainer != NULL) { 197 | ACaptureSessionOutputContainer_free(captureSessionOutputContainer); 198 | captureSessionOutputContainer = NULL; 199 | } 200 | 201 | if(imageReader != NULL) { 202 | AImageReader_delete(imageReader); 203 | imageReader = NULL; 204 | } 205 | 206 | if(image != NULL) { 207 | AImage_delete(image); 208 | image = NULL; 209 | } 210 | 211 | LOGI("camera closed.\n"); 212 | return ACAMERA_OK; 213 | } 214 | 215 | int openCamera(int index, int width, int height); 216 | int captureCamera(); 217 | int closeCamera(); 218 | 219 | #cgo android CFLAGS: -D__ANDROID_API__=24 220 | #cgo android LDFLAGS: -lcamera2ndk -lmediandk -llog -landroid 221 | */ 222 | import "C" 223 | 224 | import ( 225 | "fmt" 226 | "image" 227 | "unsafe" 228 | ) 229 | 230 | // Camera represents camera. 231 | type Camera struct { 232 | opts Options 233 | img *image.YCbCr 234 | } 235 | 236 | // New returns new Camera for given camera index. 237 | func New(opts Options) (camera *Camera, err error) { 238 | camera = &Camera{} 239 | camera.opts = opts 240 | 241 | camera.img = image.NewYCbCr(image.Rect(0, 0, int(opts.Width), int(opts.Height)), image.YCbCrSubsampleRatio420) 242 | 243 | ret := C.openCamera(C.int(opts.Index), C.int(opts.Width), C.int(opts.Height)) 244 | if bool(int(ret) != 0) { 245 | err = fmt.Errorf("camera: can not open camera %d: error %d", opts.Index, int(ret)) 246 | return 247 | } 248 | 249 | return 250 | } 251 | 252 | // Read reads next frame from camera and returns image. 253 | func (c *Camera) Read() (img image.Image, err error) { 254 | ret := C.captureCamera() 255 | if bool(int(ret) != 0) { 256 | err = fmt.Errorf("camera: can not grab frame: error %d", int(ret)) 257 | return 258 | } 259 | 260 | if C.image == nil { 261 | err = fmt.Errorf("camera: can not retrieve frame") 262 | return 263 | } 264 | 265 | var yStride C.int 266 | var yLen, cbLen, crLen C.int 267 | var yPtr, cbPtr, crPtr *C.uint8_t 268 | 269 | C.AImage_getPlaneRowStride(C.image, 0, &yStride) 270 | C.AImage_getPlaneData(C.image, 0, &yPtr, &yLen) 271 | C.AImage_getPlaneData(C.image, 1, &cbPtr, &cbLen) 272 | C.AImage_getPlaneData(C.image, 2, &crPtr, &crLen) 273 | 274 | c.img.YStride = int(yStride) 275 | c.img.CStride = int(yStride) / 2 276 | 277 | c.img.Y = C.GoBytes(unsafe.Pointer(yPtr), yLen) 278 | c.img.Cb = C.GoBytes(unsafe.Pointer(cbPtr), cbLen) 279 | c.img.Cr = C.GoBytes(unsafe.Pointer(crPtr), crLen) 280 | 281 | img = c.img 282 | 283 | return 284 | } 285 | 286 | // GetProperty returns the specified camera property. 287 | func (c *Camera) GetProperty(id int) float64 { 288 | return 0 289 | } 290 | 291 | // SetProperty sets a camera property. 292 | func (c *Camera) SetProperty(id int, value float64) { 293 | } 294 | 295 | // Close closes camera. 296 | func (c *Camera) Close() (err error) { 297 | ret := C.closeCamera() 298 | if bool(int(ret) != 0) { 299 | err = fmt.Errorf("camera: can not close camera %d: error %d", c.opts.Index, int(ret)) 300 | return 301 | } 302 | 303 | return 304 | } 305 | -------------------------------------------------------------------------------- /camera/camera_const_cv.go: -------------------------------------------------------------------------------- 1 | //go:build cv2 || cv4 2 | // +build cv2 cv4 3 | 4 | package camera 5 | 6 | // Property identifiers. 7 | const ( 8 | PropPosMsec = iota 9 | PropPosFrames 10 | PropPosAviRatio 11 | PropFrameWidth 12 | PropFrameHeight 13 | PropFps 14 | PropFourcc 15 | PropFrameCount 16 | PropFormat 17 | PropMode 18 | PropBrightness 19 | PropContrast 20 | PropSaturation 21 | PropHue 22 | PropGain 23 | PropExposure 24 | PropConvertRgb 25 | PropWhiteBalanceU 26 | PropRectification 27 | PropMonocrome 28 | PropSharpness 29 | PropAutoExposure 30 | PropGamma 31 | PropTemperature 32 | PropTrigger 33 | PropTriggerDelay 34 | PropWhiteBalanceV 35 | PropZoom 36 | PropFocus 37 | PropGuid 38 | PropIsoSpeed 39 | PropMaxDc1394 40 | PropBacklight 41 | PropPan 42 | PropTilt 43 | PropRoll 44 | PropIris 45 | PropSettings 46 | PropBuffersize 47 | ) 48 | -------------------------------------------------------------------------------- /camera/camera_const_linux.go: -------------------------------------------------------------------------------- 1 | //go:build !cv2 && !cv4 && !android 2 | // +build !cv2,!cv4,!android 3 | 4 | package camera 5 | 6 | import ( 7 | "github.com/korandiz/v4l" 8 | ) 9 | 10 | // Property identifiers. 11 | const ( 12 | PropBrightness = v4l.CtrlBrightness 13 | PropContrast = v4l.CtrlContrast 14 | PropSaturation = v4l.CtrlSaturation 15 | PropHue = v4l.CtrlHue 16 | PropGain = v4l.CtrlGain 17 | PropExposure = v4l.CtrlExposure 18 | PropWhiteBalanceU = v4l.CtrlWhiteBalance 19 | PropSharpness = v4l.CtrlSharpness 20 | PropWhiteBalanceV = v4l.CtrlDoWhiteBalance 21 | PropBacklight = v4l.CtrlBacklightCompensation 22 | ) 23 | -------------------------------------------------------------------------------- /camera/camera_cv2.go: -------------------------------------------------------------------------------- 1 | //go:build cv2 && !cv4 2 | // +build cv2,!cv4 3 | 4 | // Package camera. 5 | package camera 6 | 7 | import ( 8 | "fmt" 9 | "image" 10 | "image/color" 11 | "image/draw" 12 | "time" 13 | 14 | "github.com/disintegration/imaging" 15 | "github.com/gen2brain/go-opencv/opencv" 16 | "github.com/pbnjay/pixfont" 17 | ) 18 | 19 | // Camera represents camera. 20 | type Camera struct { 21 | opts Options 22 | camera *opencv.Capture 23 | frame *opencv.IplImage 24 | } 25 | 26 | // New returns new Camera for given camera index. 27 | func New(opts Options) (camera *Camera, err error) { 28 | camera = &Camera{} 29 | camera.opts = opts 30 | 31 | camera.camera = opencv.NewCameraCapture(opts.Index) 32 | if camera.camera == nil { 33 | err = fmt.Errorf("camera: can not open camera %d", opts.Index) 34 | } 35 | 36 | camera.SetProperty(PropFrameWidth, opts.Width) 37 | camera.SetProperty(PropFrameHeight, opts.Height) 38 | 39 | return 40 | } 41 | 42 | // Read reads next frame from camera and returns image. 43 | func (c *Camera) Read() (img image.Image, err error) { 44 | if !c.camera.GrabFrame() { 45 | err = fmt.Errorf("camera: can not grab frame") 46 | return 47 | } 48 | 49 | c.frame = c.camera.RetrieveFrame(1) 50 | if c.frame == nil { 51 | err = fmt.Errorf("camera: can not retrieve frame") 52 | return 53 | } 54 | 55 | img = c.frame.ToImage() 56 | 57 | switch c.opts.Rotate { 58 | case 90: 59 | img = imaging.Rotate90(img) 60 | case 180: 61 | img = imaging.Rotate180(img) 62 | case 270: 63 | img = imaging.Rotate270(img) 64 | } 65 | 66 | if c.opts.Timestamp { 67 | dimg, ok := img.(draw.Image) 68 | if !ok { 69 | err = fmt.Errorf("camera: %T is not a drawable image type", img) 70 | return 71 | } 72 | 73 | pixfont.DrawString(dimg, 10, 10, time.Now().Format("2006-01-02 15:04:05"), color.White) 74 | img = dimg 75 | } 76 | 77 | return 78 | } 79 | 80 | // GetProperty returns the specified camera property. 81 | func (c *Camera) GetProperty(id int) float64 { 82 | return c.camera.GetProperty(id) 83 | } 84 | 85 | // SetProperty sets a camera property. 86 | func (c *Camera) SetProperty(id int, value float64) { 87 | c.camera.SetProperty(id, value) 88 | } 89 | 90 | // Close closes camera. 91 | func (c *Camera) Close() (err error) { 92 | if c.camera == nil { 93 | err = fmt.Errorf("camera: camera is not opened") 94 | return 95 | } 96 | 97 | c.frame.Release() 98 | c.camera.Release() 99 | c.camera = nil 100 | return 101 | } 102 | -------------------------------------------------------------------------------- /camera/camera_cv4.go: -------------------------------------------------------------------------------- 1 | //go:build cv4 && !cv2 2 | // +build cv4,!cv2 3 | 4 | // Package camera. 5 | package camera 6 | 7 | import ( 8 | "fmt" 9 | "image" 10 | "image/color" 11 | "image/draw" 12 | "time" 13 | 14 | "github.com/disintegration/imaging" 15 | "github.com/pbnjay/pixfont" 16 | "gocv.io/x/gocv" 17 | ) 18 | 19 | // Camera represents camera. 20 | type Camera struct { 21 | opts Options 22 | camera *gocv.VideoCapture 23 | frame *gocv.Mat 24 | } 25 | 26 | // New returns new Camera for given camera index. 27 | func New(opts Options) (camera *Camera, err error) { 28 | camera = &Camera{} 29 | camera.opts = opts 30 | 31 | mat := gocv.NewMat() 32 | camera.frame = &mat 33 | 34 | camera.camera, err = gocv.VideoCaptureDevice(opts.Index) 35 | if err != nil { 36 | err = fmt.Errorf("camera: can not open camera %d: %s", opts.Index, err.Error()) 37 | } 38 | 39 | camera.SetProperty(PropFrameWidth, opts.Width) 40 | camera.SetProperty(PropFrameHeight, opts.Height) 41 | 42 | return 43 | } 44 | 45 | // Read reads next frame from camera and returns image. 46 | func (c *Camera) Read() (img image.Image, err error) { 47 | ok := c.camera.Read(c.frame) 48 | if !ok { 49 | err = fmt.Errorf("camera: can not grab frame") 50 | return 51 | } 52 | 53 | img, e := c.frame.ToImage() 54 | if e != nil { 55 | err = fmt.Errorf("camera: %v", e) 56 | return 57 | } 58 | 59 | if c.frame == nil { 60 | err = fmt.Errorf("camera: can not retrieve frame") 61 | return 62 | } 63 | 64 | switch c.opts.Rotate { 65 | case 90: 66 | img = imaging.Rotate90(img) 67 | case 180: 68 | img = imaging.Rotate180(img) 69 | case 270: 70 | img = imaging.Rotate270(img) 71 | } 72 | 73 | if c.opts.Timestamp { 74 | dimg, ok := img.(draw.Image) 75 | if !ok { 76 | err = fmt.Errorf("camera: %T is not a drawable image type", img) 77 | return 78 | } 79 | 80 | pixfont.DrawString(dimg, 10, 10, time.Now().Format("2006-01-02 15:04:05"), color.White) 81 | img = dimg 82 | } 83 | 84 | return 85 | } 86 | 87 | // GetProperty returns the specified camera property. 88 | func (c *Camera) GetProperty(id int) float64 { 89 | return c.camera.Get(gocv.VideoCaptureProperties(id)) 90 | } 91 | 92 | // SetProperty sets a camera property. 93 | func (c *Camera) SetProperty(id int, value float64) { 94 | c.camera.Set(gocv.VideoCaptureProperties(id), value) 95 | } 96 | 97 | // Close closes camera. 98 | func (c *Camera) Close() (err error) { 99 | if c.camera == nil { 100 | err = fmt.Errorf("camera: camera is not opened") 101 | return 102 | } 103 | 104 | c.frame.Close() 105 | err = c.camera.Close() 106 | c.camera = nil 107 | return 108 | } 109 | -------------------------------------------------------------------------------- /camera/camera_linux.go: -------------------------------------------------------------------------------- 1 | //go:build !cv2 && !cv4 && !android 2 | // +build !cv2,!cv4,!android 3 | 4 | // Package camera. 5 | package camera 6 | 7 | import ( 8 | "fmt" 9 | "image" 10 | "image/color" 11 | "image/draw" 12 | "time" 13 | 14 | "github.com/disintegration/imaging" 15 | "github.com/korandiz/v4l" 16 | "github.com/korandiz/v4l/fmt/mjpeg" 17 | "github.com/pbnjay/pixfont" 18 | 19 | im "github.com/gen2brain/cam2ip/image" 20 | ) 21 | 22 | // Camera represents camera. 23 | type Camera struct { 24 | opts Options 25 | camera *v4l.Device 26 | } 27 | 28 | // New returns new Camera for given camera index. 29 | func New(opts Options) (camera *Camera, err error) { 30 | camera = &Camera{} 31 | camera.opts = opts 32 | 33 | devices := v4l.FindDevices() 34 | if len(devices) < opts.Index+1 { 35 | err = fmt.Errorf("camera: no camera at index %d", opts.Index) 36 | return 37 | } 38 | 39 | camera.camera, err = v4l.Open(devices[opts.Index].Path) 40 | if err != nil { 41 | err = fmt.Errorf("camera: %s", err.Error()) 42 | return 43 | } 44 | 45 | if camera.camera == nil { 46 | err = fmt.Errorf("camera: can not open camera %d", opts.Index) 47 | return 48 | } 49 | 50 | config, err := camera.camera.GetConfig() 51 | if err != nil { 52 | err = fmt.Errorf("camera: %s", err.Error()) 53 | return 54 | } 55 | 56 | config.Format = mjpeg.FourCC 57 | config.Width = int(opts.Width) 58 | config.Height = int(opts.Height) 59 | 60 | err = camera.camera.SetConfig(config) 61 | if err != nil { 62 | err = fmt.Errorf("camera: %s", err.Error()) 63 | return 64 | } 65 | 66 | err = camera.camera.TurnOn() 67 | if err != nil { 68 | err = fmt.Errorf("camera: %s", err.Error()) 69 | return 70 | } 71 | 72 | return 73 | } 74 | 75 | // Read reads next frame from camera and returns image. 76 | func (c *Camera) Read() (img image.Image, err error) { 77 | 78 | buffer, err := c.camera.Capture() 79 | if err != nil { 80 | err = fmt.Errorf("camera: can not grab frame: %s", err.Error()) 81 | return 82 | } 83 | 84 | img, err = im.NewDecoder(buffer).Decode() 85 | if err != nil { 86 | err = fmt.Errorf("camera: %s", err.Error()) 87 | return 88 | } 89 | 90 | switch c.opts.Rotate { 91 | case 90: 92 | img = imaging.Rotate90(img) 93 | case 180: 94 | img = imaging.Rotate180(img) 95 | case 270: 96 | img = imaging.Rotate270(img) 97 | } 98 | 99 | if c.opts.Timestamp { 100 | dimg, ok := img.(draw.Image) 101 | if !ok { 102 | err = fmt.Errorf("camera: %T is not a drawable image type", img) 103 | return 104 | } 105 | 106 | pixfont.DrawString(dimg, 10, 10, time.Now().Format("2006-01-02 15:04:05"), color.White) 107 | img = dimg 108 | } 109 | 110 | return 111 | } 112 | 113 | // GetProperty returns the specified camera property. 114 | func (c *Camera) GetProperty(id int) float64 { 115 | ret, _ := c.camera.GetControl(uint32(id)) 116 | return float64(ret) 117 | } 118 | 119 | // SetProperty sets a camera property. 120 | func (c *Camera) SetProperty(id int, value float64) { 121 | c.camera.SetControl(uint32(id), int32(value)) 122 | } 123 | 124 | // Close closes camera. 125 | func (c *Camera) Close() (err error) { 126 | if c.camera == nil { 127 | err = fmt.Errorf("camera: camera is not opened") 128 | return 129 | } 130 | 131 | c.camera.TurnOff() 132 | 133 | c.camera.Close() 134 | c.camera = nil 135 | return 136 | } 137 | -------------------------------------------------------------------------------- /camera/camera_test.go: -------------------------------------------------------------------------------- 1 | package camera 2 | 3 | import ( 4 | "fmt" 5 | "image/jpeg" 6 | "io/ioutil" 7 | "os" 8 | "path/filepath" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func TestCamera(t *testing.T) { 14 | camera, err := New(Options{0, 0, 640, 480}) 15 | if err != nil { 16 | t.Fatal(err) 17 | } 18 | 19 | defer camera.Close() 20 | 21 | tmpdir, err := ioutil.TempDir(os.TempDir(), "cam2ip") 22 | if err != nil { 23 | t.Error(err) 24 | } 25 | 26 | defer os.RemoveAll(tmpdir) 27 | 28 | var i int 29 | var n int = 10 30 | 31 | timeout := time.After(time.Duration(n) * time.Second) 32 | 33 | for { 34 | select { 35 | case <-timeout: 36 | //fmt.Printf("Fps: %d\n", i/n) 37 | return 38 | default: 39 | i += 1 40 | 41 | img, err := camera.Read() 42 | if err != nil { 43 | t.Error(err) 44 | } 45 | 46 | file, err := os.Create(filepath.Join(tmpdir, fmt.Sprintf("%03d.jpg", i))) 47 | if err != nil { 48 | t.Error(err) 49 | } 50 | 51 | err = jpeg.Encode(file, img, &jpeg.Options{Quality: 75}) 52 | if err != nil { 53 | t.Error(err) 54 | } 55 | 56 | err = file.Close() 57 | if err != nil { 58 | t.Error(err) 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /camera/camera_windows.go: -------------------------------------------------------------------------------- 1 | //go:build !cv2 && !cv4 2 | // +build !cv2,!cv4 3 | 4 | // Package camera. 5 | package camera 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "image" 11 | "image/color" 12 | "image/draw" 13 | "syscall" 14 | "time" 15 | "unsafe" 16 | 17 | "github.com/disintegration/imaging" 18 | "github.com/pbnjay/pixfont" 19 | ) 20 | 21 | // Camera represents camera. 22 | type Camera struct { 23 | opts Options 24 | camera syscall.Handle 25 | frame *image.RGBA 26 | hdr *videoHdr 27 | instance syscall.Handle 28 | className string 29 | } 30 | 31 | // New returns new Camera for given camera index. 32 | func New(opts Options) (camera *Camera, err error) { 33 | camera = &Camera{} 34 | camera.opts = opts 35 | camera.className = "capWindowClass" 36 | 37 | camera.instance, err = getModuleHandle() 38 | if err != nil { 39 | return 40 | } 41 | 42 | camera.frame = image.NewRGBA(image.Rect(0, 0, int(camera.opts.Width), int(camera.opts.Height))) 43 | 44 | go func(c *Camera) { 45 | fn := func(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) uintptr { 46 | switch msg { 47 | case wmClose: 48 | destroyWindow(hwnd) 49 | case wmDestroy: 50 | postQuitMessage(0) 51 | default: 52 | ret := defWindowProc(hwnd, msg, wparam, lparam) 53 | return ret 54 | } 55 | 56 | return 0 57 | } 58 | 59 | err = registerClass(c.className, c.instance, fn) 60 | if err != nil { 61 | return 62 | } 63 | 64 | hwnd, err := createWindow(0, c.className, "", wsOverlappedWindow, cwUseDefault, cwUseDefault, int64(c.opts.Width)+100, int64(c.opts.Height)+100, 0, 0, c.instance) 65 | if err != nil { 66 | return 67 | } 68 | 69 | c.camera, err = capCreateCaptureWindow("", wsChild, 0, 0, int64(c.opts.Width), int64(c.opts.Height), hwnd, 0) 70 | if err != nil { 71 | return 72 | } 73 | 74 | ret := sendMessage(c.camera, wmCapDriverConnect, uintptr(c.opts.Index), 0) 75 | if bool(int(ret) == 0) { 76 | err = fmt.Errorf("camera: can not open camera %d", c.opts.Index) 77 | return 78 | } 79 | 80 | var bi bitmapInfo 81 | size := sendMessage(c.camera, wmCapGetVideoformat, 0, 0) 82 | sendMessage(c.camera, wmCapGetVideoformat, size, uintptr(unsafe.Pointer(&bi))) 83 | 84 | bi.BmiHeader.BiWidth = int32(c.opts.Width) 85 | bi.BmiHeader.BiHeight = int32(c.opts.Height) 86 | 87 | ret = sendMessage(c.camera, wmCapSetVideoformat, size, uintptr(unsafe.Pointer(&bi))) 88 | if bool(int(ret) == 0) { 89 | err = fmt.Errorf("camera: can not set video format") 90 | return 91 | } 92 | 93 | sendMessage(c.camera, wmCapSetCallbackFrame, 0, syscall.NewCallback(c.callback)) 94 | 95 | messageLoop(c.camera) 96 | }(camera) 97 | 98 | return 99 | } 100 | 101 | // Read reads next frame from camera and returns image. 102 | func (c *Camera) Read() (img image.Image, err error) { 103 | ret := sendMessage(c.camera, wmCapGrabFrameNoStop, 0, 0) 104 | if bool(int(ret) == 0) { 105 | err = fmt.Errorf("camera: can not grab frame") 106 | return 107 | } 108 | 109 | data := (*[1 << 24]uint8)(unsafe.Pointer(c.hdr.LpData))[0:c.hdr.DwBytesUsed] 110 | r := bytes.NewReader(data) 111 | 112 | width := int(c.opts.Width) 113 | height := int(c.opts.Height) 114 | 115 | // Taken from https://github.com/hotei/bmp/blob/master/bmpRGBA.go#L12 116 | // There are 3 bytes per pixel, and each row is 4-byte aligned. 117 | b := make([]byte, (3*width+3)&^3) 118 | // BMP images are stored bottom-up rather than top-down. 119 | for y := height - 1; y >= 0; y-- { 120 | _, err = r.Read(b) 121 | if err != nil { 122 | err = fmt.Errorf("camera: can not retrieve frame: %v", err) 123 | return 124 | } 125 | 126 | p := c.frame.Pix[y*c.frame.Stride : y*c.frame.Stride+width*4] 127 | for i, j := 0, 0; i < len(p); i, j = i+4, j+3 { 128 | // BMP images are stored in BGR order rather than RGB order. 129 | p[i+0] = b[j+2] 130 | p[i+1] = b[j+1] 131 | p[i+2] = b[j+0] 132 | p[i+3] = 0xFF 133 | } 134 | } 135 | 136 | img = c.frame 137 | 138 | switch c.opts.Rotate { 139 | case 90: 140 | img = imaging.Rotate90(img) 141 | case 180: 142 | img = imaging.Rotate180(img) 143 | case 270: 144 | img = imaging.Rotate270(img) 145 | } 146 | 147 | if c.opts.Timestamp { 148 | dimg, ok := img.(draw.Image) 149 | if !ok { 150 | err = fmt.Errorf("camera: %T is not a drawable image type", img) 151 | return 152 | } 153 | 154 | pixfont.DrawString(dimg, 10, 10, time.Now().Format("2006-01-02 15:04:05"), color.White) 155 | img = dimg 156 | } 157 | 158 | return 159 | } 160 | 161 | // GetProperty returns the specified camera property. 162 | func (c *Camera) GetProperty(id int) float64 { 163 | return 0 164 | } 165 | 166 | // SetProperty sets a camera property. 167 | func (c *Camera) SetProperty(id int, value float64) { 168 | return 169 | } 170 | 171 | // Close closes camera. 172 | func (c *Camera) Close() (err error) { 173 | sendMessage(c.camera, wmCapSetCallbackFrame, 0, 0) 174 | unregisterClass(c.className, c.instance) 175 | sendMessage(c.camera, wmCapDriverDisconnect, 0, 0) 176 | destroyWindow(c.camera) 177 | return 178 | } 179 | 180 | // callback function. 181 | func (c *Camera) callback(hwvd syscall.Handle, hdr *videoHdr) uintptr { 182 | c.hdr = hdr 183 | return 0 184 | } 185 | 186 | var ( 187 | user32 = syscall.NewLazyDLL("user32.dll") 188 | kernel32 = syscall.NewLazyDLL("kernel32.dll") 189 | avicap32 = syscall.NewLazyDLL("avicap32.dll") 190 | 191 | createWindowExW = user32.NewProc("CreateWindowExW") 192 | destroyWindowW = user32.NewProc("DestroyWindow") 193 | defWindowProcW = user32.NewProc("DefWindowProcW") 194 | dispatchMessageW = user32.NewProc("DispatchMessageW") 195 | translateMessageW = user32.NewProc("TranslateMessage") 196 | getMessageW = user32.NewProc("GetMessageW") 197 | sendMessageW = user32.NewProc("SendMessageW") 198 | postQuitMessageW = user32.NewProc("PostQuitMessage") 199 | registerClassExW = user32.NewProc("RegisterClassExW") 200 | unregisterClassW = user32.NewProc("UnregisterClassW") 201 | 202 | getModuleHandleW = kernel32.NewProc("GetModuleHandleW") 203 | capCreateCaptureWindowW = avicap32.NewProc("capCreateCaptureWindowW") 204 | ) 205 | 206 | const ( 207 | wmDestroy = 0x0002 208 | wmClose = 0x0010 209 | wmUser = 0x0400 210 | 211 | wmCapStart = wmUser 212 | wmCapSetCallbackFrame = wmCapStart + 5 213 | wmCapDriverConnect = wmCapStart + 10 214 | wmCapDriverDisconnect = wmCapStart + 11 215 | wmCapGetVideoformat = wmCapStart + 44 216 | wmCapSetVideoformat = wmCapStart + 45 217 | wmCapGrabFrame = wmCapStart + 60 218 | wmCapGrabFrameNoStop = wmCapStart + 61 219 | wmCapStop = wmCapStart + 68 220 | wmCapAbort = wmCapStart + 69 221 | 222 | wsChild = 0x40000000 223 | wsOverlappedWindow = 0x00CF0000 224 | 225 | cwUseDefault = 0x7fffffff 226 | ) 227 | 228 | // wndClassExW https://msdn.microsoft.com/en-us/library/windows/desktop/ms633577.aspx 229 | type wndClassExW struct { 230 | size uint32 231 | style uint32 232 | wndProc uintptr 233 | clsExtra int32 234 | wndExtra int32 235 | instance syscall.Handle 236 | icon syscall.Handle 237 | cursor syscall.Handle 238 | background syscall.Handle 239 | menuName *uint16 240 | className *uint16 241 | iconSm syscall.Handle 242 | } 243 | 244 | // msgW https://msdn.microsoft.com/en-us/library/windows/desktop/ms644958.aspx 245 | type msgW struct { 246 | hwnd syscall.Handle 247 | message uint32 248 | wParam uintptr 249 | lParam uintptr 250 | time uint32 251 | pt pointW 252 | } 253 | 254 | // https://msdn.microsoft.com/en-us/ecb0f0e1-90c2-48ab-a069-552262b49c7c 255 | type pointW struct { 256 | x, y int32 257 | } 258 | 259 | // http://msdn.microsoft.com/en-us/library/windows/desktop/dd183376.aspx 260 | type bitmapInfoHeader struct { 261 | BiSize uint32 262 | BiWidth int32 263 | BiHeight int32 264 | BiPlanes uint16 265 | BiBitCount uint16 266 | BiCompression uint32 267 | BiSizeImage uint32 268 | BiXPelsPerMeter int32 269 | BiYPelsPerMeter int32 270 | BiClrUsed uint32 271 | BiClrImportant uint32 272 | } 273 | 274 | // http://msdn.microsoft.com/en-us/library/windows/desktop/dd183375.aspx 275 | type bitmapInfo struct { 276 | BmiHeader bitmapInfoHeader 277 | BmiColors *rgbQuad 278 | } 279 | 280 | // http://msdn.microsoft.com/en-us/library/windows/desktop/dd162938.aspx 281 | type rgbQuad struct { 282 | RgbBlue byte 283 | RgbGreen byte 284 | RgbRed byte 285 | RgbReserved byte 286 | } 287 | 288 | // https://docs.microsoft.com/en-us/windows/desktop/api/vfw/ns-vfw-videohdr_tag 289 | type videoHdr struct { 290 | LpData *uint8 291 | DwBufferLength uint32 292 | DwBytesUsed uint32 293 | DwTimeCaptured uint32 294 | DwUser uint64 295 | DwFlags uint32 296 | DwReserved [4]uint64 297 | } 298 | 299 | // https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-getmodulehandlea 300 | func getModuleHandle() (syscall.Handle, error) { 301 | ret, _, err := getModuleHandleW.Call(uintptr(0)) 302 | if ret == 0 { 303 | return 0, err 304 | } 305 | 306 | return syscall.Handle(ret), nil 307 | } 308 | 309 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createwindowexw 310 | func createWindow(exStyle uint64, className, windowName string, style uint64, x, y, width, height int64, 311 | parent, menu, instance syscall.Handle) (syscall.Handle, error) { 312 | ret, _, err := createWindowExW.Call(uintptr(exStyle), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(className))), 313 | uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(windowName))), uintptr(style), uintptr(x), uintptr(y), 314 | uintptr(width), uintptr(height), uintptr(parent), uintptr(menu), uintptr(instance), uintptr(0)) 315 | 316 | if ret == 0 { 317 | return 0, err 318 | } 319 | 320 | return syscall.Handle(ret), nil 321 | } 322 | 323 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-destroywindow 324 | func destroyWindow(hwnd syscall.Handle) error { 325 | ret, _, err := destroyWindowW.Call(uintptr(hwnd)) 326 | if ret == 0 { 327 | return err 328 | } 329 | 330 | return nil 331 | } 332 | 333 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-defwindowprocw 334 | func defWindowProc(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) uintptr { 335 | ret, _, _ := defWindowProcW.Call(uintptr(hwnd), uintptr(msg), uintptr(wparam), uintptr(lparam)) 336 | return uintptr(ret) 337 | } 338 | 339 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-dispatchmessagew 340 | func dispatchMessage(msg *msgW) { 341 | dispatchMessageW.Call(uintptr(unsafe.Pointer(msg))) 342 | } 343 | 344 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-translatemessage 345 | func translateMessage(msg *msgW) { 346 | translateMessageW.Call(uintptr(unsafe.Pointer(msg))) 347 | } 348 | 349 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getmessagew 350 | func getMessage(msg *msgW, hwnd syscall.Handle, msgFilterMin, msgFilterMax uint32) (bool, error) { 351 | ret, _, err := getMessageW.Call(uintptr(unsafe.Pointer(msg)), uintptr(hwnd), uintptr(msgFilterMin), uintptr(msgFilterMax)) 352 | if int32(ret) == -1 { 353 | return false, err 354 | } 355 | 356 | return int32(ret) != 0, nil 357 | } 358 | 359 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage 360 | func sendMessage(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) uintptr { 361 | ret, _, _ := sendMessageW.Call(uintptr(hwnd), uintptr(msg), wparam, lparam, 0, 0) 362 | return ret 363 | } 364 | 365 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-postquitmessage 366 | func postQuitMessage(exitCode int32) { 367 | postQuitMessageW.Call(uintptr(exitCode)) 368 | } 369 | 370 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-registerclassexw 371 | func registerClass(className string, instance syscall.Handle, fn interface{}) error { 372 | var wcx wndClassExW 373 | wcx.size = uint32(unsafe.Sizeof(wcx)) 374 | wcx.wndProc = syscall.NewCallback(fn) 375 | wcx.instance = instance 376 | wcx.className = syscall.StringToUTF16Ptr(className) 377 | 378 | ret, _, err := registerClassExW.Call(uintptr(unsafe.Pointer(&wcx))) 379 | if ret == 0 { 380 | return err 381 | } 382 | 383 | return nil 384 | } 385 | 386 | // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-unregisterclassw 387 | func unregisterClass(className string, instance syscall.Handle) bool { 388 | ret, _, _ := unregisterClassW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(className))), uintptr(instance)) 389 | return ret != 0 390 | } 391 | 392 | // https://docs.microsoft.com/en-us/windows/desktop/api/vfw/nf-vfw-capcreatecapturewindoww 393 | func capCreateCaptureWindow(lpszWindowName string, dwStyle, x, y, width, height int64, parent syscall.Handle, id int64) (syscall.Handle, error) { 394 | ret, _, err := capCreateCaptureWindowW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpszWindowName))), 395 | uintptr(dwStyle), uintptr(x), uintptr(y), uintptr(width), uintptr(height), uintptr(parent), uintptr(id)) 396 | if ret == 0 { 397 | return 0, err 398 | } 399 | 400 | return syscall.Handle(ret), nil 401 | } 402 | 403 | // messageLoop function 404 | func messageLoop(hwnd syscall.Handle) { 405 | for { 406 | msg := &msgW{} 407 | ok, _ := getMessage(msg, 0, 0, 0) 408 | if ok { 409 | translateMessage(msg) 410 | dispatchMessage(msg) 411 | } else { 412 | break 413 | } 414 | } 415 | 416 | return 417 | } 418 | -------------------------------------------------------------------------------- /cmd/cam2ip/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/jamiealquiza/envy" 9 | 10 | "github.com/gen2brain/cam2ip/camera" 11 | "github.com/gen2brain/cam2ip/server" 12 | ) 13 | 14 | const ( 15 | name = "cam2ip" 16 | version = "1.6" 17 | ) 18 | 19 | func main() { 20 | srv := server.NewServer() 21 | 22 | flag.IntVar(&srv.Index, "index", 0, "Camera index") 23 | flag.IntVar(&srv.Delay, "delay", 10, "Delay between frames, in milliseconds") 24 | flag.Float64Var(&srv.FrameWidth, "width", 640, "Frame width") 25 | flag.Float64Var(&srv.FrameHeight, "height", 480, "Frame height") 26 | flag.IntVar(&srv.Rotate, "rotate", 0, "Rotate image, valid values are 90, 180, 270") 27 | flag.BoolVar(&srv.NoWebGL, "nowebgl", false, "Disable WebGL drawing of images (html handler)") 28 | flag.BoolVar(&srv.Timestamp, "timestamp", false, "Draws timestamp on images") 29 | flag.StringVar(&srv.Bind, "bind-addr", ":56000", "Bind address") 30 | flag.StringVar(&srv.Htpasswd, "htpasswd-file", "", "Path to htpasswd file, if empty auth is disabled") 31 | 32 | envy.Parse("CAM2IP") 33 | flag.Parse() 34 | 35 | srv.Name = name 36 | srv.Version = version 37 | 38 | var err error 39 | 40 | if srv.Htpasswd != "" { 41 | if _, err = os.Stat(srv.Htpasswd); err != nil { 42 | fmt.Fprintf(os.Stderr, "%s\n", err.Error()) 43 | os.Exit(1) 44 | } 45 | } 46 | 47 | if srv.FileName != "" { 48 | if _, err = os.Stat(srv.FileName); err != nil { 49 | fmt.Fprintf(os.Stderr, "%s\n", err.Error()) 50 | os.Exit(1) 51 | } 52 | } 53 | 54 | cam, err := camera.New(camera.Options{srv.Index, srv.Rotate, srv.FrameWidth, srv.FrameHeight, srv.Timestamp}) 55 | if err != nil { 56 | fmt.Fprintf(os.Stderr, "%s\n", err.Error()) 57 | os.Exit(1) 58 | } 59 | 60 | srv.Reader = cam 61 | 62 | defer srv.Reader.Close() 63 | 64 | fmt.Fprintf(os.Stderr, "Listening on %s\n", srv.Bind) 65 | 66 | err = srv.ListenAndServe() 67 | if err != nil { 68 | fmt.Fprintf(os.Stderr, "%s\n", err.Error()) 69 | os.Exit(1) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/gen2brain/cam2ip 2 | 3 | require ( 4 | github.com/abbot/go-http-auth v0.4.0 5 | github.com/antonini/golibjpegturbo v0.0.0-20141208033414-c03a2fa1e89a 6 | github.com/disintegration/imaging v1.6.2 7 | github.com/gen2brain/base64 v0.0.0-20221015184129-317a5c93030c 8 | github.com/gen2brain/go-opencv v0.0.0-20191005190506-bf186fc94f7a 9 | github.com/jamiealquiza/envy v1.1.0 10 | github.com/korandiz/v4l v1.1.0 11 | github.com/pbnjay/pixfont v0.0.0-20200714042608-33b744692567 12 | gocv.io/x/gocv v0.35.0 13 | nhooyr.io/websocket v1.8.10 14 | ) 15 | 16 | require ( 17 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 18 | github.com/spf13/cobra v1.8.0 // indirect 19 | github.com/spf13/pflag v1.0.5 // indirect 20 | golang.org/x/crypto v0.18.0 // indirect 21 | golang.org/x/image v0.15.0 // indirect 22 | golang.org/x/net v0.20.0 // indirect 23 | golang.org/x/sys v0.16.0 // indirect 24 | ) 25 | 26 | go 1.21 27 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/abbot/go-http-auth v0.4.0 h1:QjmvZ5gSC7jm3Zg54DqWE/T5m1t2AfDu6QlXJT0EVT0= 2 | github.com/abbot/go-http-auth v0.4.0/go.mod h1:Cz6ARTIzApMJDzh5bRMSUou6UMSp0IEXg9km/ci7TJM= 3 | github.com/antonini/golibjpegturbo v0.0.0-20141208033414-c03a2fa1e89a h1:+Q4qlzO9KeavJSvWgRKckT3ViTSQ8rR6GroSiXPRXhs= 4 | github.com/antonini/golibjpegturbo v0.0.0-20141208033414-c03a2fa1e89a/go.mod h1:UOX4aiVZ5WVUBY3D/31H4m6Z8UHgBj5Qr/oldRBBUMY= 5 | github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 6 | github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= 7 | github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= 8 | github.com/gen2brain/base64 v0.0.0-20221015184129-317a5c93030c h1:TUjjeJ2rV4KZxH6hIEi/boEQB3v6aKvwdakUJR3AwiE= 9 | github.com/gen2brain/base64 v0.0.0-20221015184129-317a5c93030c/go.mod h1:VG58IUyxPWojCtGwqwoZ/6LLXwClu1tssqa5ktOxI9o= 10 | github.com/gen2brain/go-opencv v0.0.0-20191005190506-bf186fc94f7a h1:0arrt5Ke40opD5glNdh9ltrkZ0jaqPWsquGPSE3ukug= 11 | github.com/gen2brain/go-opencv v0.0.0-20191005190506-bf186fc94f7a/go.mod h1:pOLh42huXUuMoJWvD2K+EeXzvQ9GZ5HN6gdFk5ZwIuU= 12 | github.com/hybridgroup/mjpeg v0.0.0-20140228234708-4680f319790e/go.mod h1:eagM805MRKrioHYuU7iKLUyFPVKqVV6um5DAvCkUtXs= 13 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 14 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 15 | github.com/jamiealquiza/envy v1.1.0 h1:Nwh4wqTZ28gDA8zB+wFkhnUpz3CEcO12zotjeqqRoKE= 16 | github.com/jamiealquiza/envy v1.1.0/go.mod h1:MP36BriGCLwEHhi1OU8E9569JNZrjWfCvzG7RsPnHus= 17 | github.com/korandiz/v4l v1.1.0 h1:VbzaWlhqNzVPfHEYEM+V8T7184ndiEzljJgDHSHc7pc= 18 | github.com/korandiz/v4l v1.1.0/go.mod h1:pftxPG7hkuUgepioAY6PAE81mShaVjzd95X/WF4Izus= 19 | github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= 20 | github.com/pbnjay/pixfont v0.0.0-20200714042608-33b744692567 h1:pKjmNHL7BCXhgsnSlN6Ov3WAN2jbJMCx6IvrMN9GNfc= 21 | github.com/pbnjay/pixfont v0.0.0-20200714042608-33b744692567/go.mod h1:ytYavTmrpWG4s7UOfDhP6m4ASL5XA66nrOcUn1e2M78= 22 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 23 | github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= 24 | github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= 25 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 26 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 27 | gocv.io/x/gocv v0.35.0 h1:Qaxb5KdVyy8Spl4S4K0SMZ6CVmKtbfoSGQAxRD3FZlw= 28 | gocv.io/x/gocv v0.35.0/go.mod h1:oc6FvfYqfBp99p+yOEzs9tbYF9gOrAQSeL/dyIPefJU= 29 | golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= 30 | golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= 31 | golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= 32 | golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8= 33 | golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE= 34 | golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= 35 | golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= 36 | golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= 37 | golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 38 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 39 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 40 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 41 | nhooyr.io/websocket v1.8.10 h1:mv4p+MnGrLDcPlBoWsvPP7XCzTYMXP9F9eIGoKbgx7Q= 42 | nhooyr.io/websocket v1.8.10/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= 43 | -------------------------------------------------------------------------------- /handlers/html.go: -------------------------------------------------------------------------------- 1 | // Package handlers. 2 | package handlers 3 | 4 | import ( 5 | "fmt" 6 | "net/http" 7 | "strings" 8 | ) 9 | 10 | // HTML handler. 11 | type HTML struct { 12 | Template []byte 13 | } 14 | 15 | // NewHTML returns new HTML handler. 16 | func NewHTML(width, height float64, nogl bool) *HTML { 17 | h := &HTML{} 18 | 19 | tpl := htmlWebGL 20 | if nogl { 21 | tpl = html 22 | } 23 | tpl = strings.Replace(tpl, "{WIDTH}", fmt.Sprintf("%.0f", width), -1) 24 | tpl = strings.Replace(tpl, "{HEIGHT}", fmt.Sprintf("%.0f", height), -1) 25 | 26 | h.Template = []byte(tpl) 27 | return h 28 | } 29 | 30 | // ServeHTTP handles requests on incoming connections. 31 | func (h *HTML) ServeHTTP(w http.ResponseWriter, r *http.Request) { 32 | if r.Method != "GET" && r.Method != "HEAD" { 33 | msg := fmt.Sprintf("405 Method Not Allowed (%s)", r.Method) 34 | http.Error(w, msg, http.StatusMethodNotAllowed) 35 | return 36 | } 37 | 38 | w.Header().Set("Content-Type", "text/html; charset=utf-8") 39 | w.WriteHeader(http.StatusOK) 40 | w.Write(h.Template) 41 | } 42 | 43 | var html = ` 44 | 45 | 46 | cam2ip 47 | 62 | 63 | 64 | 65 | 66 | 69 | 70 |
67 | 68 |
71 | 72 | ` 73 | 74 | var htmlWebGL = ` 75 | 76 | 77 | cam2ip 78 | 160 | 161 | 162 | 163 | 164 | 167 | 168 |
165 | 166 |
169 | 170 | ` 171 | -------------------------------------------------------------------------------- /handlers/index.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | // Index handler. 8 | type Index struct { 9 | } 10 | 11 | // NewIndex returns new Index handler. 12 | func NewIndex() *Index { 13 | return &Index{} 14 | } 15 | 16 | // ServeHTTP handles requests on incoming connections. 17 | func (i *Index) ServeHTTP(w http.ResponseWriter, r *http.Request) { 18 | if r.Method != "GET" && r.Method != "HEAD" { 19 | http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed) 20 | return 21 | } 22 | 23 | w.Write([]byte(` 24 | cam2ip 25 | 26 |

cam2ip

27 |

html

28 |

jpeg

29 |

mjpeg

30 | 31 | `)) 32 | } 33 | -------------------------------------------------------------------------------- /handlers/jpeg.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | 7 | "github.com/gen2brain/cam2ip/image" 8 | "github.com/gen2brain/cam2ip/reader" 9 | ) 10 | 11 | // JPEG handler. 12 | type JPEG struct { 13 | reader reader.ImageReader 14 | } 15 | 16 | // NewJPEG returns new JPEG handler. 17 | func NewJPEG(reader reader.ImageReader) *JPEG { 18 | return &JPEG{reader} 19 | } 20 | 21 | // ServeHTTP handles requests on incoming connections. 22 | func (j *JPEG) ServeHTTP(w http.ResponseWriter, r *http.Request) { 23 | if r.Method != "GET" && r.Method != "HEAD" { 24 | http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed) 25 | return 26 | } 27 | 28 | w.Header().Add("Connection", "close") 29 | w.Header().Add("Cache-Control", "no-store, no-cache") 30 | w.Header().Add("Content-Type", "image/jpeg") 31 | 32 | img, err := j.reader.Read() 33 | if err != nil { 34 | log.Printf("jpeg: read: %v", err) 35 | return 36 | } 37 | 38 | err = image.NewEncoder(w).Encode(img) 39 | if err != nil { 40 | log.Printf("jpeg: encode: %v", err) 41 | return 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /handlers/mjpeg.go: -------------------------------------------------------------------------------- 1 | // Package handlers. 2 | package handlers 3 | 4 | import ( 5 | "fmt" 6 | "log" 7 | "mime/multipart" 8 | "net/http" 9 | "net/textproto" 10 | "time" 11 | 12 | "github.com/gen2brain/cam2ip/image" 13 | "github.com/gen2brain/cam2ip/reader" 14 | ) 15 | 16 | // MJPEG handler. 17 | type MJPEG struct { 18 | reader reader.ImageReader 19 | delay int 20 | } 21 | 22 | // NewMJPEG returns new MJPEG handler. 23 | func NewMJPEG(reader reader.ImageReader, delay int) *MJPEG { 24 | return &MJPEG{reader, delay} 25 | } 26 | 27 | // ServeHTTP handles requests on incoming connections. 28 | func (m *MJPEG) ServeHTTP(w http.ResponseWriter, r *http.Request) { 29 | if r.Method != "GET" && r.Method != "HEAD" { 30 | http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed) 31 | return 32 | } 33 | 34 | mimeWriter := multipart.NewWriter(w) 35 | mimeWriter.SetBoundary("--boundary") 36 | 37 | w.Header().Add("Connection", "close") 38 | w.Header().Add("Cache-Control", "no-store, no-cache") 39 | w.Header().Add("Content-Type", fmt.Sprintf("multipart/x-mixed-replace;boundary=%s", mimeWriter.Boundary())) 40 | 41 | cn := w.(http.CloseNotifier).CloseNotify() 42 | 43 | loop: 44 | for { 45 | select { 46 | case <-cn: 47 | break loop 48 | 49 | default: 50 | partHeader := make(textproto.MIMEHeader) 51 | partHeader.Add("Content-Type", "image/jpeg") 52 | 53 | partWriter, err := mimeWriter.CreatePart(partHeader) 54 | if err != nil { 55 | log.Printf("mjpeg: createPart: %v", err) 56 | continue 57 | } 58 | 59 | img, err := m.reader.Read() 60 | if err != nil { 61 | log.Printf("mjpeg: read: %v", err) 62 | continue 63 | } 64 | 65 | err = image.NewEncoder(partWriter).Encode(img) 66 | if err != nil { 67 | log.Printf("mjpeg: encode: %v", err) 68 | continue 69 | } 70 | 71 | time.Sleep(time.Duration(m.delay) * time.Millisecond) 72 | } 73 | } 74 | 75 | mimeWriter.Close() 76 | } 77 | -------------------------------------------------------------------------------- /handlers/socket.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "log" 7 | "net/http" 8 | "time" 9 | 10 | "nhooyr.io/websocket" 11 | 12 | "github.com/gen2brain/cam2ip/image" 13 | "github.com/gen2brain/cam2ip/reader" 14 | ) 15 | 16 | // Socket handler. 17 | type Socket struct { 18 | reader reader.ImageReader 19 | delay int 20 | } 21 | 22 | // NewSocket returns new socket handler. 23 | func NewSocket(reader reader.ImageReader, delay int) *Socket { 24 | return &Socket{reader, delay} 25 | } 26 | 27 | // ServeHTTP handles requests on incoming connections. 28 | func (s *Socket) ServeHTTP(w http.ResponseWriter, r *http.Request) { 29 | conn, err := websocket.Accept(w, r, nil) 30 | if err != nil { 31 | log.Printf("socket: accept: %v", err) 32 | return 33 | } 34 | 35 | ctx := context.Background() 36 | 37 | for { 38 | img, err := s.reader.Read() 39 | if err != nil { 40 | log.Printf("socket: read: %v", err) 41 | break 42 | } 43 | 44 | w := new(bytes.Buffer) 45 | 46 | err = image.NewEncoder(w).Encode(img) 47 | if err != nil { 48 | log.Printf("socket: encode: %v", err) 49 | continue 50 | } 51 | 52 | b64 := image.EncodeToString(w.Bytes()) 53 | 54 | err = conn.Write(ctx, websocket.MessageText, []byte(b64)) 55 | if err != nil { 56 | break 57 | } 58 | 59 | time.Sleep(time.Duration(s.delay) * time.Millisecond) 60 | } 61 | 62 | conn.Close(websocket.StatusNormalClosure, "") 63 | } 64 | -------------------------------------------------------------------------------- /image/base64.go: -------------------------------------------------------------------------------- 1 | //go:build !amd64 2 | // +build !amd64 3 | 4 | package image 5 | 6 | import ( 7 | "encoding/base64" 8 | ) 9 | 10 | func EncodeToString(src []byte) string { 11 | return base64.StdEncoding.EncodeToString(src) 12 | } 13 | -------------------------------------------------------------------------------- /image/base64_amd64.go: -------------------------------------------------------------------------------- 1 | //go:build amd64 2 | // +build amd64 3 | 4 | package image 5 | 6 | import ( 7 | "github.com/gen2brain/base64" 8 | ) 9 | 10 | func EncodeToString(src []byte) string { 11 | return base64.StdEncoding.EncodeToString(src) 12 | } 13 | -------------------------------------------------------------------------------- /image/decode.go: -------------------------------------------------------------------------------- 1 | //go:build turbo 2 | // +build turbo 3 | 4 | // Package image. 5 | package image 6 | 7 | import ( 8 | "image" 9 | "io" 10 | 11 | jpeg "github.com/antonini/golibjpegturbo" 12 | ) 13 | 14 | // NewDecoder returns a new Decoder. 15 | func NewDecoder(r io.Reader) *Decoder { 16 | return &Decoder{r} 17 | } 18 | 19 | // Decoder struct. 20 | type Decoder struct { 21 | r io.Reader 22 | } 23 | 24 | // Decode decodes image from JPEG. 25 | func (d Decoder) Decode() (image.Image, error) { 26 | return jpeg.Decode(d.r) 27 | } 28 | -------------------------------------------------------------------------------- /image/decode_jpeg.go: -------------------------------------------------------------------------------- 1 | //go:build !turbo 2 | // +build !turbo 3 | 4 | // Package image. 5 | package image 6 | 7 | import ( 8 | "image" 9 | "image/jpeg" 10 | "io" 11 | ) 12 | 13 | // NewDecoder returns a new Decoder. 14 | func NewDecoder(r io.Reader) *Decoder { 15 | return &Decoder{r} 16 | } 17 | 18 | // Decoder struct. 19 | type Decoder struct { 20 | r io.Reader 21 | } 22 | 23 | // Decode decodes image from JPEG. 24 | func (d Decoder) Decode() (image.Image, error) { 25 | return jpeg.Decode(d.r) 26 | } 27 | -------------------------------------------------------------------------------- /image/encode.go: -------------------------------------------------------------------------------- 1 | //go:build turbo 2 | // +build turbo 3 | 4 | // Package image. 5 | package image 6 | 7 | import ( 8 | "image" 9 | "io" 10 | 11 | jpeg "github.com/antonini/golibjpegturbo" 12 | ) 13 | 14 | // NewEncoder returns a new Encoder. 15 | func NewEncoder(w io.Writer) *Encoder { 16 | return &Encoder{w} 17 | } 18 | 19 | // Encoder struct. 20 | type Encoder struct { 21 | w io.Writer 22 | } 23 | 24 | // Encode encodes image to JPEG. 25 | func (e Encoder) Encode(img image.Image) error { 26 | err := jpeg.Encode(e.w, img, &jpeg.Options{Quality: 75}) 27 | if err != nil { 28 | return err 29 | } 30 | 31 | return nil 32 | } 33 | -------------------------------------------------------------------------------- /image/encode_jpeg.go: -------------------------------------------------------------------------------- 1 | //go:build !turbo 2 | // +build !turbo 3 | 4 | // Package image. 5 | package image 6 | 7 | import ( 8 | "image" 9 | "image/jpeg" 10 | "io" 11 | ) 12 | 13 | // NewEncoder returns a new Encoder. 14 | func NewEncoder(w io.Writer) *Encoder { 15 | return &Encoder{w} 16 | } 17 | 18 | // Encoder struct. 19 | type Encoder struct { 20 | w io.Writer 21 | } 22 | 23 | // Encode encodes image to JPEG. 24 | func (e Encoder) Encode(img image.Image) error { 25 | err := jpeg.Encode(e.w, img, &jpeg.Options{Quality: 75}) 26 | if err != nil { 27 | return err 28 | } 29 | 30 | return nil 31 | } 32 | -------------------------------------------------------------------------------- /make.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CHROOT="/usr/x86_64-pc-linux-gnu-static" 4 | MINGW="/usr/i686-w64-mingw32" 5 | MINGW64="/usr/x86_64-w64-mingw32" 6 | RPI="/usr/armv6j-hardfloat-linux-gnueabi" 7 | RPI3="/usr/armv7a-hardfloat-linux-gnueabi" 8 | APPLE="/usr/x86_64-apple-darwin14" 9 | ANDROID="/usr/arm-linux-androideabi" 10 | 11 | mkdir -p build 12 | 13 | LIBRARY_PATH="$CHROOT/usr/lib64:$CHROOT/lib64" \ 14 | PKG_CONFIG_PATH="$CHROOT/usr/lib64/pkgconfig" \ 15 | PKG_CONFIG_LIBDIR="$CHROOT/usr/lib64/pkgconfig" \ 16 | CGO_LDFLAGS="-L$CHROOT/usr/lib64 -L$CHROOT/lib" \ 17 | CGO_CFLAGS="-I$CHROOT/usr/include" \ 18 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags cv2,turbo -o build/cam2ip.linux.amd64.cv2 -ldflags "-linkmode external -s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 19 | 20 | LIBRARY_PATH="$CHROOT/usr/lib64:$CHROOT/lib64" \ 21 | PKG_CONFIG_PATH="$CHROOT/usr/lib64/pkgconfig" \ 22 | PKG_CONFIG_LIBDIR="$CHROOT/usr/lib64/pkgconfig" \ 23 | CGO_LDFLAGS="-L$CHROOT/usr/lib64 -L$CHROOT/lib64" \ 24 | CGO_CFLAGS="-I$CHROOT/usr/include" \ 25 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o build/cam2ip.linux.amd64 -ldflags "-linkmode external -s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 26 | 27 | PKG_CONFIG="/usr/bin/x86_64-w64-mingw32-pkg-config" \ 28 | PKG_CONFIG_PATH="$MINGW64/usr/lib/pkgconfig" \ 29 | PKG_CONFIG_LIBDIR="$MINGW64/usr/lib/pkgconfig" \ 30 | CGO_LDFLAGS="-L$MINGW64/usr/lib" \ 31 | CGO_CFLAGS="-I$MINGW64/usr/include" \ 32 | CC="x86_64-w64-mingw32-gcc" CXX="x86_64-w64-mingw32-g++" \ 33 | CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -tags cv2,turbo,pkgconfig -o build/cam2ip.amd64.cv2.exe -ldflags "-linkmode external -s -w '-extldflags=-static'" github.com/gen2brain/cam2ip/cmd/cam2ip 34 | 35 | PKG_CONFIG="/usr/bin/x86_64-w64-mingw32-pkg-config" \ 36 | PKG_CONFIG_PATH="$MINGW64/usr/lib/pkgconfig" \ 37 | PKG_CONFIG_LIBDIR="$MINGW64/usr/lib/pkgconfig" \ 38 | CGO_LDFLAGS="-L$MINGW64/usr/lib" \ 39 | CGO_CFLAGS="-I$MINGW64/usr/include" \ 40 | CC="x86_64-w64-mingw32-gcc" CXX="x86_64-w64-mingw32-g++" \ 41 | CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -o build/cam2ip.amd64.exe -ldflags "-linkmode external -s -w '-extldflags=-static'" github.com/gen2brain/cam2ip/cmd/cam2ip 42 | 43 | PKG_CONFIG="/usr/bin/armv7a-hardfloat-linux-gnueabi-pkg-config" \ 44 | PKG_CONFIG_PATH="$RPI3/usr/lib/pkgconfig" \ 45 | PKG_CONFIG_LIBDIR="$RPI3/usr/lib/pkgconfig" \ 46 | CGO_LDFLAGS="-L$RPI3/usr/lib" \ 47 | CGO_CFLAGS="-I$RPI3/usr/include" \ 48 | CC="armv7a-hardfloat-linux-gnueabi-gcc" CXX="armv7a-hardfloat-linux-gnueabi-g++" \ 49 | CGO_ENABLED=1 GOOS=linux GOARCH=arm go build -tags cv2,turbo -o build/cam2ip.linux.arm7.cv2 -ldflags "-linkmode external -s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 50 | 51 | PKG_CONFIG="/usr/bin/armv7a-hardfloat-linux-gnueabi-pkg-config" \ 52 | PKG_CONFIG_PATH="$RPI3/usr/lib/pkgconfig" \ 53 | PKG_CONFIG_LIBDIR="$RPI3/usr/lib/pkgconfig" \ 54 | CGO_LDFLAGS="-L$RPI3/usr/lib" \ 55 | CGO_CFLAGS="-I$RPI3/usr/include" \ 56 | CC="armv7a-hardfloat-linux-gnueabi-gcc" CXX="armv7a-hardfloat-linux-gnueabi-g++" \ 57 | CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -o build/cam2ip.linux.arm7 -ldflags "-linkmode external -s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 58 | 59 | PKG_CONFIG_PATH="$APPLE/SDK/MacOSX10.10.sdk/usr/lib/pkgconfig" \ 60 | PKG_CONFIG_LIBDIR="$APPLE/SDK/MacOSX10.10.sdk/usr/lib/pkgconfig" \ 61 | CGO_LDFLAGS="-L$APPLE/SDK/MacOSX10.10.sdk/usr/lib -mmacosx-version-min=10.10" \ 62 | CGO_CFLAGS="-I$APPLE/SDK/MacOSX10.10.sdk/usr/include -mmacosx-version-min=10.10" \ 63 | CC="$APPLE/bin/x86_64-apple-darwin14-clang" CXX="$APPLE/bin/x86_64-apple-darwin14-clang++" \ 64 | CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -tags cv2,turbo -o build/cam2ip.darwin.amd64 -ldflags "-linkmode external -s -w '-extldflags=-mmacosx-version-min=10.10'" github.com/gen2brain/cam2ip/cmd/cam2ip 65 | 66 | PKG_CONFIG_PATH="$ANDROID/lib/pkgconfig" \ 67 | PKG_CONFIG_LIBDIR="$ANDROID/lib/pkgconfig" \ 68 | CGO_LDFLAGS="-L$ANDROID/sysroot/usr/lib" \ 69 | CGO_CFLAGS="-I$ANDROID/sysroot/usr/include --sysroot=$ANDROID/sysroot" \ 70 | CC="$ANDROID/bin/arm-linux-androideabi-clang" CXX="$ANDROID/bin/arm-linux-androideabi-clang++" \ 71 | CGO_ENABLED=1 GOOS=android GOARCH=arm go build -o build/cam2ip.android.arm7 -ldflags "-linkmode external -s -w" github.com/gen2brain/cam2ip/cmd/cam2ip 72 | -------------------------------------------------------------------------------- /reader/reader.go: -------------------------------------------------------------------------------- 1 | // Package reader. 2 | package reader 3 | 4 | import ( 5 | "image" 6 | ) 7 | 8 | // ImageReader interface 9 | type ImageReader interface { 10 | // Read reads next frame from camera/video and returns image. 11 | Read() (img image.Image, err error) 12 | 13 | // Close closes camera/video. 14 | Close() error 15 | } 16 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | // Package server. 2 | package server 3 | 4 | import ( 5 | "fmt" 6 | "net" 7 | "net/http" 8 | 9 | "github.com/abbot/go-http-auth" 10 | 11 | "github.com/gen2brain/cam2ip/handlers" 12 | "github.com/gen2brain/cam2ip/reader" 13 | ) 14 | 15 | // Server struct. 16 | type Server struct { 17 | Name string 18 | Version string 19 | 20 | Bind string 21 | Htpasswd string 22 | 23 | Index int 24 | Delay int 25 | 26 | FrameWidth float64 27 | FrameHeight float64 28 | 29 | Rotate int 30 | 31 | NoWebGL bool 32 | Timestamp bool 33 | 34 | FileName string 35 | 36 | Reader reader.ImageReader 37 | } 38 | 39 | // NewServer returns new Server. 40 | func NewServer() *Server { 41 | s := &Server{} 42 | return s 43 | } 44 | 45 | // ListenAndServe listens on the TCP address and serves requests. 46 | func (s *Server) ListenAndServe() error { 47 | var basic *auth.BasicAuth 48 | if s.Htpasswd != "" { 49 | realm := fmt.Sprintf("%s/%s", s.Name, s.Version) 50 | basic = auth.NewBasicAuthenticator(realm, auth.HtpasswdFileProvider(s.Htpasswd)) 51 | } 52 | 53 | http.Handle("/html", newAuthHandler(handlers.NewHTML(s.FrameWidth, s.FrameHeight, s.NoWebGL), basic)) 54 | http.Handle("/jpeg", newAuthHandler(handlers.NewJPEG(s.Reader), basic)) 55 | http.Handle("/mjpeg", newAuthHandler(handlers.NewMJPEG(s.Reader, s.Delay), basic)) 56 | http.Handle("/socket", newAuthHandler(handlers.NewSocket(s.Reader, s.Delay), basic)) 57 | 58 | http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { 59 | w.WriteHeader(http.StatusOK) 60 | }) 61 | 62 | http.Handle("/", newAuthHandler(handlers.NewIndex(), basic)) 63 | 64 | srv := &http.Server{} 65 | 66 | listener, err := net.Listen("tcp", s.Bind) 67 | if err != nil { 68 | return err 69 | } 70 | 71 | return srv.Serve(listener) 72 | } 73 | 74 | // newAuthHandler wraps handler and checks auth. 75 | func newAuthHandler(handler http.Handler, authenticator *auth.BasicAuth) http.Handler { 76 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 77 | if authenticator != nil { 78 | w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", authenticator.Realm)) 79 | if authenticator.CheckAuth(r) == "" { 80 | http.Error(w, "401 Unauthorized", http.StatusUnauthorized) 81 | return 82 | } 83 | } 84 | 85 | handler.ServeHTTP(w, r) 86 | }) 87 | } 88 | --------------------------------------------------------------------------------