├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── all.sh
├── command.txt
├── control
├── Makefile
├── control.c
├── controlhidc.c
└── keyboardonly.c
├── d2.py
├── d2vlc.py
├── d2win10debug.py
├── h264
├── Makefile
├── Makefile.include
├── audio.c
├── audio.h
└── h264.c
├── lazycast.service
├── logging.sh
├── mice.sh
├── newmice.py
├── player
├── Makefile
├── Makefile.include
├── mtlinklist.c
└── player.c
├── project.py
├── removep2p.sh
├── resetwpa.sh
├── scan.py
├── vlcbased.sh
├── win10debug.sh
└── wiresharkscript.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | control/*.bin
2 | h264/h264.bin
3 | player/player.bin
4 | udhcpd.conf
5 | uuid.txt
6 | edid.txt
7 | nohup.out
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SUBDIRS := $(wildcard */.)
2 |
3 | all: $(SUBDIRS)
4 | $(SUBDIRS):
5 | $(MAKE) -C $@
6 |
7 | .PHONY: all $(SUBDIRS)
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | lazycast: A Simple Wireless Display Receiver
2 |
3 | # Description
4 | lazycast is a simple wifi display receiver. It was originally targeted Raspberry Pi (as display) and Windows 8.1/10 (as source), but it **might** also work on other Linux platforms and Miracast sources. (For other Linux systems, skip the preparation section. For video playback from Android sources, modify the ``player_select`` option in ``d2.py``.) For Windows 10 systems, the Miracast over Infrastructure (**MICE**) feature is also supported, which may provide better user experiences. In general, lazycast does not require re-compilation of wpa_supplicant to support various p2p functionalities, and should work on an "out of the box" Raspberry Pi.
5 |
6 | # OS
7 | Select "**Raspberry Pi OS (Legacy, 32-bit)** A port of Debian Bullseye with security updates and desktop environment" when flashing the SD card. Debian Bookworm seems to cause some issues.
8 |
9 | On a fresh OS, install ``cmake``:
10 | ```
11 | sudo apt install cmake
12 | ```
13 | Clone the Raspberry Pi userland repo and run ``buildme``:
14 | ```
15 | git clone https://github.com/raspberrypi/userland
16 | cd userland
17 | ./buildme
18 | ```
19 | Replace ``vc4-kms-v3d`` with ``vc4-fkms-v3d`` in ``/boot/config.txt``:
20 | ```
21 | sudo sed -i 's/vc4-kms-v3d/vc4-fkms-v3d/g' /boot/config.txt
22 | ```
23 | Then reboot:
24 | ```
25 | sudo reboot
26 | ```
27 | (You can see [this post](https://github.com/homeworkc/lazycast/issues/100#issuecomment-1003732280) for more details.)
28 | ## Build Binaries
29 | Install packages (for compiling the players):
30 | ```
31 | sudo apt install libx11-dev libasound2-dev libavformat-dev libavcodec-dev python3-evdev
32 | ```
33 | Compile libraries on Pi:
34 | ```
35 | cd /opt/vc/src/hello_pi/libs/ilclient/
36 | sudo make
37 | cd /opt/vc/src/hello_pi/hello_video
38 | sudo make
39 | ```
40 | Clone this repo (to a desired directory):
41 | ```
42 | cd ~/
43 | git clone https://github.com/homeworkc/lazycast
44 | ```
45 | Go to the ``lazycast`` directory and then ``make``:
46 | ```
47 | cd lazycast
48 | make
49 | ```
50 |
51 | # Usage
52 | Run `./all.sh` to start lazycast receiver. Wait until the "The display is ready" message. The name of the display will appear after this message. Then, search for this name on the source device you want to cast. The default PIN number is ``31415926``.
53 |
54 | It is recommended to stop casting by the controls on the source (e.g., the PC) side.
55 |
56 | # Tips
57 | Set the resolution on the source side. lazycast advertises all possible resolutions regardless of the current rendering resolution. Therefore, you may want to change the resolution (on the source) to match the actual resolution of the display connecting to Pi.
58 |
59 | Modify parameters in the "settings" section in ``d2.py`` to change the sound output port (hdmi/3.5mm) and preferred player.
60 |
61 | The maximum resolutions supported are 1920x1080p60 and 1920x1200p30. The GPU on Pi may struggle to handle 1920x1080p60, which results in high latency. In this case, reduce the FPS to 1920x1080p50.
62 |
63 | To change the default PIN number, replace the string ``31415926`` in ``all.sh`` to another 8-digit number.
64 |
65 | You can hide Pi's cursor by using ``unclutter -idle 3``. See [this post](https://forums.raspberrypi.com/viewtopic.php?t=234879#p1437648).
66 |
67 | After Pi connects to the source, it has an IP address of ``192.168.173.1`` and this connection can be reused for other purposes like SSH. On the other hand, since they are under the same subnet, precautions should be taken to prevent unauthorized access to Pi by anyone who knows the PIN number.
68 |
69 | Two in-house players are written for Raspberry Pi 3. VLC, omxplayer or gstreamer can be used instead on other platforms. (See [here](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html) for details of installing gstreamer.)
70 |
71 | **It is very important that no background WiFi scanning occurs during casting. On Raspberry Pi, lazycast will automatically disable ``lxpanel`` during casting (in order to stop the ``lxplug-network`` plugin from scanning the network), and re-enable ``lxpanel`` after the casting is terminated. You may want to disable ``wlan0`` completely (``sudo ifconfig wlan0 down``) especially if ``wlan0`` is not currently connected to any network (and periodic scanning will be triggered in such a case). You can double-check that no background WiFi scanning happens by running ``iw event`` in a second terminal (and no event should be shown). [This post](https://forums.raspberrypi.com/viewtopic.php?t=250729#p1772473) has more information.**
72 |
73 |
74 | To redirect mouse and keyboard inputs on Pi, first install evdev (``pip install evdev``) and then set ``enable_mouse_keyboard`` to ``1`` in ``d2.py``. You also need to allow mouse and keyboard inputs on the PC.
75 |
76 | # Known issues
77 | lazycast tries to remember the pairing credentials so that entering the PIN is only needed once for each device. However, this feature does not seem to work properly all the time with recent Raspbian images. Therefore, re-pairing may be needed after every Raspberry Pi reboot. Try clearing the 'lazycast' information on the source device before re-pairing if you run into pairing problems.
78 |
79 | Player2 seems to have a double-free bug which causes it to crash when playing some videos. Currently a workaround (that constantly monitors the liveliness of player2) is implemented.
80 |
81 | Latency: Limited by the implementation of the rtp player used. (In VLC, latency can be reduced from 1200 to 300ms by lowering the network cache value.)
82 |
83 | Due to the overcrowded nature of the wifi spectrum and the use of unreliable rtp transmission, you may experience some video glitching/audio stuttering. The in-house players employ several mechanisms to conceal transmission error, but it may still be noticeable in challenging wireless environments. Interference from other devices may cause disconnections.
84 |
85 | Devices may not fully support backchannel control and some keystrokes/clicks will behave differently.
86 |
87 | HDCP(content protection): Neither the key nor the hardware is available on Pi and therefore is not supported.
88 |
89 |
90 |
91 | # Start on boot
92 |
93 | Append this line to ``/etc/xdg/lxsession/LXDE-pi/autostart``:
94 | ```
95 | @lxterminal -l --working-directory= -e ./all.sh
96 | ```
97 | For example, if lazycast is placed under ``~/`` (which is ``/home/pi/``, if your username is ``pi``), append the following line to the file:
98 | ```
99 | @lxterminal -l --working-directory=/home/pi/lazycast -e ./all.sh
100 | ```
101 |
102 | # Miracast over Infrastructure
103 |
104 | For Windows 10 sources, Miracast over Infrastructure (MICE) is a feature that allows transmission of screen data over Ethernet or secure wifi networks. The spec of Miracast over Infrastructure (MICE) is available [here](https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-MICE/%5bMS-MICE%5d.pdf). Compared to wifi p2p, it allows stabler connection and lower latency. Although MICE relies on Ethernet or secure wifi network almost entirely, in the device discovery phase, it still requires a wifi p2p device to broadcast beacon and probe response frames to the source. (However, it might be possible to use two Pis so that one of the two does not need to have wifi hardware or be physically close to the source. One Pi would be used to trasmit the beacon while the other (that runs ``./project.py``) is used to project. For such setting to work, the variable ``hostname`` in ``mice.py`` must be set to the hostname of the machine running ``project.py``. In the future, it might be possible to emulate a wifi card by HW/SW on the source so that wifi p2p will not be necessary.)
105 |
106 | Currently, this feature is tested to be working with a Windows 10 PC and a Pi (with manually assigned IPs) connected via Ethernet. More tests might be needed, especially for different DHCP, DNS and firewall configurations. Ports used include but are not limited to UDP 53 (DNS), UDP 5353 (mDNS), TCP 7236 and TCP 7250. Also, the encryption feature is not implemented yet so it should only be used over trusted networks and it should not be used for sensitive data. MICE works in ipv6 networks but currently only ipv4 is implemented.
107 |
108 | ## Preparation
109 | Install avahi-utils:
110 | ```
111 | sudo apt install avahi-utils
112 | ```
113 | Make sure the Windows 10 PC is on the same network as the Pi. You can try pinging the Pi from the PC.
114 | NetworkManager is **not** required for this version of MICE. However, using MICE will disable the built-in WiFi UI. (To restore the built-in WiFi UI after MICE, either run ``resetwpa.sh`` or simply reboot.)
115 | ## Usage
116 | Make sure there is no p2p interface that has already been created and ``all.sh`` is not running. (Make sure ``all.sh`` does not start on boot and then simply reboot.)
117 |
118 | Run ``./mice.sh``.
119 |
120 | Use the "Connect" tab in Windows 10 and try to connect to the hostname of Pi (e.g., raspberrypi). Windows may try to connect using the traditional method first and therefore may ask for PIN. In that case, simply cancel the connecting process and try again. Since no encryption is implemented at the moment, the prompt for PIN should not appear using MICE.
121 |
122 | Windows 10 assigns the name of the display differently when using MICE. If the monitor connected to the Pi is successfully detected by the PC, the name of the display (e.g., raspberrypi) will be changed to the name of the monitor. If the detection fails, the name of the display will be changed to "Device". After disconnection, the name of the display will be changed back to the hostname of Pi (e.g., raspberrypi).
123 |
124 | If you wish to run MICE and wifi p2p simultaneously, set the parameter ``concurrent`` to ``1`` in ``newmice.py`` and only uses ``mice.sh``. When there are multiple IPs assigned to the Pi and mDNS does not seem to be working, manually set the ``ipstr`` variable in ``newmice.py`` to the target IP of Pi and a PC will try to connect to this IP directly.
125 | # Others
126 | Some parts of the video player1 are modified from the codes on https://github.com/Apress/raspberry-pi-gpu-audio-video-prog. Many thanks to the author of "Raspberry Pi GPU Audio Video Programming" and, by extension, authors of omxplayer.
127 | Using any part of the codes in this project in commercial products is prohibited.
128 |
--------------------------------------------------------------------------------
/all.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #################################################################################
3 | # Run script for lazycast
4 | # Licensed under GNU General Public License v3.0 GPL-3 (in short)
5 | #
6 | # You may copy, distribute and modify the software as long as you track
7 | # changes/dates in source files. Any modifications to our software
8 | # including (via compiler) GPL-licensed code must also be made available
9 | # under the GPL along with build & install instructions.
10 | #
11 | #################################################################################
12 | managefrequency=0
13 | LD_LIBRARY_PATH=/opt/vc/lib
14 | export LD_LIBRARY_PATH
15 | while :
16 | do
17 | p2pdevinterface=$(sudo wpa_cli interface | grep -E "p2p-dev" | tail -1)
18 | wlaninterface=$(echo $p2pdevinterface | cut -c1-8 --complement)
19 | echo $p2pdevinterface
20 | echo $wlaninterface
21 | ain="$(sudo wpa_cli interface)"
22 | echo "${ain}"
23 | if [ `echo "${ain}" | grep -c "p2p-wl"` -gt 0 ]
24 | then
25 | echo "already on"
26 |
27 | else
28 | sudo wpa_cli -i$p2pdevinterface p2p_find type=progressive
29 | sudo wpa_cli -i$p2pdevinterface set device_name "$(uname -n)"
30 | sudo wpa_cli -i$p2pdevinterface set device_type 7-0050F204-1
31 | sudo wpa_cli -i$p2pdevinterface set p2p_go_ht40 1
32 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 0 000600111c44012c
33 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 1 0006000000000000
34 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 6 000700000000000000
35 | perentry="$(sudo wpa_cli -i$p2pdevinterface list_networks | grep "\[DISABLED\]\[P2P-PERSISTENT\]" | tail -1)"
36 | echo "${perentry}"
37 | if [ `echo "${perentry}" | grep -c "P2P-PERSISTENT"` -gt 0 ]
38 | then
39 | networkid=${perentry%%D*}
40 | perstr="=${networkid}"
41 | else
42 | perstr=""
43 | fi
44 | echo "${perstr}"
45 | echo "${p2pdevinterface}"
46 | wlanfreq=$(sudo wpa_cli -i$wlaninterface status | grep "freq")
47 | if [ "$managefrequency" == "0" ]
48 | then
49 | wlanfreq=""
50 | fi
51 | if [ "$wlanfreq" != "" ]
52 | then
53 | echo $wlaninterface": "$wlanfreq
54 | echo "Setting up wifi p2p with "$wlanfreq
55 | fi
56 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
57 | do
58 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
59 | do
60 | #sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr freq=2
61 | result=$(sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr)
62 | if [ "$result" == "FAIL" ]
63 | then
64 | wlanfreq=""
65 | managefrequency=0
66 | fi
67 | sleep 2
68 | ain="$(sudo wpa_cli interface)"
69 | echo "$ain"
70 | done
71 | sleep 5
72 | ain="$(sudo wpa_cli interface)"
73 | echo "$ain"
74 | done
75 |
76 | fi
77 |
78 | p2pinterface=$(echo "${ain}" | grep "p2p-wl" | grep -v "interface")
79 | echo $p2pinterface
80 |
81 | sudo ifconfig $p2pinterface 192.168.173.1
82 | printf "start 192.168.173.80\n">udhcpd.conf
83 | printf "end 192.168.173.80\n">>udhcpd.conf
84 | printf "interface $p2pinterface\n">>udhcpd.conf
85 | printf "option subnet 255.255.255.0\n">>udhcpd.conf
86 | printf "option lease 10000">>udhcpd.conf
87 | sleep 3
88 | sudo busybox udhcpd ./udhcpd.conf
89 | echo "The display is ready"
90 | echo "Your device is called: "$(uname -n)""
91 | while :
92 | do
93 | echo "PIN:"
94 | sudo wpa_cli -i$p2pinterface wps_pin any 31415926
95 | echo ""
96 | ./d2.py
97 | if [ `sudo wpa_cli interface | grep -c "p2p-wl"` == 0 ]
98 | then
99 | break
100 | fi
101 |
102 | wlanfreq=$(sudo wpa_cli -i$wlaninterface status | grep "freq")
103 | p2pfreq=$(sudo wpa_cli -i$p2pinterface status | grep "freq")
104 | if [ "$managefrequency" == "0" ]
105 | then
106 | wlanfreq=""
107 | fi
108 | if [ "$wlanfreq" != "" ]
109 | then
110 | if [ "$wlanfreq" != "$p2pfreq" ]
111 | then
112 | echo "The display is disconnected since "$wlaninterface" changes from "$p2pfreq" to "$wlanfreq
113 | echo "To disable WLAN roaming, run: sudo killall -STOP NetworkManager"
114 | echo "You can re-enable roaming afterwards by running: sudo killall -CONT NetworkManager"
115 | sudo wpa_cli -i$p2pinterface p2p_group_remove $p2pinterface
116 | while :
117 | do
118 | if [ `sudo wpa_cli interface | grep -c "p2p-wl"` == 0 ]
119 | then
120 | break
121 | fi
122 | done
123 | break
124 | fi
125 | fi
126 |
127 | done
128 | done
129 |
--------------------------------------------------------------------------------
/command.txt:
--------------------------------------------------------------------------------
1 | wget https://w1.fi/releases/wpa_supplicant-2.9.tar.gz
2 | tar -xvf wpa_supplicant-2.9.tar.gz
3 |
4 | sudo apt install libdbus-1-dev libnl-3-dev libnl-genl-3-dev libssl-dev
5 |
6 | cd wpa_supplicant-2.9/wpa_supplicant
7 | cp defconfig .config
8 | make
9 | sudo mv /usr/local/bin/wpa_supplicant /usr/local/bin/wpa_supplicant_old
10 | sudo cp wpa_cli wpa_supplicant /usr/local/bin
11 | sudo rm /usr/local/bin/wpa_supplicant_old
12 | sudo reboot
13 |
--------------------------------------------------------------------------------
/control/Makefile:
--------------------------------------------------------------------------------
1 |
2 | OBJS = controlhidc.o control.o
3 | BIN = controlhidc.bin control.bin
4 |
5 |
6 | CFLAGS = -O2 -Wall
7 | LDFLAGS = -L /usr/X11R6/lib -lX11 -lm
8 | INCLUDES=
9 |
10 | all: $(BIN) $(LIB)
11 |
12 | %.o: %.c
13 | $(CC) $(CFLAGS) $(INCLUDES) -g -c $< -o $@
14 |
15 | %.bin: %.o
16 | $(CC) -o $@ $< $(LDFLAGS)
17 |
--------------------------------------------------------------------------------
/control/control.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 |
15 |
16 | char mousemove[] = {
17 | 0x00,0x00,
18 | 0x00,20,
19 | 0x02,0x00,
20 | 0x06,0x01,
21 | 0x00,0x00,
22 | 0x00,0x00,
23 | 0x00 ,0x00,
24 | 0x00,0x00,
25 | 0x00,0x00,
26 | 0x00,0x00
27 | };
28 |
29 | char scroll[] = {
30 | 0x00,0x00,
31 | 0x00, 16,
32 | 0x06,
33 | 0x00,0x02,
34 | 0x40,0x02,
35 | 0x00,
36 | 0x00,0x00,
37 | 0x00,0x00,
38 | 0x00,0x00
39 | };
40 |
41 | char keyboard[] = {
42 | 0x00,0x00,
43 | 0x00, 20,
44 | 0x03,
45 | 0x00,0x05,
46 | 0x00,
47 | 0x00,0x00,//key1
48 | 0x00,0x00,//key2
49 | 0x00,0x00,
50 | 0x00,0x00,
51 | 0x00,0x00,
52 | 0x00,0x00
53 | };
54 |
55 |
56 | #define fdsend
57 | #define warpcursor
58 | int main(int argc, char **argv)
59 | {
60 | #ifdef fdsend
61 | int fd;
62 | if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
63 | {
64 | printf("socket failed!");
65 | exit(1);
66 | }
67 |
68 | struct sockaddr_in serveraddr;
69 |
70 | printf("using port:%s\n", argv[1]);
71 |
72 | memset(&serveraddr, 0, sizeof(serveraddr));
73 | serveraddr.sin_family = AF_INET;
74 | serveraddr.sin_addr.s_addr = inet_addr("192.168.173.80");
75 | serveraddr.sin_port = htons(atoi(argv[1]));
76 |
77 | int flag = 1;
78 |
79 | setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
80 |
81 |
82 | if (connect(fd, (struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0)
83 | {
84 | perror("connect failed!");
85 | exit(1);
86 | }
87 | #endif
88 |
89 |
90 | Display *d;
91 | int s;
92 | Window w;
93 | XEvent e;
94 |
95 | d = XOpenDisplay(":0.0");
96 | //d = XOpenDisplay(NULL);
97 | if (d == NULL)
98 | {
99 | printf("Cannot open display\n");
100 | exit(1);
101 | }
102 | s = DefaultScreen(d);
103 | int width = XWidthOfScreen(DefaultScreenOfDisplay(d));
104 | int height = XHeightOfScreen(DefaultScreenOfDisplay(d));
105 | w = XCreateSimpleWindow(d, RootWindow(d, s), 0, 0, width, height, 1, BlackPixel(d, s), WhitePixel(d, s));
106 |
107 | Atom delWindow = XInternAtom( d, "WM_DELETE_WINDOW", 0 );
108 | XSetWMProtocols(d , w, &delWindow, 1);
109 |
110 | XSelectInput(d, w, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask );
111 |
112 | XMapWindow(d, w);
113 |
114 | XWarpPointer(d, None, w, 0, 0, 0, 0, width/2, height/2);
115 |
116 |
117 | int x = 0, y = 0;
118 | int oldx = 0, oldy = 0;
119 | int warp = 0;
120 | while(1)
121 | {
122 |
123 |
124 |
125 |
126 |
127 | XNextEvent(d, &e);
128 | if (e.type == Expose)
129 | {
130 | ;
131 | }
132 | else if (e.type == ClientMessage)
133 | break;
134 | else if (e.type == KeyPress)
135 | {
136 | keyboard[4] = 0x03;
137 | printf("KeyPress code:%d\n", e.xkey.keycode);
138 |
139 |
140 | int keysyms_per_keycode_return;
141 | KeySym *keysym = XGetKeyboardMapping(d, e.xkey.keycode, 1, &keysyms_per_keycode_return);
142 |
143 | if ((*keysym) < 256)
144 | {
145 | char key;
146 | if (e.xkey.state & ShiftMask)
147 | key = keysym[1];
148 | else if (e.xkey.state & LockMask && keysym[0] > 0x60 && keysym[0] < 0x7B)
149 | key = keysym[1];
150 | else
151 | key = keysym[0];
152 |
153 |
154 |
155 | if (key != NoSymbol)
156 | {
157 |
158 | printf("%x ", key);
159 | //printf("%s ", XKeysymToString(key));
160 | keyboard[9] = key;
161 | #ifdef fdsend
162 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
163 | #endif
164 | }
165 | }
166 | else if ((*keysym) == 0xff08 || (*keysym) == 0xff09
167 | || (*keysym) == 0xff0a || (*keysym) == 0xff0b
168 | || (*keysym) == 0xff0d || (*keysym) == 0xff13
169 | || (*keysym) == 0xff14 || (*keysym) == 0xff15
170 | || (*keysym) == 0xff1b)
171 | {
172 | keyboard[9] = 0xFF & (*keysym);
173 | #ifdef fdsend
174 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
175 | #endif
176 | }
177 | else if ((*keysym) == 0xffff)
178 | {
179 | keyboard[9] = 0x7F;
180 | printf("special:%x\n", keyboard[9]);
181 | #ifdef fdsend
182 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
183 | #endif
184 | }
185 | else if ((*keysym) == 0xff52)
186 | {
187 | keyboard[9] = 38;
188 | printf("special:%x\n", keyboard[9]);
189 | #ifdef fdsend
190 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
191 | #endif
192 | }
193 |
194 |
195 |
196 |
197 |
198 | printf("%x\n", *keysym);
199 |
200 | //printf("%s\n", XKeysymToString(*keysym));
201 |
202 | XFree(keysym);
203 |
204 | }
205 | else if (e.type == KeyRelease)
206 | {
207 | keyboard[4] = 0x04;
208 | printf("KeyRelease code:%d\n", e.xkey.keycode);
209 |
210 |
211 | int keysyms_per_keycode_return;
212 | KeySym *keysym = XGetKeyboardMapping(d, e.xkey.keycode, 1, &keysyms_per_keycode_return);
213 |
214 | if ((*keysym) < 256)
215 | {
216 | char key;
217 | if (e.xkey.state & ShiftMask)
218 | key = keysym[1];
219 | else if (e.xkey.state & LockMask && keysym[0] > 0x60 && keysym[0] < 0x7B)
220 | key = keysym[1];
221 | else
222 | key = keysym[0];
223 |
224 | printf("here\n");
225 |
226 | if (key != NoSymbol)
227 | {
228 |
229 | printf("%x ", key);
230 | //printf("%s ", XKeysymToString(key));
231 | keyboard[9] = key;
232 | #ifdef fdsend
233 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
234 | #endif
235 |
236 | }
237 | }
238 | else if ((*keysym) == 0xff08 || (*keysym) == 0xff09
239 | || (*keysym) == 0xff0a || (*keysym) == 0xff0b
240 | || (*keysym) == 0xff0d || (*keysym) == 0xff13
241 | || (*keysym) == 0xff14 || (*keysym) == 0xff15
242 | || (*keysym) == 0xff1b)
243 | {
244 | keyboard[9] = 0xFF & (*keysym);
245 | printf("special:%x\n", keyboard[9]);
246 | #ifdef fdsend
247 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
248 | #endif
249 | }
250 | else if ( (*keysym) == 0xffff)
251 | {
252 | keyboard[9] = 0x7F;
253 | printf("special:%x\n", keyboard[9]);
254 | #ifdef fdsend
255 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
256 | #endif
257 | }
258 | else if ((*keysym) == 0xff52)
259 | {
260 | keyboard[9] = 38;
261 | printf("special:%x\n", keyboard[9]);
262 | #ifdef fdsend
263 | printf("send:%d\n", send(fd, keyboard, sizeof(keyboard), 0));
264 | #endif
265 | }
266 |
267 |
268 | //printf("%s\n", XKeysymToString(*keysym));
269 |
270 | XFree(keysym);
271 |
272 | }
273 | else if (e.type == ButtonPress)
274 | {
275 | int buttonnum = e.xbutton.button;
276 | printf("ButtonPress:%d\n", buttonnum);
277 |
278 | if (buttonnum < 4)
279 | {
280 | mousemove[4] = 0;
281 | mousemove[9] = x >> 8;
282 | mousemove[10] = 0xFF & x;
283 | mousemove[11] = y >> 8;
284 | mousemove[12] = 0xFF & y;
285 | #ifdef fdsend
286 | printf("send:%d\n", send(fd, mousemove, sizeof(mousemove), 0));
287 | #endif
288 | }
289 | else if(buttonnum < 6)
290 | {
291 | if (buttonnum == 4)
292 | {
293 | scroll[7] |= 0x20;
294 | }
295 | else
296 | {
297 | scroll[7] &= ~0x20;
298 | }
299 | #ifdef fdsend
300 | printf("send:%d\n", send(fd, scroll, sizeof(scroll), 0));
301 | #endif
302 |
303 | }
304 |
305 | }
306 | else if (e.type == ButtonRelease)
307 | {
308 | printf("ButtonRelease:%d\n", e.xbutton.button);
309 | mousemove[4] = 1;
310 | mousemove[9] = x >> 8;
311 | mousemove[10] = 0xFF & x;
312 | mousemove[11] = y >> 8;
313 | mousemove[12] = 0xFF & y;
314 | #ifdef fdsend
315 | printf("send:%d\n", send(fd, mousemove, sizeof(mousemove), 0));
316 | #endif
317 | }
318 | else if (e.type == MotionNotify)
319 | {
320 | int newx = e.xmotion.x;
321 | int newy = e.xmotion.y;
322 | int xdiff = newx - oldx;
323 | int ydiff = newy - oldy;
324 | oldx = newx;
325 | oldy = newy;
326 |
327 | #ifdef warpcursor
328 | if (warp == 1)
329 | {
330 | warp = 0;
331 | continue;
332 | }
333 |
334 | if (newx < 128 || newx > width - 128 || newy < 128 || newy > height - 128)
335 | {
336 | XWarpPointer(d, None, w, 0, 0, 0, 0, width/2, height/2);
337 | warp = 1;
338 | printf("border\n");
339 |
340 | }
341 | #endif
342 | printf("MotionNotify:%d,%d\n", newx, newy);
343 |
344 | x += xdiff;
345 | y += ydiff;
346 |
347 | x = x < 0 ? 0 : x;
348 | y = y < 0 ? 0 : y;
349 |
350 | mousemove[4] = 2;
351 | mousemove[9] = x >> 8;
352 | mousemove[10] = 0xFF & x;
353 | mousemove[11] = y >> 8;
354 | mousemove[12] = 0xFF & y;
355 | #ifdef fdsend
356 | printf("send:%d\n", send(fd, mousemove, sizeof(mousemove), 0));
357 | #endif
358 |
359 | }
360 |
361 |
362 | }
363 | #ifdef fdsend
364 | close(fd);
365 | #endif
366 |
367 | XDestroyWindow(d, w);
368 |
369 | XCloseDisplay(d);
370 |
371 | return 0;
372 | }
--------------------------------------------------------------------------------
/control/controlhidc.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | char usageid[] =
15 | {
16 | 0x00,
17 | 0x00,
18 | 0x00,
19 | 0x00,
20 | 0x00,
21 | 0x00,
22 | 0x00,
23 | 0x00,
24 | 0x00,
25 | 0x29,
26 | 0x1E,
27 | 0x1F,
28 | 0x20,
29 | 0x21,
30 | 0x22,
31 | 0x23,
32 | 0x24,
33 | 0x25,
34 | 0x26,
35 | 0x27,
36 | 0x2D,
37 | 0x2E,
38 | 0x2A,
39 | 0x2B,
40 | 0x14,
41 | 0x1A,
42 | 0x08,
43 | 0x15,
44 | 0x17,
45 | 0x1C,
46 | 0x18,
47 | 0x0C,
48 | 0x12,
49 | 0x13,
50 | 0x2F,
51 | 0x30,
52 | 0x28,
53 | 0x00,
54 | 0x04,
55 | 0x16,
56 | 0x07,
57 | 0x09,
58 | 0x0A,
59 | 0x0B,
60 | 0x0D,
61 | 0x0E,
62 | 0x0F,
63 | 0x33,
64 | 0x34,
65 | 0x35,
66 | 0x00,
67 | 0x31,
68 | 0x1D,
69 | 0x1B,
70 | 0x06,
71 | 0x19,
72 | 0x05,
73 | 0x11,
74 | 0x10,
75 | 0x36,
76 | 0x37,
77 | 0x38,
78 | 0x00,
79 | 0x55,
80 | 0x00,
81 | 0x2C,
82 | 0x39,
83 | 0x3A,
84 | 0x3B,
85 | 0x3C,
86 | 0x3D,
87 | 0x3E,
88 | 0x3F,
89 | 0x40,
90 | 0x41,
91 | 0x42,
92 | 0x43,
93 | 0x53,
94 | 0x47,
95 | 0x5F,
96 | 0x60,
97 | 0x61,
98 | 0x56,
99 | 0x5C,
100 | 0x5D,
101 | 0x5E,
102 | 0x57,
103 | 0x59,
104 | 0x5A,
105 | 0x5B,
106 | 0x62,
107 | 0x63,
108 | 0x00,
109 | 0x00,
110 | 0x00,
111 | 0x44,
112 | 0x45,
113 | 0x00,
114 | 0x00,
115 | 0x00,
116 | 0x00,
117 | 0x00,
118 | 0x00,
119 | 0x00,
120 | 0x58,
121 | 0x00,
122 | 0x54,
123 | 0x46,
124 | 0x00,
125 | 0x00,
126 | 0x4A,
127 | 0x52,
128 | 0x4B,
129 | 0x50,
130 | 0x4F,
131 | 0x4D,
132 | 0x51,
133 | 0x4E,
134 | 0x49,
135 | 0x4C,
136 | 0x00,
137 | 0x7F,
138 | 0x81,
139 | 0x80,
140 | 0x00,
141 | 0x00,
142 | 0x00,
143 | 0x48 };
144 |
145 | char mouseinput[] = {
146 | 0x00,0x01,
147 | 0x00, 14,
148 | 0x01,0x01,
149 | 0x00,
150 | 0x00,0x04,
151 | 0x00,
152 | 0x00,0x00,
153 | 0x00,0x00
154 | };
155 |
156 | char keyboardinput[] = {
157 | 0x00,0x01,
158 | 0x00,0x0c,
159 | 0x01,0x00,
160 | 0x00,
161 | 0x00,0x03,
162 | 0x00,
163 | 0x00,0x00
164 | };
165 |
166 |
167 | char reportdescriptor[] = {
168 | 0x00,0x01,
169 | 0x00, 62,
170 |
171 |
172 | 0x01,0x01,
173 | 0x01,
174 | 0x00, 52,
175 | 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
176 | 0x09, 0x02, // USAGE (Mouse)
177 | 0xa1, 0x01, // COLLECTION (Application)
178 | 0x09, 0x01, // USAGE (Pointer)
179 | 0xa1, 0x00, // COLLECTION (Physical)
180 | 0x05, 0x09, // USAGE_PAGE (Button)
181 | 0x19, 0x01, // USAGE_MINIMUM (Button 1)
182 | 0x29, 0x03, // USAGE_MAXIMUM (Button 3)
183 | 0x15, 0x00, // LOGICAL_MINIMUM (0)
184 | 0x25, 0x01, // LOGICAL_MAXIMUM (1)
185 | 0x95, 0x03, // REPORT_COUNT (3)
186 | 0x75, 0x01, // REPORT_SIZE (1)
187 | 0x81, 0x02, // INPUT (Data,Var,Abs)
188 | 0x95, 0x01, // REPORT_COUNT (1)
189 | 0x75, 0x05, // REPORT_SIZE (5)
190 | 0x81, 0x03, // INPUT (Cnst,Var,Abs)
191 | 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
192 | 0x09, 0x30, // USAGE (X)
193 | 0x09, 0x31, // USAGE (Y)
194 | 0x09, 0x38, // USAGE (wheel)
195 | 0x15, 0x81, // LOGICAL_MINIMUM (-127)
196 | 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
197 | 0x75, 0x08, // REPORT_SIZE (8)
198 | 0x95, 0x03, // REPORT_COUNT (3)
199 | 0x81, 0x06, // INPUT (Data,Var,Rel)
200 | 0xc0, // END_COLLECTION
201 | 0xc0, // END_COLLECTION
202 | 0xFF
203 |
204 | };
205 |
206 |
207 | #define fdsend
208 | int main(int argc, char **argv)
209 | {
210 | #ifdef fdsend
211 | int fd;
212 | short port = 0;
213 |
214 | if(argc < 2)
215 | {
216 | printf("missing port number");
217 | exit(-1);
218 | }
219 | port = atoi(argv[1]);
220 | printf("port:%u\n", port);
221 |
222 | char* sourceip = "192.168.173.80";
223 | if(argc>2)
224 | {
225 | sourceip = argv[2];
226 | }
227 | printf("sourceip:%u\n", sourceip);
228 |
229 |
230 | if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
231 | {
232 | printf("socket failed!");
233 | exit(1);
234 | }
235 |
236 | struct sockaddr_in serveraddr;
237 | memset(&serveraddr, 0, sizeof(serveraddr));
238 | serveraddr.sin_family = AF_INET;
239 | serveraddr.sin_addr.s_addr = inet_addr(sourceip);
240 | serveraddr.sin_port = htons(port);
241 |
242 | int flag = 1;
243 |
244 | setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
245 |
246 | if (connect(fd, (struct sockaddr *)&serveraddr,sizeof(serveraddr)) < 0)
247 | {
248 | perror("connect failed !");
249 | exit(1);
250 | }
251 | #endif
252 |
253 |
254 | Display *d;
255 | int s;
256 | Window w;
257 | XEvent e;
258 |
259 | d = XOpenDisplay(":0.0");
260 | //d = XOpenDisplay(NULL);
261 | if (d == NULL)
262 | {
263 | printf("Cannot open display\n");
264 | exit(1);
265 | }
266 | s = DefaultScreen(d);
267 | int width = XWidthOfScreen(DefaultScreenOfDisplay(d));
268 | int height = XHeightOfScreen(DefaultScreenOfDisplay(d));
269 | w = XCreateSimpleWindow(d, RootWindow(d, s), 0, 0, width, height, 1, BlackPixel(d, s), BlackPixel(d, s));
270 |
271 | Atom delWindow = XInternAtom(d, "WM_DELETE_WINDOW", 0);
272 | XSetWMProtocols(d, w, &delWindow, 1);
273 |
274 | XSelectInput(d, w, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
275 |
276 | XMapWindow(d, w);
277 |
278 | XWarpPointer(d, None, w, 0, 0, 0, 0, width / 2, height / 2);
279 |
280 |
281 | int oldx = 0, oldy = 0;
282 | int warp = 0;
283 | int senddes = 1;
284 | while(1)
285 | {
286 | if (--senddes == 0)
287 | {
288 | senddes = 100;
289 | #ifdef fdsend
290 | printf("senddes:%d\n", send(fd, reportdescriptor, sizeof(reportdescriptor), 0));
291 | #endif
292 | }
293 |
294 |
295 | XNextEvent(d, &e);
296 | if (e.type == Expose)
297 | {
298 | ;
299 | }
300 | else if (e.type == ClientMessage)
301 | break;
302 | else if (e.type == KeyPress)
303 | {
304 | int keyin = e.xkey.keycode;
305 | if (keyin == 37)
306 | keyboardinput[9] |= 1;
307 | else if (keyin == 50)
308 | keyboardinput[9] |= 1 << 1;
309 | else if (keyin == 64)
310 | keyboardinput[9] |= 1 << 2;
311 | else if (keyin == 133)
312 | keyboardinput[9] |= 1 << 3;
313 | else if (keyin == 105)
314 | keyboardinput[9] |= 1 << 4;
315 | else if (keyin == 62)
316 | keyboardinput[9] |= 1 << 5;
317 | else if (keyin == 108)
318 | keyboardinput[9] |= 1 << 6;
319 | else if (keyin == 135)
320 | keyboardinput[9] |= 1 << 7;
321 | else if (keyin < 128)
322 | keyboardinput[11] = usageid[keyin];
323 | else
324 | keyboardinput[11] = 0;
325 | printf("KeyPress:%d\n", keyin);
326 | #ifdef fdsend
327 | printf("send:%d\n", send(fd, keyboardinput, sizeof(keyboardinput), 0));
328 | #endif
329 |
330 | }
331 | else if (e.type == KeyRelease)
332 | {
333 | int keyin = e.xkey.keycode;
334 | if (keyin == 37)
335 | keyboardinput[9] &= ~1;
336 | else if (keyin == 50)
337 | keyboardinput[9] &= ~(1 << 1);
338 | else if (keyin == 64)
339 | keyboardinput[9] &= ~(1 << 2);
340 | else if (keyin == 133)
341 | keyboardinput[9] &= ~(1 << 3);
342 | else if (keyin == 105)
343 | keyboardinput[9] &= ~(1 << 4);
344 | else if (keyin == 62)
345 | keyboardinput[9] &= ~(1 << 5);
346 | else if (keyin == 108)
347 | keyboardinput[9] &= ~(1 << 6);
348 | else if (keyin == 135)
349 | keyboardinput[9] &= ~(1 << 7);
350 | else
351 | keyboardinput[11] = 0;
352 | printf("KeyRelease:%d\n", keyin);
353 | #ifdef fdsend
354 | printf("send:%d\n", send(fd, keyboardinput, sizeof(keyboardinput), 0));
355 | #endif
356 | }
357 | else if (e.type == ButtonPress)
358 | {
359 | int buttonnum = e.xbutton.button;
360 | printf("ButtonPress:%d\n", buttonnum);
361 |
362 | if (buttonnum < 4)
363 | {
364 | char mask;
365 | switch (buttonnum)
366 | {
367 | case 1:
368 | mask = 1;
369 | break;
370 | case 3:
371 | mask = 2;
372 | break;
373 | case 2:
374 | mask = 4;
375 | break;
376 | default:
377 | mask = 0;
378 | }
379 | mouseinput[9] |= mask;
380 | mouseinput[10] = 0;
381 | mouseinput[11] = 0;
382 | }
383 | else if (buttonnum < 6)
384 | {
385 | mouseinput[10] = 0;
386 | mouseinput[11] = 0;
387 | mouseinput[12] = buttonnum == 4 ? 1 : -1;
388 | }
389 |
390 |
391 | #ifdef fdsend
392 | printf("send:%d\n", send(fd, mouseinput, sizeof(mouseinput), 0));
393 | #endif
394 | }
395 | else if (e.type == ButtonRelease)
396 | {
397 | int buttonnum = e.xbutton.button;
398 | printf("ButtonRelease:%d\n", buttonnum);
399 |
400 | if (buttonnum < 4)
401 | {
402 | char mask;
403 | switch (buttonnum)
404 | {
405 | case 1:
406 | mask = 1;
407 | break;
408 | case 3:
409 | mask = 2;
410 | break;
411 | case 2:
412 | mask = 4;
413 | break;
414 | default:
415 | mask = 0;
416 | }
417 | mouseinput[9] &= ~mask;
418 | mouseinput[10] = 0;
419 | mouseinput[11] = 0;
420 | }
421 | else if (buttonnum < 6)
422 | {
423 | mouseinput[10] = 0;
424 | mouseinput[11] = 0;
425 | mouseinput[12] = 0;
426 | }
427 | #ifdef fdsend
428 | printf("send:%d\n", send(fd, mouseinput, sizeof(mouseinput), 0));
429 | #endif
430 | }
431 | else if (e.type == MotionNotify)
432 | {
433 | int newx = e.xmotion.x;
434 | int newy = e.xmotion.y;
435 | int xdiff = newx - oldx;
436 | int ydiff = newy - oldy;
437 | oldx = newx;
438 | oldy = newy;
439 |
440 | if (warp == 1)
441 | {
442 | warp = 0;
443 | continue;
444 | }
445 | if (newx < 128 || newx > width - 128 || newy < 128 || newy > height - 128)
446 | {
447 | XWarpPointer(d, None, w, 0, 0, 0, 0, width / 2, height / 2);
448 | warp = 1;
449 | printf("border\n");
450 |
451 | }
452 |
453 | printf("MotionNotify:%d,%d\n", newx, newy);
454 |
455 |
456 | if (xdiff > 127)
457 | mouseinput[10] = 127;
458 | else if (xdiff < -128)
459 | mouseinput[10] = -128;
460 | else
461 | mouseinput[10] = xdiff;
462 |
463 | if (ydiff > 127)
464 | mouseinput[11] = 127;
465 | else if (ydiff < -128)
466 | mouseinput[11] = -128;
467 | else
468 | mouseinput[11] = ydiff;
469 | //printf("xdiff:%d,ydiff:%d\n", xdiff, ydiff);
470 | //for (int i = 0; i < sizeof(mouseinput); i++)
471 | //printf("%d,",mouseinput[i]);
472 | #ifdef fdsend
473 | printf("send:%d\n", send(fd, mouseinput, sizeof(mouseinput), 0));
474 | #endif
475 | }
476 |
477 |
478 | }
479 | #ifdef fdsend
480 | close(fd);
481 | #endif
482 | XDestroyWindow(d, w);
483 |
484 | XCloseDisplay(d);
485 |
486 | return 0;
487 | }
488 |
489 |
490 |
--------------------------------------------------------------------------------
/control/keyboardonly.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 |
15 |
16 | char mouseinput[] = {
17 | 0x00,0x01,
18 | 0x00,0x0c,
19 | 0x01,0x01,
20 | 0x00,0x00,
21 | 0x03,0x00,
22 | 0x00,0x00
23 | };
24 |
25 | char keyboardinput[] = {
26 | 0x00,0x01,
27 | 0x00,0x0c,
28 | 0x01,0x00,
29 | 0x00,0x00,
30 | 0x03,0x00,
31 | 0x00,0x00
32 | };
33 | /*
34 | char reportdescriptor[55] = {
35 | 0x01,0x01,
36 | 0x01,0x00,
37 | 50,
38 | 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
39 | 0x09, 0x02, // USAGE (Mouse)
40 | 0xa1, 0x01, // COLLECTION (Application)
41 | 0x09, 0x01, // USAGE (Pointer)
42 | 0xa1, 0x00, // COLLECTION (Physical)
43 | 0x05, 0x09, // USAGE_PAGE (Button)
44 | 0x19, 0x01, // USAGE_MINIMUM (Button 1)
45 | 0x29, 0x03, // USAGE_MAXIMUM (Button 3)
46 | 0x15, 0x00, // LOGICAL_MINIMUM (0)
47 | 0x25, 0x01, // LOGICAL_MAXIMUM (1)
48 | 0x95, 0x03, // REPORT_COUNT (3)
49 | 0x75, 0x01, // REPORT_SIZE (1)
50 | 0x81, 0x02, // INPUT (Data,Var,Abs)
51 | 0x95, 0x01, // REPORT_COUNT (1)
52 | 0x75, 0x05, // REPORT_SIZE (5)
53 | 0x81, 0x03, // INPUT (Cnst,Var,Abs)
54 | 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
55 | 0x09, 0x30, // USAGE (X)
56 | 0x09, 0x31, // USAGE (Y)
57 | 0x15, 0x81, // LOGICAL_MINIMUM (-127)
58 | 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
59 | 0x75, 0x08, // REPORT_SIZE (8)
60 | 0x95, 0x02, // REPORT_COUNT (2)
61 | 0x81, 0x06, // INPUT (Data,Var,Rel)
62 | 0xc0, // END_COLLECTION
63 | 0xc0 // END_COLLECTION
64 | };*/
65 |
66 |
67 | int main(int argc, char **argv)
68 | {
69 |
70 |
71 |
72 |
73 |
74 | Display *d;
75 | int s;
76 | Window w;
77 | XEvent e;
78 |
79 | d = XOpenDisplay(NULL);
80 | if (d == NULL)
81 | {
82 | printf("Cannot open display\n");
83 | exit(1);
84 | }
85 | s = DefaultScreen(d);
86 | w = XCreateSimpleWindow(d, RootWindow(d, s), 0, 0, 1280, 720, 1, BlackPixel(d, s), WhitePixel(d, s));
87 |
88 | Atom delWindow = XInternAtom( d, "WM_DELETE_WINDOW", 0 );
89 | XSetWMProtocols(d , w, &delWindow, 1);
90 |
91 | XSelectInput(d, w, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask );
92 |
93 | XMapWindow(d, w);
94 |
95 |
96 |
97 |
98 | int oldx = 0, oldy = 0;
99 | while(1)
100 | {
101 |
102 |
103 |
104 |
105 |
106 | XNextEvent(d, &e);
107 | if (e.type == Expose)
108 | {
109 | ;
110 | }
111 | else if (e.type == ClientMessage)
112 | break;
113 | else if (e.type == KeyPress)
114 | {
115 | keyboardinput[11] = e.xkey.keycode;
116 | printf("KeyPress:%d\n", keyboardinput[11]);
117 |
118 |
119 | }
120 | else if (e.type == KeyRelease)
121 | {
122 | keyboardinput[11] = 0;
123 | printf("KeyRelease:%d\n", e.xkey.keycode);
124 | }
125 | else if (e.type == ButtonPress)
126 | {
127 | int buttonnum = e.xbutton.button;
128 | printf("ButtonPress:%d\n", buttonnum);
129 |
130 | char mask;
131 | switch (buttonnum)
132 | {
133 | case 1:
134 | mask = 1;
135 | break;
136 | case 3:
137 | mask = 2;
138 | break;
139 | case 2:
140 | mask = 4;
141 | break;
142 | default:
143 | mask = 0;
144 | }
145 | mouseinput[9] |= mask;
146 | mouseinput[10] = 0;
147 | mouseinput[11] = 0;
148 |
149 |
150 |
151 | }
152 | else if (e.type == ButtonRelease)
153 | {
154 | int buttonnum = e.xbutton.button;
155 | printf("ButtonRelease:%d\n", buttonnum);
156 |
157 | char mask;
158 | switch (buttonnum)
159 | {
160 | case 1:
161 | mask = 1;
162 | break;
163 | case 3:
164 | mask = 2;
165 | break;
166 | case 2:
167 | mask = 4;
168 | break;
169 | default:
170 | mask = 0;
171 | }
172 | mask = ~mask;
173 | mouseinput[9] &= mask;
174 | mouseinput[10] = 0;
175 | mouseinput[11] = 0;
176 | }
177 | else if (e.type == MotionNotify)
178 | {
179 | int newx = e.xmotion.x;
180 | int newy = e.xmotion.y;
181 |
182 |
183 |
184 | int xdiff = newx - oldx;
185 | int ydiff = newy - oldy;
186 | oldx = newx;
187 | oldy = newy;
188 |
189 |
190 |
191 | if (xdiff > 127)
192 | mouseinput[10] = 127;
193 | else if (xdiff < -128)
194 | mouseinput[10] = -128;
195 | else
196 | mouseinput[10] = xdiff;
197 |
198 | if (ydiff > 127)
199 | mouseinput[11] = 127;
200 | else if (ydiff < -128)
201 | mouseinput[11] = -128;
202 | else
203 | mouseinput[11] = ydiff;
204 | //printf("xdiff:%d,ydiff:%d\n", xdiff, ydiff);
205 | //for (int i = 0; i < sizeof(mouseinput); i++)
206 | //printf("%d,",mouseinput[i]);
207 |
208 | }
209 |
210 |
211 | }
212 |
213 | XDestroyWindow(d, w);
214 |
215 | XCloseDisplay(d);
216 |
217 | return 0;
218 | }
--------------------------------------------------------------------------------
/d2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | """
4 | This software is part of lazycast, a simple wireless display receiver for Raspberry Pi
5 | Copyright (C) 2018 Hsun-Wei Cho
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | """
17 | import socket
18 | import fcntl, os
19 | import errno
20 | import threading
21 | from threading import Thread
22 | import time
23 | from time import sleep
24 | import sys
25 | import subprocess
26 | import argparse
27 | ##################### Settings #####################
28 | player_select = 2
29 | # 0: non-RPi systems. (using vlc or gstreamer)
30 | # 1: player1 has lower latency.
31 | # 2: player2 handles still images and sound better.
32 | # 3: omxplayer # Using this option for video playback on Android
33 | sound_output_select = 2
34 | # 0: HDMI sound output
35 | # 1: 3.5mm audio jack output
36 | # 2: alsa
37 | disable_1920_1080_60fps = 1
38 | enable_mouse_keyboard = 0
39 |
40 | display_power_management = 0
41 | # 1: (For projectors) Put the display in sleep mode when not in use by lazycast
42 |
43 | ####################################################
44 |
45 | parser = argparse.ArgumentParser()
46 | parser.add_argument('arg1', nargs='?', default='192.168.173.80')
47 | args = parser.parse_args()
48 | sourceip = vars(args)['arg1']
49 |
50 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
51 | server_address = (sourceip, 7236)
52 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
53 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
54 |
55 | connectcounter = 0
56 | while True:
57 | try:
58 | sock.connect(server_address)
59 | except socket.error as e:
60 | #connectcounter = connectcounter + 1
61 | #if connectcounter == 3:
62 | sock.close()
63 | sys.exit(1)
64 | else:
65 | break
66 |
67 |
68 |
69 |
70 | tohid = [0, 41, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 45, 46, 42, 43, 20, 26, 8, 21, 23, 28, 24, 12, 18, 19, 47, 48, 40, 0, 4, 22, 7, 9, 10, 11, 13, 14, 15, 51, 52, 53, 0, 49, 29, 27, 6, 25, 5, 17, 16, 54, 55, 56, 0, 85, 0, 44, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 83, 71, 95, 96, 97, 86, 92, 93, 94, 87, 89, 90, 91, 98, 99, 0, 0, 0, 68, 69, 0, 0, 0, 0, 0, 0, 0, 88, 0, 84, 70, 0, 0, 74, 82, 75, 80, 79, 77, 81, 78, 73, 76, 0, 127, 129, 128, 0, 0, 0, 72,
71 | 0,0,0,0,0,0,0,0x65]
72 |
73 | def hidcprocessing(hidcsock):
74 | print('hidcprocessing')
75 | mousemask = 0
76 | keyboardmask = 0
77 | while(1):
78 | for key,mask in selector.select():
79 | device = key.fileobj
80 | for event in device.read():
81 |
82 | if event.type == 0:
83 | continue
84 |
85 | if event.type == ecodes.EV_KEY:
86 |
87 | if(event.code<272):
88 | keyin = event.code
89 |
90 | keyout = 0
91 | if (keyin == 29): #left ctrl
92 | if(event.value == 0):
93 | keyboardmask &= ~1
94 | else:
95 | keyboardmask |= 1
96 | elif (keyin == 42): #left shift
97 | if(event.value == 0):
98 | keyboardmask &= ~(1<<1) #shift
99 | else:
100 | keyboardmask |= (1<<1)
101 | elif (keyin == 56): #left alt
102 | if(event.value == 0):
103 | keyboardmask &= ~(1<<2)
104 | else:
105 | keyboardmask |= (1<<2)
106 | elif (keyin == 125): #leftmeta
107 | if(event.value == 0):
108 | keyboardmask &= ~(1<<3) #windows
109 | else:
110 | keyboardmask |= (1<<3)
111 | elif (keyin == 97):#right ctrl
112 | if(event.value == 0):
113 | keyboardmask &= ~(1<<4)
114 | else:
115 | keyboardmask |= (1<<4)
116 | elif (keyin == 54):#right shift
117 | if(event.value == 0):
118 | keyboardmask &= ~(1<<5)
119 | else:
120 | keyboardmask |= (1<<5)
121 | elif (keyin == 100):#right alt
122 | if(event.value == 0):
123 | keyboardmask &= ~(1<<6)
124 | else:
125 | keyboardmask |= (1<<6)
126 | elif (keyin == 0x7e): #rightmeta
127 | if(event.value == 0):
128 | keyboardmask &= ~(1<<7) #windows
129 | else:
130 | keyboardmask |= (1<<7)
131 | else:
132 | if(event.value != 0):
133 | keyout = tohid[keyin]
134 |
135 | m7 = '00010012010000000929'+'{:02x}'.format(keyboardmask)+'00'+'{:02x}'.format(keyout)+'0000000000'
136 | hidcsock.send(bytes.fromhex(m7))
137 |
138 |
139 | elif(event.code == 272): # left
140 | if(event.value == 1):
141 | mousemask |= 1
142 | else:
143 | mousemask &= ~1
144 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'0000000000'
145 | hidcsock.send(bytes.fromhex(m7))
146 | elif(event.code == 273):
147 | if(event.value == 1):
148 | mousemask |= 2
149 | else:
150 | mousemask &= ~2
151 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'0000000000'
152 | hidcsock.send(bytes.fromhex(m7))
153 | elif(event.code == 274):
154 | if(event.value == 1):
155 | mousemask |= 4
156 | else:
157 | mousemask &= ~4
158 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'0000000000'
159 | hidcsock.send(bytes.fromhex(m7))
160 |
161 | elif event.type == ecodes.EV_REL:
162 | if(event.code == 0): #x
163 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'{:02x}'.format(event.value & 0xFF)+'00000000'
164 | hidcsock.send(bytes.fromhex(m7))
165 | elif(event.code == 1): #y
166 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'00'+'{:02x}'.format(event.value & 0xFF)+'000000'
167 | hidcsock.send(bytes.fromhex(m7))
168 | elif(event.code == 8): # wheel
169 | if(event.value<0):
170 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'0000FF0000'
171 | else:
172 | m7 = '00010010010100000628'+'{:02x}'.format(mousemask & 0xFF)+'0000010000'
173 | hidcsock.send(bytes.fromhex(m7))
174 |
175 |
176 |
177 |
178 |
179 | cpuinfo = os.popen('grep Hardware /proc/cpuinfo')
180 | cpustr = cpuinfo.read()
181 | runonpi = 'BCM2835' in cpustr or 'BCM2711' in cpustr
182 | cpuinfo.close()
183 |
184 | if runonpi and not os.path.exists('edid.txt'):
185 | os.system('tvservice -d edid.txt')
186 |
187 | edidlen = 0
188 | if os.path.exists('edid.txt'):
189 | edidfile = open('edid.txt','rb')
190 | edidbytes = edidfile.read()
191 | edidfile.close()
192 | edidlen = len(edidbytes)
193 |
194 | idrsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
195 | idrsock_address = ('127.0.0.1', 0)
196 | idrsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
197 | idrsock.bind(idrsock_address)
198 | addr, idrsockport = idrsock.getsockname()
199 |
200 | data = sock.recv(2048)
201 | data = data.decode()
202 | print("---M1--->\n" + data)
203 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 1\r\nPublic: org.wfa.wfd1.0, SET_PARAMETER, GET_PARAMETER\r\n\r\n'
204 | print("<--------\n" + s_data)
205 | sock.sendall(s_data.encode())
206 |
207 |
208 | # M2
209 | s_data = 'OPTIONS * RTSP/1.0\r\nCSeq: 1\r\nRequire: org.wfa.wfd1.0\r\n\r\n'
210 | print("<---M2---\n" + s_data)
211 | sock.sendall(s_data.encode())
212 |
213 | data = sock.recv(2048)
214 | data = data.decode()
215 | print("-------->\n" + data)
216 | m2data = data
217 |
218 |
219 | # M3
220 | data = sock.recv(2048)
221 | data = data.decode()
222 | print("---M3--->\n" + data)
223 |
224 | msg = 'wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\n'
225 | if player_select == 2:
226 | msg = msg + 'wfd_audio_codecs: LPCM 00000002 00\r\n'
227 | else:
228 | msg = msg + 'wfd_audio_codecs: AAC 00000001 00\r\n'
229 |
230 | if disable_1920_1080_60fps == 1:
231 | msg = msg + 'wfd_video_formats: 00 00 02 10 0001FEFF 3FFFFFFF 00000FFF 00 0000 0000 00 none none\r\n'
232 | else:
233 | msg = msg + 'wfd_video_formats: 00 00 02 10 0001FFFF 3FFFFFFF 00000FFF 00 0000 0000 00 none none\r\n'
234 |
235 | msg = msg +'wfd_3d_video_formats: none\r\n'\
236 | +'wfd_coupled_sink: none\r\n'\
237 | +'wfd_connector_type: 05\r\n'\
238 | +'wfd_uibc_capability: input_category_list=GENERIC, HIDC;generic_cap_list=Keyboard, Mouse;hidc_cap_list=Keyboard/USB, Mouse/USB;port=none\r\n'\
239 | +'wfd_standby_resume_capability: none\r\n'\
240 | +'wfd_content_protection: none\r\n'
241 |
242 |
243 | if runonpi:
244 | os.system('pkill lxpanel')
245 |
246 |
247 | if 'wfd_display_edid' in data and edidlen != 0:
248 | msg = msg + 'wfd_display_edid: ' + '{:04X}'.format(int(edidlen/256 + 1)) + ' ' + str(edidbytes.hex())+'\r\n'
249 |
250 | # if 'microsoft_latency_management_capability' in data:
251 | # msg = msg + 'microsoft-latency-management-capability: supported\r\n'
252 | # if 'microsoft_format_change_capability' in data:
253 | # msg = msg + 'microsoft_format_change_capability: supported\r\n'
254 |
255 | if 'intel_friendly_name' in data:
256 | msg = msg + 'intel_friendly_name: raspberrypi\r\n'
257 | if 'intel_sink_manufacturer_name' in data:
258 | msg = msg + 'intel_sink_manufacturer_name: lazycast\r\n'
259 | if 'intel_sink_model_name' in data:
260 | msg = msg + 'intel_sink_model_name: lazycast\r\n'
261 | if 'intel_sink_version' in data:
262 | msg = msg + 'intel_sink_version: 25.4.13\r\n'
263 | if 'intel_sink_device_URL' in data:
264 | msg = msg + 'intel_sink_device_URL: none\r\n'
265 |
266 | if 'wfd_idr_request_capability' in data:
267 | msg = msg + 'wfd_idr_request_capability: 1\r\n'
268 |
269 |
270 |
271 | m3resp ='RTSP/1.0 200 OK\r\nCSeq: 2\r\n'+'Content-Type: text/parameters\r\nContent-Length: '+str(len(msg))+'\r\n\r\n'+msg
272 | print("<--------\n" + m3resp)
273 | sock.sendall(m3resp.encode())
274 |
275 |
276 | # M4
277 | data = sock.recv(2048)
278 | data = data.decode()
279 | print("---M4--->\n" + data)
280 |
281 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 3\r\n\r\n'
282 | print("<--------\n" + s_data)
283 | sock.sendall(s_data.encode())
284 |
285 | usehidc = False
286 | messagelist=data.split('\r\n\r\n')
287 | for entry in messagelist:
288 | if 'wfd_uibc_capability:' in entry:
289 | lines = entry.split("\r\n")
290 | uibc_line = next((line for line in lines if line.startswith("wfd_uibc_capability:")), None)
291 | uibcport = None
292 | if uibc_line:
293 | uibc_content = uibc_line.split("wfd_uibc_capability:")[1].strip()
294 | for item in uibc_content.split(";"):
295 | if item.startswith("port="):
296 | uibcport = item.split("=")[1]
297 | break
298 | print('uibcport:'+uibcport+"\n")
299 | if 'none' not in uibcport and enable_mouse_keyboard == 1:
300 | usehidc = True
301 |
302 |
303 | inputdevs = []
304 | if usehidc:
305 | from evdev import InputDevice, categorize, ecodes
306 | import evdev
307 | from selectors import DefaultSelector, EVENT_READ
308 |
309 | hidcsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
310 | hidcsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
311 | hidcsock.connect((sourceip,int(uibcport)))
312 |
313 |
314 | m1 = '1001003e2ab6010101003305010902a10185280901a1000509190129081500250195087501810205010930093109380a38021581257f750895048106c0c0'
315 | m2 = '1001004c3ce2010001004105010906a1018529050719e029e71500250175019508810295017508810395057501050819012905910295017503910395067508150025650507190029658100c0'
316 | m3 = '100100243ce20107010019050c0901a101852a19002aff00150026ff00950175108100c0'
317 | m4 = '1001027a3ce2010301026f050d0904a1018513050d095495017508150025638102550c66011047ffff000027ffff00007510950109568102050d0922a102150025013500450055006500750195010942810209478102950481030600ff09109501750281027508050d095126630081027510550e651127ff7f00004640060948810209498102050109308102468403050109318102050d651447a08c000027a08c0000093f8102c0050d0922a102150025013500450055006500750195010942810209478102950481030600ff09109501750281027508050d095126630081027510550e651127ff7f00004640060948810209498102050109308102468403050109318102050d651447a08c000027a08c0000093f8102c0050d0922a102150025013500450055006500750195010942810209478102950481030600ff09109501750281027508050d095126630081027510550e651127ff7f00004640060948810209498102050109308102468403050109318102050d651447a08c000027a08c0000093f8102c0050d0922a102150025013500450055006500750195010942810209478102950481030600ff09109501750281027508050d095126630081027510550e651127ff7f00004640060948810209498102050109308102468403050109318102050d651447a08c000027a08c0000093f8102c0050d0922a102150025013500450055006500750195010942810209478102950481030600ff09109501750281027508050d095126630081027510550e651127ff7f00004640060948810209498102050109308102468403050109318102050d651447a08c000027a08c0000093f8102c0050d85120955950175101500266400b102c0'
318 | m5 = '1001000e3ce20103000003120a00'
319 | m6 = '100100d0422801060100c4050d0902a1018514050d0920a10009420944093c094509321500250175019505810295038103050127ff7f000075109501550e6533093035004640068142093146840381426500050d093081020600ff09118102091281027520050609228102c0c0050d0902a1018515050d0920a10009420944093c094509321500250175019505810295038103050127ff7f000075109501550e6533093035004640068142093146840381426500050d093081020600ff09118102091281027520050609228102c0c000'
320 |
321 |
322 | hidcsock.send(bytes.fromhex(m1))
323 | sleep(0.01)
324 | hidcsock.send(bytes.fromhex(m2))
325 | sleep(0.01)
326 | hidcsock.send(bytes.fromhex(m3))
327 | sleep(0.01)
328 | hidcsock.send(bytes.fromhex(m4))
329 | sleep(0.01)
330 | hidcsock.send(bytes.fromhex(m5))
331 | sleep(0.01)
332 | hidcsock.send(bytes.fromhex(m6))
333 | sleep(0.01)
334 | selector = DefaultSelector()
335 |
336 |
337 |
338 | for path in evdev.list_devices():
339 | inputdev = InputDevice(path)
340 | selector.register(inputdev, EVENT_READ)
341 | if inputdev not in inputdevs:
342 | inputdev.grab()
343 | inputdevs.append(inputdev)
344 |
345 | t1 = threading.Thread(target=hidcprocessing, args=(hidcsock,))
346 | t1.start()
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 | def killall(control):
355 | os.system('pkill vlc')
356 | os.system('pkill cvlc')
357 | os.system('pkill gst-launch-1.0')
358 | os.system('pkill player.bin')
359 | os.system('pkill h264.bin')
360 | if display_power_management == 1:
361 | os.system('vcgencmd display_power 0')
362 | if control:
363 | os.system('pkill control.bin')
364 | os.system('pkill controlhidc.bin')
365 |
366 | # M5
367 | data = sock.recv(2048)
368 | data = data.decode()
369 | print("---M5--->\n" + data)
370 |
371 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 4\r\n\r\n'
372 | print("<--------\n" + s_data)
373 | sock.sendall(s_data.encode())
374 |
375 |
376 | # M6
377 | m6req ='SETUP rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
378 | +'CSeq: 5\r\n'\
379 | +'Transport: RTP/AVP/UDP;unicast;client_port=1028\r\n\r\n'
380 | print("<---M6---\n" + m6req)
381 | sock.sendall(m6req.encode())
382 |
383 | data = sock.recv(2048)
384 | data = data.decode()
385 | print("-------->\n" + data)
386 |
387 | paralist=data.split(';')
388 | print(paralist)
389 | serverport=[x for x in paralist if 'server_port=' in x]
390 | print(serverport)
391 | serverport=serverport[-1]
392 | serverport=serverport[12:17]
393 | print(serverport)
394 |
395 | paralist=data.split( )
396 | position=paralist.index('Session:')+1
397 | sessionid=paralist[position]
398 |
399 |
400 |
401 |
402 |
403 | if not runonpi:
404 | player_select = 0
405 |
406 | def launchplayer(player_select):
407 | killall(False)
408 | if display_power_management == 1:
409 | os.system('vcgencmd display_power 1')
410 | if player_select == 0:
411 | # os.system('gst-launch-1.0 -v udpsrc port=1028 ! application/x-rtp,media=video,encoding-name=H264 ! queue ! rtph264depay ! avdec_h264 ! autovideosink &')
412 | # os.system('gst-launch-1.0 -v udpsrc port=1028 ! video/mpegts ! tsdemux ! h264parse ! queue ! avdec_h264 ! ximagesink sync=false &')
413 | # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=ximagesink audio-sink=alsasink sync=false &')
414 | # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=xvimagesink audio-sink=alsasink sync=false &')
415 | if False: # Change False to True if you want to use gstreamer
416 | os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=autovideosink audio-sink=alsasink sync=false &')
417 | else:
418 | os.system('vlc --fullscreen rtp://0.0.0.0:1028/wfd1.0/streamid=0 --intf dummy --no-ts-trust-pcr --ts-seek-percent --network-caching=300 --no-mouse-events & ')
419 | elif player_select == 1:
420 | os.system('./player/player.bin '+str(idrsockport)+' '+str(sound_output_select)+' &')
421 | elif player_select == 2:
422 | sinkip = sock.getsockname()[0]
423 | print(sinkip)
424 | print('./h264/h264.bin '+str(idrsockport)+' '+str(sound_output_select)+' '+sinkip+' &')
425 | os.system('./h264/h264.bin '+str(idrsockport)+' '+str(sound_output_select)+' '+sinkip+' &')
426 | elif player_select == 3:
427 | #if 'MSMiracastSource' in m2data:
428 | # os.system('omxplayer rtp://0.0.0.0:1028 -n -1 --live &') # For Windows 10 when no sound is playing
429 | #else:
430 | # os.system('omxplayer rtp://0.0.0.0:1028 --live &')
431 | #os.system('omxplayer rtp://0.0.0.0:1028 -i')
432 | omxplayerinfo = subprocess.Popen('omxplayer rtp://0.0.0.0:1028 -i'.split(),stderr=subprocess.PIPE).communicate()
433 | if '0 channels' in omxplayerinfo[1]:
434 | os.system('omxplayer rtp://0.0.0.0:1028 -n -1 --live &') # For Windows 10 when no sound is playing
435 | else:
436 | os.system('omxplayer rtp://0.0.0.0:1028 --live &')
437 |
438 | launchplayer(player_select)
439 |
440 |
441 | # M7
442 | m7req ='PLAY rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
443 | +'CSeq: 6\r\n'\
444 | +'Session: '+str(sessionid)+'\r\n\r\n'
445 | print("<---M7---\n" + m7req)
446 | sock.sendall(m7req.encode())
447 |
448 | data = sock.recv(2048)
449 | data = data.decode()
450 | print("-------->\n" + data)
451 |
452 | print("---- Negotiation successful ----")
453 |
454 | fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
455 | fcntl.fcntl(idrsock, fcntl.F_SETFL, os.O_NONBLOCK)
456 |
457 | negotiation_time = time.time()
458 |
459 | csnum = 102
460 | watchdog = 0
461 | while True:
462 | try:
463 | data = sock.recv(2048)
464 | data = data.decode()
465 | except socket.error as e:
466 | err = e.args[0]
467 | if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
468 | try:
469 | datafromc = idrsock.recv(1000)
470 | datafromc = datafromc.decode()
471 | except socket.error as e:
472 | err = e.args[0]
473 | if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
474 | processrunning = os.popen('ps au').read()
475 | if player_select == 2 and 'h264.bin' not in processrunning:
476 | launchplayer(player_select)
477 | sleep(0.01)
478 | else:
479 | watchdog = watchdog + 1
480 | if watchdog == 70/0.01:
481 | killall(True)
482 | sleep(1)
483 | break
484 | else:
485 | sys.exit(1)
486 | else:
487 | print(datafromc)
488 | elemfromc = datafromc.split(' ')
489 | if elemfromc[0] == 'recv':
490 | killall(True)
491 | sleep(1)
492 | break
493 | else:
494 | csnum = csnum + 1
495 | msg = 'wfd_idr_request\r\n'
496 | idrreq ='SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n'\
497 | +'Content-Length: '+str(len(msg))+'\r\n'\
498 | +'Content-Type: text/parameters\r\n'\
499 | +'CSeq: '+str(csnum)+'\r\n\r\n'\
500 | +msg
501 |
502 | print(idrreq)
503 | sock.sendall(idrreq.encode())
504 |
505 | else:
506 | sys.exit(1)
507 | else:
508 | print(data)
509 | watchdog = 0
510 | if len(data)==0 or 'wfd_trigger_method: TEARDOWN' in data:
511 | killall(True)
512 | sleep(1)
513 | break
514 | elif 'wfd_video_formats' in data and time.time() - negotiation_time > 5:
515 | launchplayer(player_select)
516 | messagelist=data.split('\r\n\r\n')
517 | print(messagelist)
518 | singlemessagelist=[x for x in messagelist if ('GET_PARAMETER' in x or 'SET_PARAMETER' in x )]
519 | print(singlemessagelist)
520 | for singlemessage in singlemessagelist:
521 | entrylist=singlemessage.split('\r')
522 | for entry in entrylist:
523 | if 'CSeq' in entry:
524 | cseq = entry
525 |
526 | resp='RTSP/1.0 200 OK\r'+cseq+'\r\n\r\n';#cseq contains \n
527 | print(resp)
528 | sock.sendall(resp.encode())
529 |
530 |
531 | idrsock.close()
532 | sock.close()
533 |
534 |
535 | if runonpi:
536 | os.system('nohup lxpanel --profile LXDE-pi &')
537 |
538 | if usehidc:
539 | hidcsock.close()
540 | for inputdev in inputdevs:
541 | try:
542 | inputdev.ungrab()
543 | except IOError:
544 | print('already ungrabbed')
545 |
546 |
--------------------------------------------------------------------------------
/d2vlc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | """
4 | This software is part of lazycast, a simple wireless display receiver for Raspberry Pi
5 | Copyright (C) 2018 Hsun-Wei Cho
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | """
17 | import socket
18 | import fcntl, os
19 | import errno
20 | import threading
21 | from threading import Thread
22 | import time
23 | from time import sleep
24 | import sys
25 | import subprocess
26 | import argparse
27 | ##################### Settings #####################
28 | player_select = 0
29 | disable_1920_1080_60fps = 1
30 | enable_mouse_keyboard = 1
31 |
32 | display_power_management = 0
33 |
34 | ####################################################
35 |
36 | parser = argparse.ArgumentParser()
37 | parser.add_argument('arg1', nargs='?', default='192.168.173.80')
38 | args = parser.parse_args()
39 | sourceip = vars(args)['arg1']
40 |
41 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
42 | server_address = (sourceip, 7236)
43 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
44 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
45 |
46 | connectcounter = 0
47 | while True:
48 | try:
49 | sock.connect(server_address)
50 | except socket.error as e:
51 | #connectcounter = connectcounter + 1
52 | #if connectcounter == 3:
53 | sock.close()
54 | sys.exit(1)
55 | else:
56 | break
57 |
58 | cpuinfo = os.popen('grep Hardware /proc/cpuinfo')
59 | cpustr = cpuinfo.read()
60 | runonpi = 'BCM2835' in cpustr or 'BCM2711' in cpustr
61 | cpuinfo.close()
62 |
63 |
64 | data = sock.recv(1000)
65 | data = data.decode()
66 | print("M1:")
67 | print(data)
68 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 1\r\nPublic: org.wfa.wfd1.0, SET_PARAMETER, GET_PARAMETER\r\n\r\n'
69 | print('Response:')
70 | print(s_data)
71 | sock.sendall(s_data.encode())
72 |
73 |
74 | # M2
75 | s_data = 'OPTIONS * RTSP/1.0\r\nCSeq: 1\r\nRequire: org.wfa.wfd1.0\r\n\r\n'
76 | print("M2:")
77 | print(s_data)
78 | sock.sendall(s_data.encode())
79 |
80 | data = sock.recv(1000)
81 | data = data.decode()
82 | print('Response:')
83 | print(data)
84 | m2data = data
85 |
86 |
87 | # M3
88 | data = sock.recv(1000)
89 | data = data.decode()
90 | print("M3:")
91 | print(data)
92 |
93 | msg = 'wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\n'
94 | if player_select == 2:
95 | msg = msg + 'wfd_audio_codecs: LPCM 00000002 00\r\n'
96 | else:
97 | msg = msg + 'wfd_audio_codecs: AAC 00000001 00\r\n'
98 |
99 | if disable_1920_1080_60fps == 1:
100 | msg = msg + 'wfd_video_formats: 00 00 02 10 0001FEFF 3FFFFFFF 00000FFF 00 0000 0000 00 none none\r\n'
101 | else:
102 | msg = msg + 'wfd_video_formats: 00 00 02 10 0001FFFF 3FFFFFFF 00000FFF 00 0000 0000 00 none none\r\n'
103 |
104 | msg = msg +'wfd_3d_video_formats: none\r\n'\
105 | +'wfd_coupled_sink: none\r\n'\
106 | +'wfd_connector_type: 05\r\n'\
107 | +'wfd_uibc_capability: input_category_list=GENERIC, HIDC;generic_cap_list=Keyboard, Mouse;hidc_cap_list=Keyboard/USB, Mouse/USB;port=none\r\n'\
108 | +'wfd_standby_resume_capability: none\r\n'\
109 | +'wfd_content_protection: none\r\n'
110 |
111 |
112 | # if runonpi and not os.path.exists('edid.txt'):
113 | # os.system('tvservice -d edid.txt')
114 |
115 | # edidlen = 0
116 | # if os.path.exists('edid.txt'):
117 | # edidfile = open('edid.txt','r')
118 | # lines = edidfile.readlines()
119 | # edidfile.close()
120 | # edidstr =''
121 | # for line in lines:
122 | # edidstr = edidstr + line
123 | # edidlen = len(edidstr)
124 |
125 | # if 'wfd_display_edid' in data and edidlen != 0:
126 | # msg = msg + 'wfd_display_edid: ' + '{:04X}'.format(edidlen/256 + 1) + ' ' + str(edidstr.encode('utf-8').hex())+'\r\n'
127 |
128 | # if 'microsoft_latency_management_capability' in data:
129 | # msg = msg + 'microsoft-latency-management-capability: supported\r\n'
130 | # if 'microsoft_format_change_capability' in data:
131 | # msg = msg + 'microsoft_format_change_capability: supported\r\n'
132 |
133 | if 'intel_friendly_name' in data:
134 | msg = msg + 'intel_friendly_name: raspberrypi\r\n'
135 | if 'intel_sink_manufacturer_name' in data:
136 | msg = msg + 'intel_sink_manufacturer_name: lazycast\r\n'
137 | if 'intel_sink_model_name' in data:
138 | msg = msg + 'intel_sink_model_name: lazycast\r\n'
139 | # if 'intel_sink_version' in data:
140 | # msg = msg + 'intel_sink_version: 20.4.26\r\n'
141 | if 'intel_sink_device_URL' in data:
142 | msg = msg + 'intel_sink_device_URL: https://github.com/homeworkc/lazycast\r\n'
143 |
144 |
145 |
146 |
147 | m3resp ='RTSP/1.0 200 OK\r\nCSeq: 2\r\n'+'Content-Type: text/parameters\r\nContent-Length: '+str(len(msg))+'\r\n\r\n'+msg
148 | print('Response:')
149 | print(m3resp)
150 | sock.sendall(m3resp.encode())
151 |
152 |
153 | # M4
154 | data = sock.recv(1000)
155 | data = data.decode()
156 | print('M4')
157 | print(data)
158 |
159 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 3\r\n\r\n'
160 | print(s_data)
161 | sock.sendall(s_data.encode())
162 |
163 | # def uibcstart(sock, data):
164 | # #print data
165 | # data = data.decode()
166 | # messagelist=data.split('\r\n\r\n')
167 | # for entry in messagelist:
168 | # if 'wfd_uibc_capability:' in entry:
169 | # entrylist = entry.split(';')
170 | # uibcport = entrylist[-1]
171 | # uibcport = uibcport.split('\r')
172 | # uibcport = uibcport[0]
173 | # uibcport = uibcport.split('=')
174 | # uibcport = uibcport[1]
175 | # print('uibcport:'+uibcport+"\n")
176 | # if 'none' not in uibcport and enable_mouse_keyboard == 1:
177 | # os.system('pkill control.bin')
178 | # os.system('pkill controlhidc.bin')
179 | # if('hidc_cap_list=none' not in entry):
180 | # os.system('./control/controlhidc.bin '+ uibcport + ' ' + sourceip + ' &')
181 | # elif('generic_cap_list=none' not in entry):
182 | # os.system('./control/control.bin '+ uibcport + ' &')
183 |
184 | # uibcstart(sock,data)
185 |
186 | def killall(control):
187 | os.system('pkill vlc')
188 | if display_power_management == 1:
189 | os.system('vcgencmd display_power 0')
190 |
191 | # M5
192 | data = sock.recv(1000)
193 | data = data.decode()
194 | print('M5')
195 | print(data)
196 |
197 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 4\r\n\r\n'
198 | print(s_data)
199 | sock.sendall(s_data.encode())
200 |
201 |
202 | # M6
203 | m6req ='SETUP rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
204 | +'CSeq: 5\r\n'\
205 | +'Transport: RTP/AVP/UDP;unicast;client_port=1028\r\n\r\n'
206 | print('M6')
207 | print(m6req)
208 | sock.sendall(m6req.encode())
209 |
210 | data = sock.recv(1000)
211 | data = data.decode()
212 | print(data)
213 |
214 | paralist=data.split(';')
215 | print(paralist)
216 | serverport=[x for x in paralist if 'server_port=' in x]
217 | print(serverport)
218 | serverport=serverport[-1]
219 | serverport=serverport[12:17]
220 | print(serverport)
221 |
222 | paralist=data.split( )
223 | position=paralist.index('Session:')+1
224 | sessionid=paralist[position]
225 |
226 |
227 | # M7
228 | m7req ='PLAY rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
229 | +'CSeq: 6\r\n'\
230 | +'Session: '+str(sessionid)+'\r\n\r\n'
231 | print("<---M7---\n" + m7req)
232 | sock.sendall(m7req.encode())
233 |
234 | data = sock.recv(1000)
235 | data = data.decode()
236 | print(data)
237 |
238 | print("---- Negotiation successful ----")
239 |
240 |
241 | player_select = 0
242 |
243 | def launchplayer(player_select):
244 |
245 | #os.system('nc -u -l 1028 > test.ts')
246 | #os.system('gst-launch-1.0 -v udpsrc port=1028 ! tsdemux name=d ! h264parse ! queue ! v4l2h264dec capture-io-mode=4 ! kmssink d. ! queue ! decodebin ! audioconvert ! audioresample ! alsasink &')
247 | #os.system('gst-launch-1.0 -v udpsrc port=1028 ! tsparse set-timestamps=true ! tsdemux name=d ! h264parse ! queue ! v4l2h264dec capture-io-mode=4 ! kmssink &')
248 | os.system('vlc --fullscreen rtp://0.0.0.0:1028/wfd1.0/streamid=0 --intf dummy --no-ts-trust-pcr --ts-seek-percent --network-caching=100 --no-mouse-events & ')
249 | # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=autovideosink audio-sink=alsasink sync=false &')
250 | # # os.system('gst-launch-1.0 -v udpsrc port=1028 ! application/x-rtp,media=video,encoding-name=H264 ! queue ! rtph264depay ! avdec_h264 ! autovideosink &')
251 | # # os.system('gst-launch-1.0 -v udpsrc port=1028 ! video/mpegts ! tsdemux ! h264parse ! queue ! avdec_h264 ! ximagesink sync=false &')
252 | # # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=ximagesink audio-sink=alsasink sync=false &')
253 | # # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=xvimagesink audio-sink=alsasink sync=false &')
254 | # if True:
255 | #os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=kmssink audio-sink=alsasink sync=true &')
256 | # else:
257 | # os.system('vlc --fullscreen rtp://0.0.0.0:1028/wfd1.0/streamid=0 --intf dummy --no-ts-trust-pcr --ts-seek-percent --network-caching=300 --no-mouse-events & ')
258 |
259 |
260 | launchplayer(player_select)
261 |
262 |
263 |
264 | csnum = 102
265 | while True:
266 | data = sock.recv(1000)
267 | data = data.decode()
268 | print(data)
269 | watchdog = 0
270 | if len(data)==0 or 'wfd_trigger_method: TEARDOWN' in data:
271 | killall(True)
272 | sleep(1)
273 | break
274 | elif 'wfd_video_formats' in data:
275 | launchplayer(player_select)
276 | messagelist=data.split('\r\n\r\n')
277 | print(messagelist)
278 | singlemessagelist=[x for x in messagelist if ('GET_PARAMETER' in x or 'SET_PARAMETER' in x )]
279 | print(singlemessagelist)
280 | for singlemessage in singlemessagelist:
281 | entrylist=singlemessage.split('\r')
282 | for entry in entrylist:
283 | if 'CSeq' in entry:
284 | cseq = entry
285 |
286 | resp='RTSP/1.0 200 OK\r'+cseq+'\r\n\r\n';#cseq contains \n
287 | print(resp)
288 | sock.sendall(resp.encode())
289 |
290 | # uibcstart(sock,data)
291 |
292 |
293 | sock.close()
294 |
295 |
296 |
297 |
--------------------------------------------------------------------------------
/d2win10debug.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | """
4 | This software is part of lazycast, a simple wireless display receiver for Raspberry Pi
5 | Copyright (C) 2018 Hsun-Wei Cho
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | """
17 | import socket
18 | import fcntl, os
19 | import errno
20 | import threading
21 | from threading import Thread
22 | import time
23 | from time import sleep
24 | import sys
25 | import subprocess
26 | import argparse
27 | ##################### Settings #####################
28 | player_select = 2
29 | # 0: non-RPi systems. (using vlc or gstreamer)
30 | # 1: player1 has lower latency.
31 | # 2: player2 handles still images and sound better.
32 | # 3: omxplayer # Using this option for video playback on Android
33 | sound_output_select = 0
34 | # 0: HDMI sound output
35 | # 1: 3.5mm audio jack output
36 | # 2: alsa
37 | disable_1920_1080_60fps = 1
38 | enable_mouse_keyboard = 0
39 |
40 | display_power_management = 0
41 | # 1: (For projectors) Put the display in sleep mode when not in use by lazycast
42 |
43 | ####################################################
44 |
45 | parser = argparse.ArgumentParser()
46 | parser.add_argument('arg1', nargs='?', default='192.168.173.80')
47 | args = parser.parse_args()
48 | sourceip = vars(args)['arg1']
49 |
50 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
51 | server_address = (sourceip, 7236)
52 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
53 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
54 |
55 | connectcounter = 0
56 | while True:
57 | try:
58 | sock.connect(server_address)
59 | except socket.error as e:
60 | #connectcounter = connectcounter + 1
61 | #if connectcounter == 3:
62 | sock.close()
63 | sys.exit(1)
64 | else:
65 | break
66 |
67 | cpuinfo = os.popen('grep Hardware /proc/cpuinfo')
68 | cpustr = cpuinfo.read()
69 | runonpi = 'BCM2835' in cpustr or 'BCM2711' in cpustr
70 | cpuinfo.close()
71 |
72 | idrsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
73 | idrsock_address = ('127.0.0.1', 0)
74 | idrsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
75 | idrsock.bind(idrsock_address)
76 | addr, idrsockport = idrsock.getsockname()
77 |
78 | data = sock.recv(2048)
79 | data = data.decode()
80 | print("---M1--->\n" + data)
81 | s_data = '525453502f312e3020323030204f4b0d0a446174653a204d6f6e2c203136204a616e20323032332032333a34303a343020474d540d0a5075626c69633a206f72672e7766612e776664312e302c204745545f504152414d455445522c205345545f504152414d455445520d0a435365713a20310d0a0d0a'
82 | sock.sendall(bytes.fromhex(s_data))
83 |
84 | print('sgsdg')
85 |
86 | # M2
87 | s_data = '4f5054494f4e53202a20525453502f312e300d0a526571756972653a206f72672e7766612e776664312e300d0a435365713a20310d0a0d0a'
88 | sock.sendall(bytes.fromhex(s_data))
89 |
90 | data = sock.recv(2048)
91 | data = data.decode()
92 | print("-------->\n" + data)
93 | m2data = data
94 |
95 |
96 | # M3
97 | data = sock.recv(2048)
98 | data = data.decode()
99 | print("---M3--->\n" + data)
100 |
101 | msg = 'wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\nwfd2_audio_codecs: LPCM 000001ff 00\r\nwfd2_video_formats: 40 01 04 0080 000001ffbdeb 000155557fff 000000000fff 10 0000 001f 11, 01 01 0080 000001ffbdeb 0001555557ff 000000000fff 10 0000 001f 11 00\r\nmicrosoft_video_formats: 0000001fffff\r\nwfd_content_protection: none\r\nwfd_connector_type: 05\r\nwfd_uibc_capability: input_category_list=HIDC;hidc_cap_list=Keyboard/USB, Mouse/USB, MultiTouch/USB, Gesture/USB, RemoteControl/USB, Joystick/USB;port=none\r\nwfd2_video_stream_control: 0f 0f\r\nintel_friendly_name: Tablet\r\nintel_sink_manufacturer_name: Microsoft\r\nintel_sink_model_name: Windows PC\r\nintel_sink_device_URL: none\r\nwfd_idr_request_capability: 1\r\nmicrosoft_latency_management_capability: none\r\nmicrosoft_format_change_capability: supported\r\nmicrosoft_diagnostics_capability: supported\r\nmicrosoft_multiscreen_projection: supported\r\nmicrosoft_audio_mute: supported\r\nmicrosoft_cursor: none 0100 0100 4abf\r\nmicrosoft_rtcp_capability: supported\r\nwfd2_rotation_capability: supported\r\nmicrosoft_max_bitrate: 200000000'
102 |
103 |
104 |
105 | m3resp ='RTSP/1.0 200 OK\r\nCSeq: 2\r\n'+'Content-Type: text/parameters\r\nContent-Length: '+str(len(msg))+'\r\n\r\n'+msg
106 | print("<--------\n" + m3resp)
107 | sock.sendall(m3resp.encode())
108 |
109 |
110 | # M4
111 | data = sock.recv(2048)
112 | data = data.decode()
113 | print("---M4--->\n" + data)
114 |
115 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 3\r\n\r\n'
116 | print("<--------\n" + s_data)
117 | sock.sendall(s_data.encode())
118 |
119 |
120 |
121 | def killall(control):
122 | os.system('pkill vlc')
123 | os.system('pkill cvlc')
124 | os.system('pkill gst-launch-1.0')
125 | os.system('pkill player.bin')
126 | os.system('pkill h264.bin')
127 | if display_power_management == 1:
128 | os.system('vcgencmd display_power 0')
129 | if control:
130 | os.system('pkill control.bin')
131 | os.system('pkill controlhidc.bin')
132 |
133 | # M5
134 | data = sock.recv(2048)
135 | data = data.decode()
136 | print("---M5--->\n" + data)
137 |
138 | s_data = 'RTSP/1.0 200 OK\r\nCSeq: 4\r\n\r\n'
139 | print("<--------\n" + s_data)
140 | sock.sendall(s_data.encode())
141 |
142 |
143 | # M6
144 | m6req ='SETUP rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
145 | +'CSeq: 5\r\n'\
146 | +'Transport: RTP/AVP/UDP;unicast;client_port=1028-1029\r\n\r\n'
147 | print("<---M6---\n" + m6req)
148 | sock.sendall(m6req.encode())
149 |
150 | data = sock.recv(2048)
151 | data = data.decode()
152 | print("-------->\n" + data)
153 |
154 | paralist=data.split(';')
155 | print(paralist)
156 | serverport=[x for x in paralist if 'server_port=' in x]
157 | print(serverport)
158 | serverport=serverport[-1]
159 | serverport=serverport[12:17]
160 | print(serverport)
161 |
162 | paralist=data.split( )
163 | position=paralist.index('Session:')+1
164 | sessionid=paralist[position]
165 |
166 |
167 |
168 |
169 |
170 | if not runonpi:
171 | player_select = 0
172 |
173 | def launchplayer(player_select):
174 | killall(False)
175 | if display_power_management == 1:
176 | os.system('vcgencmd display_power 1')
177 | if player_select == 0:
178 | # os.system('gst-launch-1.0 -v udpsrc port=1028 ! application/x-rtp,media=video,encoding-name=H264 ! queue ! rtph264depay ! avdec_h264 ! autovideosink &')
179 | # os.system('gst-launch-1.0 -v udpsrc port=1028 ! video/mpegts ! tsdemux ! h264parse ! queue ! avdec_h264 ! ximagesink sync=false &')
180 | # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=ximagesink audio-sink=alsasink sync=false &')
181 | # os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=xvimagesink audio-sink=alsasink sync=false &')
182 | if False: # Change False to True if you want to use gstreamer
183 | os.system('gst-launch-1.0 -v playbin uri=udp://0.0.0.0:1028/wfd1.0/streamid=0 video-sink=autovideosink audio-sink=alsasink sync=false &')
184 | else:
185 | os.system('vlc --fullscreen rtp://0.0.0.0:1028/wfd1.0/streamid=0 --intf dummy --no-ts-trust-pcr --ts-seek-percent --network-caching=300 --no-mouse-events & ')
186 | elif player_select == 1:
187 | os.system('./player/player.bin '+str(idrsockport)+' '+str(sound_output_select)+' &')
188 | elif player_select == 2:
189 | sinkip = sock.getsockname()[0]
190 | print(sinkip)
191 | print('./h264/h264.bin '+str(idrsockport)+' '+str(sound_output_select)+' '+sinkip+' &')
192 | os.system('./h264/h264.bin '+str(idrsockport)+' '+str(sound_output_select)+' '+sinkip+' &')
193 | elif player_select == 3:
194 | #if 'MSMiracastSource' in m2data:
195 | # os.system('omxplayer rtp://0.0.0.0:1028 -n -1 --live &') # For Windows 10 when no sound is playing
196 | #else:
197 | # os.system('omxplayer rtp://0.0.0.0:1028 --live &')
198 | #os.system('omxplayer rtp://0.0.0.0:1028 -i')
199 | omxplayerinfo = subprocess.Popen('omxplayer rtp://0.0.0.0:1028 -i'.split(),stderr=subprocess.PIPE).communicate()
200 | if '0 channels' in omxplayerinfo[1]:
201 | os.system('omxplayer rtp://0.0.0.0:1028 -n -1 --live &') # For Windows 10 when no sound is playing
202 | else:
203 | os.system('omxplayer rtp://0.0.0.0:1028 --live &')
204 |
205 | launchplayer(player_select)
206 |
207 |
208 | # M7
209 | m7req ='PLAY rtsp://'+sourceip+'/wfd1.0/streamid=0 RTSP/1.0\r\n'\
210 | +'User-Agent: MSMiracastSink/10.00.19041.2486\r\n'\
211 | +'CSeq: 6\r\n'\
212 | +'Session: '+str(sessionid)+'\r\n\r\n'
213 | print("<---M7---\n" + m7req)
214 | sock.sendall(m7req.encode())
215 |
216 | data = sock.recv(2048)
217 | data = data.decode()
218 | print("-------->\n" + data)
219 |
220 | print("---- Negotiation successful ----")
221 |
222 |
223 | while False:
224 | data = sock.recv(2048)
225 | data = data.decode()
226 | print(data)
227 | if len(data)==0 or 'wfd_trigger_method: TEARDOWN' in data:
228 | killall(True)
229 | sleep(1)
230 | break
231 | elif 'wfd_video_formats' in data:
232 | launchplayer(player_select)
233 | messagelist=data.split('\r\n\r\n')
234 | print(messagelist)
235 | singlemessagelist=[x for x in messagelist if ('GET_PARAMETER' in x or 'SET_PARAMETER' in x )]
236 | print(singlemessagelist)
237 | for singlemessage in singlemessagelist:
238 | entrylist=singlemessage.split('\r')
239 | for entry in entrylist:
240 | if 'CSeq' in entry:
241 | cseq = entry
242 |
243 | resp='RTSP/1.0 200 OK\r'+cseq+'\r\n\r\n';#cseq contains \n
244 | print(resp)
245 | sock.sendall(resp.encode())
246 |
247 |
248 |
249 | fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
250 | fcntl.fcntl(idrsock, fcntl.F_SETFL, os.O_NONBLOCK)
251 |
252 |
253 | csnum = 102
254 | watchdog = 0
255 | while True:
256 | try:
257 | data = sock.recv(2048)
258 | data = data.decode()
259 | except socket.error as e:
260 | err = e.args[0]
261 | processrunning = os.popen('ps au').read()
262 | if player_select == 2 and 'h264.bin' not in processrunning:
263 | launchplayer(player_select)
264 | # if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
265 | # try:
266 | # datafromc = idrsock.recv(1000)
267 | # datafromc = datafromc.decode()
268 | # except socket.error as e:
269 | # err = e.args[0]
270 | # if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
271 | # processrunning = os.popen('ps au').read()
272 | # if player_select == 2 and 'h264.bin' not in processrunning:
273 | # launchplayer(player_select)
274 | # sleep(0.01)
275 | # # else:
276 | # # watchdog = watchdog + 1
277 | # # if watchdog == 70/0.01:
278 | # # killall(True)
279 | # # sleep(1)
280 | # # break
281 | # else:
282 | # sys.exit(1)
283 | # else:
284 | # print(datafromc)
285 | # elemfromc = datafromc.split(' ')
286 | # if elemfromc[0] == 'recv':
287 | # killall(True)
288 | # sleep(1)
289 | # break
290 |
291 |
292 | # else:
293 | # csnum = csnum + 1
294 | # msg = 'wfd_idr_request\r\n'
295 | # idrreq ='SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n'\
296 | # +'Content-Length: '+str(len(msg))+'\r\n'\
297 | # +'Content-Type: text/parameters\r\n'\
298 | # +'CSeq: '+str(csnum)+'\r\n\r\n'\
299 | # +msg
300 |
301 | # print(idrreq)
302 | # sock.sendall(idrreq.encode())
303 |
304 | # else:
305 | # sys.exit(1)
306 | else:
307 | print(data)
308 | watchdog = 0
309 | if len(data)==0 or 'wfd_trigger_method: TEARDOWN' in data:
310 | killall(True)
311 | sleep(1)
312 | break
313 | elif 'wfd_video_formats' in data:
314 | launchplayer(player_select)
315 | messagelist=data.split('\r\n\r\n')
316 | print(messagelist)
317 | singlemessagelist=[x for x in messagelist if ('GET_PARAMETER' in x or 'SET_PARAMETER' in x )]
318 | print(singlemessagelist)
319 | for singlemessage in singlemessagelist:
320 | entrylist=singlemessage.split('\r')
321 | for entry in entrylist:
322 | if 'CSeq' in entry:
323 | cseq = entry
324 |
325 | resp='RTSP/1.0 200 OK\r'+cseq+'\r\n\r\n';#cseq contains \n
326 | print(resp)
327 | sock.sendall(resp.encode())
328 |
329 | #uibcstart(sock,data)
330 |
331 | idrsock.close()
332 | sock.close()
333 |
334 |
335 |
336 |
--------------------------------------------------------------------------------
/h264/Makefile:
--------------------------------------------------------------------------------
1 | OBJS=h264.o audio.o
2 | BIN=./h264.bin
3 | DMX_INC = -I/opt/vc/include/ -I /opt/vc/include/interface/vmcs_host/ -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux -I/opt/vc/include/interface/vcos/
4 | EGL_INC =
5 | OMX_INC = -I /opt/vc/include/IL
6 | OMX_ILCLIENT_INC = -I/opt/vc/src/hello_pi/libs/ilclient
7 | INCLUDES = $(DMX_INC) $(EGL_INC) $(OMX_INC) $(OMX_ILCLIENT_INC)
8 | CFLAGS+= -DOMX_SKIP64BIT $(INCLUDES)
9 | LDFLAGS+= -lilclient -lavformat -lavcodec -lavutil -lasound
10 |
11 | include ./Makefile.include
12 |
13 |
--------------------------------------------------------------------------------
/h264/Makefile.include:
--------------------------------------------------------------------------------
1 |
2 | CFLAGS+=-DSTANDALONE -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS -DTARGET_POSIX -D_LINUX -fPIC -DPIC -D_REENTRANT -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -Wall -g -DHAVE_LIBOPENMAX=2 -DOMX -DOMX_SKIP64BIT -ftree-vectorize -pipe -DUSE_EXTERNAL_OMX -DHAVE_LIBBCM_HOST -DUSE_EXTERNAL_LIBBCM_HOST -DUSE_VCHIQ_ARM -Wno-psabi
3 |
4 | LDFLAGS+=-L$(SDKSTAGE)/opt/vc/lib/ -lbrcmGLESv2 -lbrcmEGL -lopenmaxil -lbcm_host -lvcos -lvchiq_arm -lpthread -lrt -lm -L$(SDKSTAGE)/opt/vc/src/hello_pi/libs/ilclient -L$(SDKSTAGE)/opt/vc/src/hello_pi/libs/vgfont
5 |
6 | INCLUDES+=-I$(SDKSTAGE)/opt/vc/include/ -I$(SDKSTAGE)/opt/vc/include/interface/vcos/pthreads -I$(SDKSTAGE)/opt/vc/include/interface/vmcs_host/linux -I./ -I$(SDKSTAGE)/opt/vc/src/hello_pi/libs/ilclient -I$(SDKSTAGE)/opt/vc/src/hello_pi/libs/vgfont
7 |
8 | all: $(BIN) $(LIB)
9 |
10 | %.o: %.c
11 | @rm -f $@
12 | $(CC) $(CFLAGS) $(INCLUDES) -g -c $< -o $@ -Wno-deprecated-declarations
13 |
14 | %.o: %.cpp
15 | @rm -f $@
16 | $(CXX) $(CFLAGS) $(INCLUDES) -g -c $< -o $@ -Wno-deprecated-declarations
17 |
18 | %.bin: $(OBJS)
19 | $(CC) -o $@ -Wl,--whole-archive $(OBJS) $(LDFLAGS) -Wl,--no-whole-archive -rdynamic
20 |
21 | %.a: $(OBJS)
22 | $(AR) r $@ $^
23 |
24 | clean:
25 | for i in $(OBJS); do (if test -e "$$i"; then ( rm $$i ); fi ); done
26 | @rm -f $(BIN) $(LIB)
27 |
28 |
29 |
--------------------------------------------------------------------------------
/h264/audio.c:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2012, Broadcom Europe Ltd
3 | All rights reserved.
4 |
5 | Redistribution and use in source and binary forms, with or without
6 | modification, are permitted provided that the following conditions are met:
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 | * Redistributions in binary form must reproduce the above copyright
10 | notice, this list of conditions and the following disclaimer in the
11 | documentation and/or other materials provided with the distribution.
12 | * Neither the name of the copyright holder nor the
13 | names of its contributors may be used to endorse or promote products
14 | derived from this software without specific prior written permission.
15 |
16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 | */
27 |
28 | // Audio output demo using OpenMAX IL though the ilcient helper library
29 |
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 |
36 | #include "bcm_host.h"
37 | #include "ilclient.h"
38 | #include
39 |
40 |
41 | typedef int int32_t;
42 | static uint32_t audioplay_alsapcm_init(void);
43 |
44 | snd_pcm_t *pcm_dev = NULL;
45 | uint8_t is_alsa = 0;
46 |
47 |
48 | int32_t audioplay_create(ILCLIENT_T *client, COMPONENT_T** audio_render, COMPONENT_T **list, int listindex)
49 | {
50 | int32_t ret = -1;
51 |
52 | int size = 4096;
53 |
54 |
55 | OMX_ERRORTYPE error;
56 | OMX_PARAM_PORTDEFINITIONTYPE param;
57 | OMX_AUDIO_PARAM_PCMMODETYPE pcm;
58 |
59 | ret = 0;
60 |
61 |
62 | ilclient_create_component(client, audio_render, "audio_render", ILCLIENT_ENABLE_INPUT_BUFFERS | ILCLIENT_DISABLE_ALL_PORTS);
63 | assert(*audio_render != NULL);
64 |
65 | list[listindex] = *audio_render;
66 |
67 | // set up the number/size of buffers
68 | memset(¶m, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
69 | param.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
70 | param.nVersion.nVersion = OMX_VERSION;
71 | param.nPortIndex = 100;
72 |
73 | error = OMX_GetParameter(ILC_GET_HANDLE(*audio_render), OMX_IndexParamPortDefinition, ¶m);
74 | assert(error == OMX_ErrorNone);
75 |
76 | param.nBufferSize = size;
77 | param.nBufferCountActual = 4;
78 | //param.nBufferCountActual = num_buffers;
79 |
80 | error = OMX_SetParameter(ILC_GET_HANDLE(*audio_render), OMX_IndexParamPortDefinition, ¶m);
81 | assert(error == OMX_ErrorNone);
82 |
83 | // set the pcm parameters
84 | memset(&pcm, 0, sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
85 | pcm.nSize = sizeof(OMX_AUDIO_PARAM_PCMMODETYPE);
86 | pcm.nVersion.nVersion = OMX_VERSION;
87 | pcm.nPortIndex = 100;
88 | pcm.nChannels = 2;
89 | pcm.eNumData = OMX_NumericalDataSigned;
90 | pcm.eEndian = OMX_EndianBig;
91 | pcm.nSamplingRate = 48000;
92 | pcm.bInterleaved = OMX_TRUE;
93 | pcm.nBitPerSample = 16;
94 | pcm.ePCMMode = OMX_AUDIO_PCMModeLinear;
95 |
96 | pcm.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
97 | pcm.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
98 |
99 | error = OMX_SetParameter(ILC_GET_HANDLE(*audio_render), OMX_IndexParamAudioPcm, &pcm);
100 | assert(error == OMX_ErrorNone);
101 |
102 | ilclient_change_component_state(*audio_render, OMX_StateIdle);
103 | if(ilclient_enable_port_buffers(*audio_render, 100, NULL, NULL, NULL) < 0)
104 | {
105 | // error
106 | ilclient_change_component_state(*audio_render, OMX_StateLoaded);
107 |
108 | return -1;
109 | }
110 |
111 | ilclient_change_component_state(*audio_render, OMX_StateExecuting);
112 |
113 | return ret;
114 | }
115 |
116 | int32_t audioplay_delete(COMPONENT_T *audio_render)
117 | {
118 | OMX_ERRORTYPE error;
119 |
120 | ilclient_change_component_state(audio_render, OMX_StateIdle);
121 |
122 | error = OMX_SendCommand(ILC_GET_HANDLE(audio_render), OMX_CommandStateSet, OMX_StateLoaded, NULL);
123 | assert(error == OMX_ErrorNone);
124 |
125 | ilclient_change_component_state(audio_render, OMX_StateLoaded);
126 |
127 | assert(error == OMX_ErrorNone);
128 |
129 |
130 | return 0;
131 | }
132 |
133 |
134 | #include
135 | int32_t audioplay_play_buffer(COMPONENT_T *audio_render, uint8_t *buffer, uint32_t length)
136 | {
137 | if(is_alsa) {
138 | int pcmreturn;
139 |
140 | while ((pcmreturn = snd_pcm_writei(pcm_dev, buffer, length>>2)) < 0) {
141 | snd_pcm_prepare(pcm_dev);
142 | printf("--:%u----\n", length);
143 | }
144 | }
145 | else {
146 | OMX_BUFFERHEADERTYPE *hdr = ilclient_get_input_buffer(audio_render, 100, 0);
147 | int32_t ret = -1;
148 |
149 | if (hdr == NULL)
150 | return ret;
151 |
152 | OMX_ERRORTYPE error;
153 |
154 | hdr->nOffset = 0;
155 | memcpy(hdr->pBuffer, buffer, length);
156 | hdr->nFilledLen = length;
157 |
158 | error = OMX_EmptyThisBuffer(ILC_GET_HANDLE(audio_render), hdr);
159 | assert(error == OMX_ErrorNone);
160 | }
161 | return 0;
162 | }
163 |
164 | int32_t audioplay_set_dest(COMPONENT_T *audio_render, const char *name)
165 | {
166 | int32_t success = -1;
167 | OMX_CONFIG_BRCMAUDIODESTINATIONTYPE ar_dest;
168 |
169 | if (name && strlen(name) < sizeof(ar_dest.sName))
170 | {
171 | printf("set audio backend :%s\n", name);
172 | if(strcmp(name, "alsa") == 0) {
173 | is_alsa = 1;
174 |
175 | audioplay_alsapcm_init();
176 | }
177 | else {
178 | is_alsa = 0;
179 |
180 | OMX_ERRORTYPE error;
181 | memset(&ar_dest, 0, sizeof(ar_dest));
182 | ar_dest.nSize = sizeof(OMX_CONFIG_BRCMAUDIODESTINATIONTYPE);
183 | ar_dest.nVersion.nVersion = OMX_VERSION;
184 | strcpy((char *)ar_dest.sName, name);
185 |
186 | error = OMX_SetConfig(ILC_GET_HANDLE(audio_render), OMX_IndexConfigBrcmAudioDestination, &ar_dest);
187 | assert(error == OMX_ErrorNone);
188 | }
189 | success = 0;
190 | }
191 |
192 | return success;
193 | }
194 |
195 | static uint32_t audioplay_alsapcm_init(void)
196 | {
197 | int err, retry_times;
198 | unsigned int rate;
199 | snd_pcm_hw_params_t *hwp;
200 | snd_pcm_uframes_t buffer_size, period_size, period_size_max;
201 |
202 | retry_times = 0;
203 | reopen:
204 | printf("alsa pcm init ...\n");
205 | err = snd_pcm_open(&pcm_dev, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
206 | if (err < 0) {
207 | if(++retry_times > 2) {
208 | goto alsa_error;
209 | }
210 | else {
211 | usleep(300);
212 | goto reopen;
213 | }
214 | }
215 | retry_times = 0;
216 |
217 | rate = 48000;
218 | buffer_size = rate / 5;
219 | period_size = buffer_size / 4;
220 | period_size_max = buffer_size / 3;
221 |
222 |
223 | snd_pcm_hw_params_alloca(&hwp);
224 | snd_pcm_hw_params_any(pcm_dev, hwp);
225 | err = snd_pcm_hw_params_set_channels(pcm_dev, hwp, 2);
226 | if (err)
227 | goto alsa_error;
228 | err = snd_pcm_hw_params_set_access(pcm_dev, hwp, SND_PCM_ACCESS_RW_INTERLEAVED);
229 | if (err)
230 | goto alsa_error;
231 | err = snd_pcm_hw_params_set_rate_near(pcm_dev, hwp, &rate, 0);
232 | if (err)
233 | goto alsa_error;
234 | err = snd_pcm_hw_params_set_format(pcm_dev, hwp, SND_PCM_FORMAT_S16_BE);
235 | if (err)
236 | goto alsa_error;
237 | err = snd_pcm_hw_params_set_period_size_max(pcm_dev, hwp, &period_size_max, 0);
238 | if (err)
239 | goto alsa_error;
240 | err = snd_pcm_hw_params_set_buffer_size_near(pcm_dev, hwp, &buffer_size);
241 | if (err)
242 | goto alsa_error;
243 | err = snd_pcm_hw_params_set_period_size_near(pcm_dev, hwp, &period_size, 0);
244 | if (err) goto alsa_error;
245 | err = snd_pcm_hw_params(pcm_dev, hwp);
246 | if (err)
247 | goto alsa_error;
248 | printf("alsa config success\n");
249 |
250 | int dir;
251 | snd_pcm_hw_params_get_rate(hwp, &rate, &dir);
252 | printf("rate = %d bps\n", rate);
253 |
254 | snd_pcm_hw_params_get_period_time(hwp, &rate, &dir);
255 | printf("period time = %d us\n", rate);
256 |
257 | snd_pcm_hw_params_get_period_size(hwp, &period_size_max, &dir);
258 | printf("period size = %d frames\n", (int)period_size_max);
259 |
260 | snd_pcm_hw_params_get_buffer_time(hwp, &rate, &dir);
261 | printf("buffer time = %d us\n", rate);
262 |
263 | snd_pcm_hw_params_get_buffer_size(hwp, (snd_pcm_uframes_t *) &buffer_size);
264 | printf("buffer size = %ld frames\n", buffer_size);
265 |
266 | snd_pcm_hw_params_get_periods(hwp, &rate, &dir);
267 | printf("periods per buffer = %d frames\n", rate);
268 |
269 | printf("alsa init success\n");
270 |
271 | return 0;
272 |
273 | alsa_error:
274 | if (pcm_dev)
275 | snd_pcm_close(pcm_dev);
276 |
277 | printf("alsa init failed\n");
278 |
279 | return 1;
280 | }
281 |
282 | uint32_t audioplay_get_latency(COMPONENT_T *audio_render)
283 | {
284 | OMX_PARAM_U32TYPE param;
285 | OMX_ERRORTYPE error;
286 |
287 | memset(¶m, 0, sizeof(OMX_PARAM_U32TYPE));
288 | param.nSize = sizeof(OMX_PARAM_U32TYPE);
289 | param.nVersion.nVersion = OMX_VERSION;
290 | param.nPortIndex = 100;
291 |
292 | error = OMX_GetConfig(ILC_GET_HANDLE(audio_render), OMX_IndexConfigAudioRenderingLatency, ¶m);
293 | assert(error == OMX_ErrorNone);
294 |
295 | return param.nU32;
296 | }
297 |
298 |
299 |
--------------------------------------------------------------------------------
/h264/audio.h:
--------------------------------------------------------------------------------
1 | int32_t audioplay_create(ILCLIENT_T *, COMPONENT_T *, COMPONENT_T **, int);
2 | int32_t audioplay_delete(COMPONENT_T *);
3 | int32_t audioplay_play_buffer(COMPONENT_T *, uint8_t *, uint32_t);
4 | int32_t audioplay_set_dest(COMPONENT_T *, const char *);
5 | uint32_t audioplay_get_latency(COMPONENT_T *);
6 |
--------------------------------------------------------------------------------
/h264/h264.c:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2012, Broadcom Europe Ltd
3 | All rights reserved.
4 | Copyright (c) 2018, Hsun-Wei Cho
5 |
6 | Redistribution and use in source and binary forms, with or without
7 | modification, are permitted provided that the following conditions are met:
8 | * Redistributions of source code must retain the above copyright
9 | notice, this list of conditions and the following disclaimer.
10 | * Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in the
12 | documentation and/or other materials provided with the distribution.
13 | * Neither the name of the copyright holder nor the
14 | names of its contributors may be used to endorse or promote products
15 | derived from this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
21 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | */
28 |
29 | // Video deocode demo using OpenMAX IL though the ilcient helper library
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 | #include
37 |
38 | #include
39 | #include
40 |
41 | #include "bcm_host.h"
42 | #include "ilclient.h"
43 | #include "audio.h"
44 |
45 | #define here() printf("line:%d\n",__LINE__);
46 |
47 | typedef struct srtppacket
48 | {
49 | unsigned char* buf;
50 | int recvlen;
51 | int seqnum;
52 | struct srtppacket* next;
53 | } rtppacket;
54 |
55 | atomic_int numofnode;
56 |
57 |
58 | int largers(int a, int b)
59 | {
60 | if (abs(a - b) < 32768)
61 | return a > b;
62 | else if (a - b <= -32768)
63 | return 1;
64 | else
65 | return 0;
66 | }
67 |
68 | int sendtodecoder(COMPONENT_T *video_decode, COMPONENT_T *video_scheduler, COMPONENT_T *video_render, TUNNEL_T* tunnel,
69 | OMX_BUFFERHEADERTYPE *buf, rtppacket **beg, rtppacket *scan,
70 | int* port_settings_changed, int *first)
71 | {
72 | int loop = 1;
73 | int theveryfirst = 1;
74 | while (loop)
75 | {
76 | buf = ilclient_get_input_buffer(video_decode, 130, 1);
77 | if (buf == NULL)
78 | return 0;
79 | unsigned char *dest = buf->pBuffer;
80 |
81 | int data_len = 0;
82 | while (1)
83 | {
84 | int numofts = ((*beg)->recvlen - 12) / 188;
85 | for (int i = 0; i < numofts; i++)
86 | {
87 | unsigned char* buffer = (*beg)->buf + 12 + i * 188;
88 | short pid = ((0x1F & buffer[1]) << 8) + buffer[2];
89 | if (pid != 0x1011)
90 | continue;
91 | int ad = 3 & (buffer[3] >> 4);
92 | if (ad & 1)
93 | {
94 | int adlen = buffer[4];
95 | int shift = (ad == 1) ? 4 : adlen + 5;
96 | if (theveryfirst)
97 | {
98 | shift += 14;
99 | theveryfirst = 0;
100 | }
101 | memcpy(dest + data_len, buffer + shift, 188 - shift);
102 | data_len += 188 - shift;
103 | }
104 | }
105 |
106 | rtppacket* nexttemp = (*beg)->next;
107 | free((*beg)->buf);
108 | free((*beg));
109 | (*beg) = nexttemp;
110 |
111 | if ((*beg) == scan)
112 | {
113 | loop = 0;
114 | break;
115 | }
116 | else if (buf->nAllocLen - data_len < 1500)
117 | {
118 | break;
119 | }
120 |
121 |
122 | }
123 |
124 | if ((*port_settings_changed) == 0 &&
125 | ((data_len > 0 && ilclient_remove_event(video_decode, OMX_EventPortSettingsChanged, 131, 0, 0, 1) == 0) ||
126 | (data_len == 0 && ilclient_wait_for_event(video_decode, OMX_EventPortSettingsChanged, 131, 0, 0, 1,
127 | ILCLIENT_EVENT_ERROR | ILCLIENT_PARAMETER_CHANGED, 10000) == 0)))
128 | {
129 | *port_settings_changed = 1;
130 |
131 | if (ilclient_setup_tunnel(tunnel, 0, 0) != 0)
132 | return -7;
133 |
134 | ilclient_change_component_state(video_scheduler, OMX_StateExecuting);
135 |
136 | // now setup tunnel to video_render
137 | if (ilclient_setup_tunnel(tunnel + 1, 0, 1000) != 0)
138 | return -12;
139 |
140 | ilclient_change_component_state(video_render, OMX_StateExecuting);
141 | }
142 |
143 | const unsigned char sidedata[14] = { 0xea, 0x00, 0x00, 0x00,
144 | 0x01, 0xce, 0x8c, 0x4d,
145 | 0x9d, 0x10, 0x8e, 0x25, 0xe9, 0xfe };
146 |
147 |
148 | if (!loop)
149 | {
150 | memcpy(dest + data_len, sidedata, 14);
151 | data_len += 14;
152 | buf->nFlags |= OMX_BUFFERFLAG_ENDOFFRAME;
153 | }
154 |
155 |
156 | buf->nFilledLen = data_len;
157 |
158 | //printf("len:%d\n", data_len);
159 |
160 | buf->nOffset = 0;
161 | if (*first)
162 | {
163 | buf->nFlags |= OMX_BUFFERFLAG_STARTTIME;
164 | *first = 0;
165 | }else
166 | buf->nFlags |= OMX_BUFFERFLAG_TIME_UNKNOWN;
167 |
168 |
169 |
170 |
171 |
172 |
173 | if (OMX_EmptyThisBuffer(ILC_GET_HANDLE(video_decode), buf) != OMX_ErrorNone)
174 | return -6;
175 | }
176 |
177 | }
178 |
179 |
180 | int idrsockport = -1;
181 | char* sinkip = "192.168.173.1";
182 | static void* addnullpacket(rtppacket* beg)
183 | {
184 | struct sockaddr_in addr1, addr2;
185 | struct sockaddr_in sourceaddr;
186 | socklen_t addrlen = sizeof(sourceaddr);
187 | int fd, fd2;
188 |
189 |
190 |
191 | if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
192 | {
193 | perror("cannot create socket\n");
194 | return 0;
195 | }
196 |
197 |
198 | memset((char *)&addr1, 0, sizeof(addr1));
199 | addr1.sin_family = AF_INET;
200 | addr1.sin_addr.s_addr = inet_addr(sinkip);
201 | addr1.sin_port = htons(1028);
202 |
203 | struct timeval tv;
204 | tv.tv_sec = 10;
205 | if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0)
206 | {
207 | perror("cannot set timeout\n");
208 | return 0;
209 | }
210 |
211 | if (bind(fd, (struct sockaddr *)&addr1, sizeof(addr1)) < 0)
212 | {
213 | perror("bind failed");
214 | return 0;
215 | }
216 |
217 | if (idrsockport > 0)
218 | {
219 | if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
220 | {
221 | perror("cannot create socket\n");
222 | return 0;
223 | }
224 | memset((char *)&addr2, 0, sizeof(addr2));
225 | addr2.sin_family = AF_INET;
226 | addr2.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
227 | addr2.sin_port = htons(idrsockport);
228 | }
229 |
230 |
231 |
232 |
233 |
234 |
235 | while (1)
236 | {
237 | beg->buf = malloc(2048 * sizeof(unsigned char));
238 | beg->recvlen = recvfrom(fd, beg->buf, 2048, 0, (struct sockaddr *)&sourceaddr, &addrlen);
239 | if (beg->recvlen <= 0)
240 | {
241 | free(beg->buf);
242 | free(beg);
243 | continue;
244 | }
245 | beg->seqnum = (beg->buf[2] << 8) + beg->buf[3];
246 | beg->next = NULL;
247 | break;
248 |
249 | }
250 |
251 | rtppacket* head = beg;
252 | rtppacket* oldhead = NULL;
253 |
254 |
255 | int numofpacket = 1;
256 | int osn = 0xFFFF & (beg->seqnum);
257 | int hold = 0;
258 | int sentseqnum = -1;
259 |
260 | while (1)
261 | {
262 | rtppacket* p1 = malloc(sizeof(rtppacket));
263 | p1->buf = malloc(2048 * sizeof(unsigned char));
264 | p1->recvlen = recvfrom(fd, p1->buf, 2048, 0, (struct sockaddr *)&sourceaddr, &addrlen);
265 | if (p1->recvlen == 0)
266 | {
267 | free(p1->buf);
268 | free(p1);
269 | continue;
270 | }else if(p1->recvlen < 0)
271 | {
272 | const char topython[] = "recv timeout";
273 | if (sendto(fd2, topython, sizeof(topython), 0, (struct sockaddr *)&addr2, addrlen) < 0)
274 | perror("recv timeout");
275 | exit(1);
276 | }
277 |
278 | p1->seqnum = (p1->buf[2] << 8) + p1->buf[3];
279 | p1->next = NULL;
280 |
281 | if (largers(sentseqnum, p1->seqnum) && sentseqnum > 0)
282 | {
283 | printf("drop:%d\n", p1->seqnum);
284 | free(p1->buf);
285 | free(p1);
286 | continue;
287 | }
288 |
289 | if (numofpacket == 0)
290 | {
291 | head = p1;
292 | }
293 | else
294 | {
295 | rtppacket* currentp = head;
296 | rtppacket* prevp = NULL;
297 |
298 |
299 | while (currentp != NULL)
300 | {
301 | if (largers(currentp->seqnum, p1->seqnum))
302 | {
303 | if (prevp == NULL)
304 | head = p1;
305 | else
306 | prevp->next = p1;
307 | p1->next = currentp;
308 | break;
309 | }
310 | prevp = currentp;
311 | currentp = currentp->next;
312 | }
313 |
314 |
315 | if (currentp == NULL)//end
316 | {
317 | prevp->next = p1;
318 | }
319 |
320 | }
321 |
322 | numofpacket++;
323 |
324 | if (head->seqnum == osn)
325 | {
326 | hold = 0;
327 |
328 | }
329 | else if (numofpacket > 14)
330 | {
331 | hold = 0;
332 | printf("start:%d, end:%d\n", osn, head->seqnum);
333 |
334 | osn = head->seqnum;
335 | sentseqnum = osn;
336 |
337 | }
338 | else if (idrsockport > 0 && (numofpacket == 12))
339 | {
340 | const char topython[] = "send idr";
341 | if (sendto(fd2, topython, sizeof(topython), 0, (struct sockaddr *)&addr2, addrlen) < 0)
342 | perror("sendto error");
343 | printf("idr:%d\n", numofpacket);
344 | }
345 |
346 |
347 | if (numofpacket > 0 && !hold && osn == head->seqnum && oldhead != NULL)
348 | {
349 | oldhead->next = head;
350 | }
351 |
352 |
353 |
354 | while (numofpacket > 0 && !hold)
355 | {
356 | if (osn != head->seqnum)
357 | {
358 | hold = 1;
359 | break;
360 | }
361 |
362 | sentseqnum = osn;
363 |
364 | osn = 0xFFFF & (osn + 1);
365 | oldhead = head;
366 | head = head->next;
367 | numofpacket--;
368 | atomic_fetch_add(&numofnode, 1);
369 |
370 | }
371 |
372 | }
373 |
374 | }
375 | int audiodest = 0;
376 |
377 | static int video_decode_test(rtppacket* beg)
378 | {
379 | OMX_VIDEO_PARAM_PORTFORMATTYPE format;
380 | OMX_TIME_CONFIG_CLOCKSTATETYPE cstate;
381 | COMPONENT_T *video_decode = NULL, *video_scheduler = NULL, *video_render = NULL, *clock = NULL, *audio_render = NULL;
382 | COMPONENT_T *list[5];
383 | TUNNEL_T tunnel[4];
384 | ILCLIENT_T *client;
385 | int status = 0;
386 |
387 | memset(list, 0, sizeof(list));
388 | memset(tunnel, 0, sizeof(tunnel));
389 |
390 |
391 | if ((client = ilclient_init()) == NULL)
392 | return -3;
393 |
394 | if (OMX_Init() != OMX_ErrorNone)
395 | {
396 | ilclient_destroy(client);
397 | return -4;
398 | }
399 |
400 | // create video_decode
401 | if (ilclient_create_component(client, &video_decode, "video_decode", ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS) != 0)
402 | status = -14;
403 | list[0] = video_decode;
404 |
405 | // create video_render
406 | if (status == 0 && ilclient_create_component(client, &video_render, "video_render", ILCLIENT_DISABLE_ALL_PORTS) != 0)
407 | status = -14;
408 | list[1] = video_render;
409 |
410 | // create clock
411 | if (status == 0 && ilclient_create_component(client, &clock, "clock", ILCLIENT_DISABLE_ALL_PORTS) != 0)
412 | status = -14;
413 | list[2] = clock;
414 |
415 | memset(&cstate, 0, sizeof(cstate));
416 | cstate.nSize = sizeof(cstate);
417 | cstate.nVersion.nVersion = OMX_VERSION;
418 | cstate.eState = OMX_TIME_ClockStateWaitingForStartTime;
419 | cstate.nWaitMask = 1;
420 | if (clock != NULL && OMX_SetParameter(ILC_GET_HANDLE(clock), OMX_IndexConfigTimeClockState, &cstate) != OMX_ErrorNone)
421 | status = -13;
422 |
423 | // create video_scheduler
424 | if (status == 0 && ilclient_create_component(client, &video_scheduler, "video_scheduler", ILCLIENT_DISABLE_ALL_PORTS) != 0)
425 | status = -14;
426 | list[3] = video_scheduler;
427 |
428 | if (audioplay_create(client, &audio_render, list, 4) != 0)
429 | printf("create error\n");
430 |
431 | if (audiodest == 0)
432 | audioplay_set_dest(audio_render, "hdmi");
433 | else if (audiodest == 1)
434 | audioplay_set_dest(audio_render, "local");
435 | else
436 | audioplay_set_dest(audio_render, "alsa");
437 |
438 | set_tunnel(tunnel, video_decode, 131, video_scheduler, 10);
439 | set_tunnel(tunnel + 1, video_scheduler, 11, video_render, 90);
440 | set_tunnel(tunnel + 2, clock, 80, video_scheduler, 12);
441 |
442 | // setup clock tunnel first
443 | if (status == 0 && ilclient_setup_tunnel(tunnel + 2, 0, 0) != 0)
444 | status = -15;
445 | else
446 | ilclient_change_component_state(clock, OMX_StateExecuting);
447 |
448 | if (status == 0)
449 | ilclient_change_component_state(video_decode, OMX_StateIdle);
450 |
451 | memset(&format, 0, sizeof(OMX_VIDEO_PARAM_PORTFORMATTYPE));
452 | format.nSize = sizeof(OMX_VIDEO_PARAM_PORTFORMATTYPE);
453 | format.nVersion.nVersion = OMX_VERSION;
454 | format.nPortIndex = 130;
455 | format.eCompressionFormat = OMX_VIDEO_CodingAVC;
456 |
457 | //OMX_PARAM_PORTDEFINITIONTYPE portParam;
458 | //memset(&portParam, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
459 | //portParam.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
460 | //portParam.nVersion.nVersion = OMX_VERSION;
461 | //if (OMX_GetParameter(ILC_GET_HANDLE(video_decode), OMX_IndexParamPortDefinition, &portParam) == OMX_ErrorNone)
462 | // printf("get error\n");
463 |
464 | //portParam.nPortIndex = 130;
465 | //portParam.nBufferSize = 188;
466 | //if (OMX_SetParameter(ILC_GET_HANDLE(video_decode), OMX_IndexParamPortDefinition, &portParam) == OMX_ErrorNone)
467 | // printf("set error\n");
468 |
469 |
470 | if (status == 0 &&
471 | OMX_SetParameter(ILC_GET_HANDLE(video_decode), OMX_IndexParamVideoPortFormat, &format) == OMX_ErrorNone &&
472 | ilclient_enable_port_buffers(video_decode, 130, NULL, NULL, NULL) == 0
473 | )
474 | {
475 | OMX_BUFFERHEADERTYPE *buf;
476 | int port_settings_changed = 0;
477 |
478 | ilclient_change_component_state(video_decode, OMX_StateExecuting);
479 |
480 |
481 | int oldcc = 0;
482 | int peserror = 1;
483 | int first = 1;
484 | int peslen = -100, actuallen = 0;
485 | unsigned char* oldlen = NULL;
486 |
487 | rtppacket*scan = beg;
488 | while (1)
489 | {
490 | int non = atomic_load(&numofnode);
491 | if (non < 2)
492 | {
493 | usleep(10);
494 | continue;
495 | }
496 | /*else if (non > 10)
497 | {
498 | printf("node:%d\n", non);
499 | }*/
500 |
501 | int numofts = (scan->recvlen - 12) / 188;
502 | for (int i = 0; i < numofts; i++)
503 | {
504 | unsigned char* buffer = scan->buf + 12 + i * 188;
505 |
506 | unsigned char sync = buffer[0];
507 | if (sync == 0x47)
508 | {
509 | int startindicator = buffer[1] & 0x40;
510 | short pid = ((0x1F & buffer[1]) << 8) + buffer[2];
511 |
512 | if (pid == 0x1011)
513 | {
514 | int ad = 3 & (buffer[3] >> 4);
515 | int cc = buffer[3] & 0x0F;
516 | if (cc != oldcc)
517 | {
518 | printf("oldcc %d cc %d\n", oldcc, cc);
519 | oldcc = cc;
520 | peserror = 1;
521 | }
522 | oldcc = 0xF & (oldcc + 1);
523 |
524 |
525 | if (ad & 1)
526 | {
527 | int adlen = buffer[4];
528 | int shift = (ad == 1) ? 4 : adlen + 5;
529 | if (buffer[shift] == 0 && buffer[shift + 1] == 0 && buffer[shift + 2] == 1)/////newpesstart
530 | {
531 | if (peserror == 0)
532 | {
533 |
534 | sendtodecoder(video_decode, video_scheduler, video_render, tunnel,
535 | buf, &beg, scan, &port_settings_changed, &first);
536 |
537 | }
538 | else
539 | {
540 | while (beg != scan)
541 | {
542 | rtppacket* nexttemp = beg->next;
543 | free(beg->buf);
544 | free(beg);
545 | beg = nexttemp;
546 | }
547 | first = 1;
548 | }
549 | peserror = 0;
550 | }
551 | }
552 | }else if (pid == 0x1100)
553 | {
554 | int ad = 3 & (buffer[3] >> 4);
555 |
556 | if (ad & 1)
557 | {
558 | int adlen = buffer[4];
559 | int shift = (ad == 1) ? 4 : adlen + 5;
560 | if (buffer[shift] == 0 && buffer[shift + 1] == 0 && buffer[shift + 2] == 1)/////newpesstart
561 | {
562 | shift += 20;
563 | }
564 |
565 |
566 |
567 | if (audioplay_play_buffer(audio_render, buffer + shift, 188 - shift) < 0)
568 | printf("sound error\n");
569 |
570 |
571 |
572 | }
573 | }
574 |
575 |
576 |
577 |
578 |
579 |
580 |
581 | }
582 |
583 | }
584 | atomic_fetch_sub(&numofnode, 1);
585 | scan = scan->next;
586 | }
587 |
588 | buf->nFilledLen = 0;
589 | buf->nFlags = OMX_BUFFERFLAG_TIME_UNKNOWN | OMX_BUFFERFLAG_EOS;
590 |
591 | if (OMX_EmptyThisBuffer(ILC_GET_HANDLE(video_decode), buf) != OMX_ErrorNone)
592 | status = -20;
593 |
594 | // wait for EOS from render
595 | ilclient_wait_for_event(video_render, OMX_EventBufferFlag, 90, 0, OMX_BUFFERFLAG_EOS, 0,
596 | ILCLIENT_BUFFER_FLAG_EOS, -1);
597 |
598 | // need to flush the renderer to allow video_decode to disable its input port
599 | ilclient_flush_tunnels(tunnel, 0);
600 |
601 | }
602 |
603 |
604 | ilclient_disable_tunnel(tunnel);
605 | ilclient_disable_tunnel(tunnel + 1);
606 | ilclient_disable_tunnel(tunnel + 2);
607 | ilclient_disable_port_buffers(video_decode, 130, NULL, NULL, NULL);
608 | ilclient_teardown_tunnels(tunnel);
609 |
610 | ilclient_state_transition(list, OMX_StateIdle);
611 | ilclient_state_transition(list, OMX_StateLoaded);
612 |
613 | ilclient_cleanup_components(list);
614 |
615 | OMX_Deinit();
616 |
617 | ilclient_destroy(client);
618 | return status;
619 | }
620 |
621 | int main(int argc, char **argv)
622 | {
623 | if (argc > 1)
624 | {
625 | idrsockport = atoi(argv[1]);
626 | printf("idrport:%d\n", idrsockport);
627 | }
628 | if (argc > 2)
629 | {
630 | audiodest = atoi(argv[2]);
631 | printf("audiodest:%d\n", audiodest);
632 | }
633 | if (argc > 3)
634 | {
635 | sinkip = argv[3];
636 | printf("sinkip:%s\n", sinkip);
637 | }
638 |
639 | atomic_store(&numofnode, 0);
640 |
641 | pthread_t npthread;
642 | pthread_t dthread;
643 |
644 | rtppacket* beg = malloc(sizeof(rtppacket));
645 |
646 | bcm_host_init();
647 |
648 | if (pthread_create(&npthread, NULL, addnullpacket, beg) != 0)
649 | exit(1);
650 | if (pthread_create(&dthread, NULL, video_decode_test, beg) != 0)
651 | exit(1);
652 |
653 | if (pthread_join(npthread, NULL) != 0)
654 | exit(1);
655 | if (pthread_join(dthread, NULL) != 0)
656 | exit(1);
657 |
658 | return 0;
659 |
660 | }
661 |
662 |
663 |
--------------------------------------------------------------------------------
/lazycast.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=lazycast server
3 |
4 | [Service]
5 | ExecStart=/home/pi/lazycast/all.sh
6 | WorkingDirectory=/home/pi/lazycast
7 |
8 | [Install]
9 | WantedBy=default.target
10 | WantedBy=lightdm.service
11 |
--------------------------------------------------------------------------------
/logging.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # sudo killall wpa_supplicant; sudo wpa_supplicant -Dnl80211 -iwlan0 -C/var/run/wpa_supplicant/ -c/etc/wpa_supplicant/wpa_supplicant.conf -dd
4 |
5 | cd wpa_supplicant-2.9/wpa_supplicant
6 | make
7 | sudo killall wpa_supplicant
8 | sudo ./wpa_supplicant -Dnl80211 -iwlan0 -C/var/run/wpa_supplicant/ -c/etc/wpa_supplicant/wpa_supplicant.conf -dd
9 |
10 | make; sudo killall wpa_supplicant;sleep 3;sudo ./wpa_supplicant -dd -u -f ~/log.txt -B
11 | sudo killall wpa_supplicant; make; sudo ./wpa_supplicant -dd -u -f ~/log.txt -B; python ~/p2p_group_add.py
12 |
--------------------------------------------------------------------------------
/mice.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #################################################################################
3 | # Run script for lazycast
4 | # Licensed under GNU General Public License v3.0 GPL-3 (in short)
5 | #
6 | # You may copy, distribute and modify the software as long as you track
7 | # changes/dates in source files. Any modifications to our software
8 | # including (via compiler) GPL-licensed code must also be made available
9 | # under the GPL along with build & install instructions.
10 | #
11 | ################################################################################
12 | sudo systemctl stop dhcpcd
13 | sudo systemctl stop wpa_supplicant
14 | sudo wpa_supplicant -Dnl80211 -iwlan0 -u -c/etc/wpa_supplicant/wpa_supplicant.conf &
15 | sleep 1; sudo systemctl start dhcpcd
16 |
17 | LD_LIBRARY_PATH=/opt/vc/lib
18 | export LD_LIBRARY_PATH
19 | ./newmice.py
--------------------------------------------------------------------------------
/newmice.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | This software is part of lazycast, a simple wireless display receiver for Raspberry Pi
4 | Copyright (C) 2020 Hsun-Wei Cho
5 | Modified from the p2p_group_add example of wpa_supplicant
6 | # Tests p2p_group_add
7 | ######### MAY NEED TO RUN AS SUDO #############
8 | Using any part of the code in commercial products is prohibited.
9 | This program is free software: you can redistribute it and/or modify
10 | it under the terms of the GNU General Public License as published by
11 | the Free Software Foundation, either version 3 of the License, or
12 | (at your option) any later version.
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 | You should have received a copy of the GNU General Public License
18 | along with this program. If not, see .
19 | """
20 | import dbus
21 | import sys, os
22 | import time
23 | from gi.repository import GObject as gobject
24 | import threading
25 | import socket
26 | from dbus.mainloop.glib import DBusGMainLoop
27 | from time import sleep
28 | from threading import Event
29 |
30 |
31 |
32 | ##################### Settings #####################
33 | hostname = socket.gethostname()
34 | # hostname = 'raspberrypi'
35 | # If ./mice.py and ./project.py do not run on the same machine,
36 | # hostname and ipstr should be the those of the machine running ./project.py
37 | ipstr = ''
38 | # ipstr = '192.168.1.5'
39 | concurrent = 0
40 | # 0: Accept MICE connection only
41 | # 1: Accept MICE and wifi p2p connections
42 |
43 | event = Event()
44 | ippipe = os.popen('hostname -I')
45 | ipstrs = ippipe.read()
46 | ippipe.close()
47 | ipstrs = ipstrs[:ipstrs.find(' \n')]
48 | ipelems = ipstrs.split(' ')
49 | if len(ipelems)>1 and ipstr == '':
50 | print('Warning:')
51 | print('This machine has multiple IP addresses:')
52 | for ipelem in ipelems:
53 | print(ipelem)
54 | ipstr = ipelems[0]
55 | print('A PC will try to connect to '+ipstr+' directly if mDNS fails')
56 | print('Set the variable "ipstr" in mice.py to another IP manually if '+ipstr+' does not work')
57 |
58 |
59 | def groupStarted(properties):
60 |
61 | print("groupStarted: " + str(properties))
62 | g_obj = dbus.SystemBus().get_object('fi.w1.wpa_supplicant1',properties['group_object'])
63 | res = g_obj.GetAll('fi.w1.wpa_supplicant1.Group', dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
64 | print("Group properties: " + str(res))
65 |
66 | hostnamehex = hostname.encode('utf-8').hex()
67 | hostnamemessage = '2002'+'{:04X}'.format(int(len(hostname)))+hostnamehex
68 |
69 | ipmessage = ''
70 |
71 | if ipstr != '':
72 | # The spec supportes multiple ip attributes. However, Windows will only try the first one
73 | iphex = ipstr.encode('utf-8').hex()
74 | ipmessage = '2005'+'{:04X}'.format(int(len(iphex)/2))+iphex
75 |
76 | capandhostmessage = '0001372001000105' + hostnamemessage + ipmessage
77 |
78 | innerarray = []
79 | print(capandhostmessage)
80 | for c in bytes.fromhex(capandhostmessage):
81 | innerarray.append(dbus.Byte(c))
82 |
83 | g_obj.Set('fi.w1.wpa_supplicant1.Group', 'WPSVendorExtensions',
84 | dbus.Array([dbus.Array(innerarray, signature=dbus.Signature('ay'))], signature=dbus.Signature('ay')),dbus_interface=dbus.PROPERTIES_IFACE)
85 |
86 | g_obj = dbus.SystemBus().get_object('fi.w1.wpa_supplicant1',properties['group_object'])
87 | res = g_obj.GetAll('fi.w1.wpa_supplicant1.Group', dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
88 | print("Group properties: " + str(res))
89 |
90 | event.set()
91 |
92 |
93 |
94 |
95 |
96 | def WpsFailure(status, etc):
97 | print("WPS Authentication Failure".format(status))
98 | print(etc)
99 | os._exit(0)
100 |
101 | class P2P_Group_Add (threading.Thread):
102 | # Needed Variables
103 | global bus
104 | global wpas_object
105 | global interface_object
106 | global interfacep2pdevice
107 | global interface_name
108 | global wpas
109 | global wpas_dbus_interface
110 | global path
111 |
112 | # Dbus Paths
113 | global wpas_dbus_opath
114 | global wpas_dbus_interfaces_opath
115 | global wpas_dbus_interfaces_interface
116 | global wpas_dbus_interfaces_p2pdevice
117 |
118 |
119 | # Constructor
120 | def __init__(self,interface_name,wpas_dbus_interface):
121 | # Initializes variables and threads
122 | self.interface_name = interface_name
123 | self.wpas_dbus_interface = wpas_dbus_interface
124 |
125 |
126 | # Initializes thread and daemon allows for ctrl-c kill
127 | threading.Thread.__init__(self)
128 | self.daemon = True
129 |
130 | # Generating interface/object paths
131 | self.wpas_dbus_opath = "/" + self.wpas_dbus_interface.replace(".","/")
132 | self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + "/Interfaces"
133 | self.wpas_dbus_interfaces_interface = self.wpas_dbus_interface + ".Interface"
134 | self.wpas_dbus_interfaces_p2pdevice = self.wpas_dbus_interfaces_interface + ".P2PDevice"
135 |
136 | # Getting interfaces and objects
137 | DBusGMainLoop(set_as_default=True)
138 | self.bus = dbus.SystemBus()
139 | self.wpas_object = self.bus.get_object(self.wpas_dbus_interface, self.wpas_dbus_opath)
140 | self.wpas = dbus.Interface(self.wpas_object, self.wpas_dbus_interface)
141 |
142 | # Try to see if supplicant knows about interface
143 | # If not, throw an exception
144 | try:
145 | self.path = self.wpas.GetInterface(self.interface_name)
146 | except dbus.DBusException as exc:
147 | error = 'Error:\n Interface ' + self.interface_name + ' was not found'
148 | print(error)
149 | usage()
150 | os._exit(0)
151 |
152 | self.interface_object = self.bus.get_object(self.wpas_dbus_interface, self.path)
153 | self.interfacep2pdevice = dbus.Interface(self.interface_object, self.wpas_dbus_interfaces_p2pdevice)
154 |
155 | self.bus.add_signal_receiver(groupStarted, dbus_interface=self.wpas_dbus_interfaces_p2pdevice,
156 | signal_name="GroupStarted")
157 | self.bus.add_signal_receiver(WpsFailure, dbus_interface=self.wpas_dbus_interfaces_p2pdevice,
158 | signal_name="WpsFailed")
159 |
160 |
161 | def setarguments(self):
162 |
163 | props = self.interface_object.GetAll(self.wpas_dbus_interfaces_p2pdevice,dbus_interface=dbus.PROPERTIES_IFACE)
164 | print(props)
165 | print('')
166 |
167 | dbus.Interface(self.interface_object, dbus_interface=dbus.PROPERTIES_IFACE).Set(self.wpas_dbus_interfaces_p2pdevice, 'P2PDeviceConfig',dbus.Dictionary({ 'DeviceName' : hostname},signature='sv'))
168 |
169 | dbus.Interface(self.interface_object, dbus_interface=dbus.PROPERTIES_IFACE).Set(self.wpas_dbus_interfaces_p2pdevice, 'P2PDeviceConfig',dbus.Dictionary({dbus.String(u'PrimaryDeviceType'): dbus.Array([dbus.Byte(0), dbus.Byte(7), dbus.Byte(0), dbus.Byte(80), dbus.Byte(242), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0)])},signature='sv'))
170 |
171 | dbus.Interface(self.wpas_object, dbus_interface=dbus.PROPERTIES_IFACE).Set('fi.w1.wpa_supplicant1', dbus.String(u'WFDIEs'), dbus.Array([dbus.Byte(0), dbus.Byte(0), dbus.Byte(6), dbus.Byte(1), dbus.Byte(81), dbus.Byte(2), dbus.Byte(42), dbus.Byte(1), dbus.Byte(44), dbus.Byte(1), dbus.Byte(0), dbus.Byte(6), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(6), dbus.Byte(0), dbus.Byte(7), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0)], signature=dbus.Signature('y'), variant_level=1))
172 |
173 | props = self.wpas_object.GetAll('fi.w1.wpa_supplicant1',dbus_interface=dbus.PROPERTIES_IFACE)
174 | print(props)
175 | print('')
176 |
177 | def run(self):
178 |
179 | groupadddict = {'persistent':False}
180 | try:
181 | self.interfacep2pdevice.GroupAdd(groupadddict)
182 | except:
183 | print('Warning:\n Could not preform group add')
184 | print('If existing beacon does not function properly, run ./removep2p.sh first.')
185 | print('Now running ./project.py')
186 | event.set()
187 |
188 | gobject.MainLoop().get_context().iteration(True)
189 | gobject.threads_init()
190 | gobject.MainLoop().run()
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 | if __name__ == "__main__":
199 |
200 | try:
201 | p2p_group_add_test = P2P_Group_Add('wlan0','fi.w1.wpa_supplicant1')
202 | except:
203 | print("Error:\n Invalid Arguements")
204 |
205 | p2p_group_add_test.setarguments()
206 | p2p_group_add_test.start()
207 |
208 |
209 | event.wait()
210 |
211 | if concurrent == 1:
212 | os.system('./all.sh &')
213 |
214 | exec(open('project.py').read())
215 |
216 |
--------------------------------------------------------------------------------
/player/Makefile:
--------------------------------------------------------------------------------
1 | OBJS=player.o
2 | BIN=./player.bin
3 | DMX_INC = -I/opt/vc/include/ -I /opt/vc/include/interface/vmcs_host/ -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux -I/opt/vc/include/interface/vcos/
4 | EGL_INC =
5 | OMX_INC = -I /opt/vc/include/IL
6 | OMX_ILCLIENT_INC = -I/opt/vc/src/hello_pi/libs/ilclient
7 | INCLUDES = $(DMX_INC) $(EGL_INC) $(OMX_INC) $(OMX_ILCLIENT_INC)
8 | CFLAGS+= -DOMX_SKIP64BIT $(INCLUDES)
9 | LDFLAGS+= -lilclient -lavformat -lavcodec -lavutil
10 |
11 | include ./Makefile.include
12 |
13 |
--------------------------------------------------------------------------------
/player/Makefile.include:
--------------------------------------------------------------------------------
1 |
2 | CFLAGS+=-DSTANDALONE -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS -DTARGET_POSIX -D_LINUX -fPIC -DPIC -D_REENTRANT -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -Wall -g -DHAVE_LIBOPENMAX=2 -DOMX -DOMX_SKIP64BIT -ftree-vectorize -pipe -DUSE_EXTERNAL_OMX -DHAVE_LIBBCM_HOST -DUSE_EXTERNAL_LIBBCM_HOST -DUSE_VCHIQ_ARM -Wno-psabi
3 |
4 | LDFLAGS+=-L$(SDKSTAGE)/opt/vc/lib/ -lbrcmGLESv2 -lbrcmEGL -lopenmaxil -lbcm_host -lvcos -lvchiq_arm -lpthread -lrt -lm -L$(SDKSTAGE)/opt/vc/src/hello_pi/libs/ilclient -L$(SDKSTAGE)/opt/vc/src/hello_pi/libs/vgfont
5 |
6 | INCLUDES+=-I$(SDKSTAGE)/opt/vc/include/ -I$(SDKSTAGE)/opt/vc/include/interface/vcos/pthreads -I$(SDKSTAGE)/opt/vc/include/interface/vmcs_host/linux -I./ -I$(SDKSTAGE)/opt/vc/src/hello_pi/libs/ilclient -I$(SDKSTAGE)/opt/vc/src/hello_pi/libs/vgfont
7 |
8 | all: $(BIN) $(LIB)
9 |
10 | %.o: %.c
11 | @rm -f $@
12 | $(CC) $(CFLAGS) $(INCLUDES) -g -c $< -o $@ -Wno-deprecated-declarations
13 |
14 | %.o: %.cpp
15 | @rm -f $@
16 | $(CXX) $(CFLAGS) $(INCLUDES) -g -c $< -o $@ -Wno-deprecated-declarations
17 |
18 | %.bin: $(OBJS)
19 | $(CC) -o $@ -Wl,--whole-archive $(OBJS) $(LDFLAGS) -Wl,--no-whole-archive -rdynamic
20 |
21 | %.a: $(OBJS)
22 | $(AR) r $@ $^
23 |
24 | clean:
25 | for i in $(OBJS); do (if test -e "$$i"; then ( rm $$i ); fi ); done
26 | @rm -f $(BIN) $(LIB)
27 |
28 |
29 |
--------------------------------------------------------------------------------
/player/mtlinklist.c:
--------------------------------------------------------------------------------
1 | // mtlinklist.cpp : Defines the entry point for the console application.
2 | //
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | atomic_int numofnode = 0;
11 |
12 | typedef struct Node
13 | {
14 | int* pbuff;
15 | struct Node* next;
16 | } Nodetype;
17 |
18 | static void * receivepkt(Nodetype* oldnode)
19 | {
20 | for (int i = 0; i < 100; i++)
21 | {
22 | oldnode->pbuff = malloc(sizeof(int));
23 | (*oldnode->pbuff) = i;
24 | oldnode->next = malloc(sizeof(Nodetype));
25 |
26 | Nodetype* pnext = oldnode->next;
27 |
28 | oldnode = pnext;
29 | atomic_fetch_add(&numofnode, 1);
30 | }
31 |
32 |
33 | }
34 |
35 | int main()
36 | {
37 | Nodetype* oldnode = malloc(sizeof(Nodetype));
38 | Nodetype* oldnodecopy = oldnode;
39 |
40 |
41 | pthread_t thread;
42 | if (pthread_create(&thread, NULL, receivepkt, oldnodecopy) != 0)
43 | exit(1);
44 |
45 | while (1)
46 | {
47 | if (numofnode < 2)
48 | {
49 | usleep(10);
50 | continue;
51 | }
52 | printf("%d\n", numofnode);
53 |
54 | printf("%d\n", *(oldnode->pbuff));
55 | free(oldnode->pbuff);
56 | Nodetype* pnext = oldnode->next;
57 | free(oldnode);
58 |
59 | oldnode = pnext;
60 | atomic_fetch_sub(&numofnode, 1);
61 | }
62 |
63 |
64 |
65 |
66 | if (pthread_join(thread, NULL) != 0)
67 | exit(1);
68 |
69 |
70 | free(oldnode);
71 | return 0;
72 | }
73 |
74 |
75 |
--------------------------------------------------------------------------------
/player/player.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 | #include
10 |
11 | #include
12 | #include
13 |
14 | #include
15 | #include
16 |
17 | #define VCOS_LOG_CATEGORY (&il_ffmpeg_log_category)
18 | static VCOS_LOG_CAT_T il_ffmpeg_log_category;
19 |
20 | #include
21 |
22 | #include "libavcodec/avcodec.h"
23 | #include
24 |
25 | //#define insertpacket
26 | #define stoprendering
27 | //#define injecterror
28 |
29 | static AVCodecContext *video_dec_ctx = NULL;
30 | static AVCodecContext *audio_dec_ctx = NULL;
31 | AVCodecContext* codec_context;
32 |
33 |
34 | static AVStream *video_stream = NULL;
35 | static AVStream *audio_stream = NULL;
36 | static AVPacket pkt;
37 | AVFormatContext *pFormatCtx = NULL;
38 |
39 | static int video_stream_idx = -1;
40 | static int audio_stream_idx = -1;
41 |
42 |
43 | uint8_t extradatasize;
44 | void *extradata;
45 |
46 | AVCodec *codec;
47 |
48 | void printState(OMX_HANDLETYPE handle)
49 | {
50 | // elided
51 | }
52 |
53 | char *err2str(int err)
54 | {
55 | return "error";
56 | }
57 |
58 | void printClockState(COMPONENT_T *clockComponent)
59 | {
60 | OMX_ERRORTYPE err = OMX_ErrorNone;
61 | OMX_TIME_CONFIG_CLOCKSTATETYPE clockState;
62 |
63 | memset(&clockState, 0, sizeof( OMX_TIME_CONFIG_CLOCKSTATETYPE));
64 | clockState.nSize = sizeof( OMX_TIME_CONFIG_CLOCKSTATETYPE);
65 | clockState.nVersion.nVersion = OMX_VERSION;
66 |
67 | err = OMX_GetConfig(ilclient_get_handle(clockComponent),
68 | OMX_IndexConfigTimeClockState, &clockState);
69 | if (err != OMX_ErrorNone)
70 | {
71 | fprintf(stderr, "Error getting clock state %s\n", err2str(err));
72 | return;
73 | }
74 | switch (clockState.eState)
75 | {
76 | case OMX_TIME_ClockStateRunning:
77 | printf("Clock running\n");
78 | break;
79 | case OMX_TIME_ClockStateWaitingForStartTime:
80 | printf("Clock waiting for start time\n");
81 | break;
82 | case OMX_TIME_ClockStateStopped:
83 | printf("Clock stopped\n");
84 | break;
85 | default:
86 | printf("Clock in other state\n");
87 | }
88 | }
89 |
90 | void startClock(COMPONENT_T *clockComponent)
91 | {
92 | OMX_ERRORTYPE err = OMX_ErrorNone;
93 | OMX_TIME_CONFIG_CLOCKSTATETYPE clockState;
94 |
95 | memset(&clockState, 0, sizeof( OMX_TIME_CONFIG_CLOCKSTATETYPE));
96 | clockState.nSize = sizeof( OMX_TIME_CONFIG_CLOCKSTATETYPE);
97 | clockState.nVersion.nVersion = OMX_VERSION;
98 |
99 | err = OMX_GetConfig(ilclient_get_handle(clockComponent), OMX_IndexConfigTimeClockState, &clockState);
100 | if (err != OMX_ErrorNone)
101 | {
102 | fprintf(stderr, "Error getting clock state %s\n", err2str(err));
103 | return;
104 | }
105 | clockState.eState = OMX_TIME_ClockStateRunning;
106 | err = OMX_SetConfig(ilclient_get_handle(clockComponent),
107 | OMX_IndexConfigTimeClockState, &clockState);
108 | if (err != OMX_ErrorNone)
109 | {
110 | fprintf(stderr, "Error starting clock %s\n", err2str(err));
111 | return;
112 | }
113 |
114 | }
115 |
116 | void eos_callback(void *userdata, COMPONENT_T *comp, OMX_U32 data)
117 | {
118 | printf("Got eos event\n");
119 | }
120 |
121 | void error_callback(void *userdata, COMPONENT_T *comp, OMX_U32 data)
122 | {
123 | printf("OMX error %s\n", err2str(data));
124 | }
125 |
126 | void port_settings_callback(void *userdata, COMPONENT_T *comp, OMX_U32 data)
127 | {
128 | printf("Got port Settings event\n");
129 | // exit(0);
130 | }
131 |
132 | void empty_buffer_done_callback(void *userdata, COMPONENT_T *comp)
133 | {
134 | //printf("Got empty buffer done\n");
135 | }
136 |
137 |
138 | unsigned int uWidth;
139 | unsigned int uHeight;
140 |
141 | unsigned int fpsscale;
142 | unsigned int fpsrate;
143 | unsigned int time_base_num;
144 | unsigned int time_base_den;
145 |
146 | #ifdef OMX_SKIP64BIT
147 | OMX_TICKS ToOMXTime(int64_t pts)
148 | {
149 | OMX_TICKS ticks;
150 | ticks.nLowPart = pts;
151 | ticks.nHighPart = pts >> 32;
152 | return ticks;
153 | }
154 | #else
155 | #define FromOMXTime(x) (x)
156 | #endif
157 |
158 | static long int startpts;
159 |
160 | atomic_int numofnode;
161 | atomic_int stoprender;
162 |
163 | OMX_ERRORTYPE copy_into_buffer_and_empty(AVPacket *pkt,COMPONENT_T *component)
164 | {
165 | OMX_ERRORTYPE r;
166 |
167 | #ifdef stoprendering
168 | if (atomic_load(&numofnode) > 10 && !(pkt->flags & AV_PKT_FLAG_KEY))
169 | return r;
170 | if (atomic_load(&stoprender) && (pkt->flags & AV_PKT_FLAG_KEY))
171 | {
172 | printf("keyframe\n");
173 | atomic_store(&stoprender, 0);
174 | return r;
175 | }
176 |
177 | #endif
178 |
179 | int size = pkt->size;
180 | uint8_t *content = pkt->data;
181 |
182 |
183 |
184 | //if (atomic_load(&stoprender))
185 | //{
186 | // int idrindex = -1;
187 | // if (pkt->flags & AV_PKT_FLAG_KEY)
188 | // {
189 | // atomic_store(&stoprender, 0);
190 | // for (int i = 0; i < pkt->size - 4; i++)
191 | // {
192 | // if (content[i] == 0 && content[i + 1] == 0 && content[i + 2] == 1)
193 | // {
194 | // printf("type %x", content[i + 3]);
195 | // if ((content[i + 3] & 0x1F) == 5)
196 | // idrindex = i;
197 | // printf("index %d\n", idrindex);
198 |
199 | // }
200 |
201 | // }
202 | // }
203 |
204 | // if (idrindex == -1)
205 | // return r;
206 |
207 | // size -= idrindex;
208 | // content += idrindex;
209 |
210 | //}
211 |
212 |
213 |
214 |
215 |
216 | /////RETURN HERE
217 | OMX_BUFFERHEADERTYPE *buff_header = ilclient_get_input_buffer(component, 130, 1 /* block */);
218 | if (buff_header == NULL)
219 | return r;
220 |
221 | int buff_size = buff_header->nAllocLen;
222 |
223 | while (size > 0)
224 | {
225 | buff_header->nFilledLen = (size > buff_header->nAllocLen-1) ? buff_header->nAllocLen-1 : size;
226 | memset(buff_header->pBuffer, 0x0, buff_header->nAllocLen);
227 | memcpy(buff_header->pBuffer, content, buff_header->nFilledLen);
228 | size -= buff_header->nFilledLen;
229 | content += buff_header->nFilledLen;
230 |
231 |
232 | buff_header->nFlags = 0;
233 | if (size <= 0)
234 | buff_header->nFlags |= OMX_BUFFERFLAG_ENDOFFRAME;
235 |
236 |
237 | if (pkt->flags & AV_PKT_FLAG_KEY)
238 | {
239 | startpts = pkt->pts;
240 | buff_header->nFlags |= OMX_BUFFERFLAG_STARTTIME;
241 | }
242 | else
243 | {
244 | long int rpts = pkt->pts - startpts;
245 | buff_header->nTimeStamp = ToOMXTime((uint64_t)(rpts * 1000000 / time_base_den));
246 | //printf("rpts:%d\n", rpts);
247 | }
248 |
249 |
250 |
251 | r = OMX_EmptyThisBuffer(ilclient_get_handle(component), buff_header);
252 | /*
253 | if (r != OMX_ErrorNone)
254 | {
255 | fprintf(stderr, "Empty buffer error %s\n",err2str(r));
256 | } else
257 | {
258 | printf("Emptying buffer %p\n", buff_header);
259 | }
260 | */
261 |
262 |
263 | if (size > 0)
264 | {
265 | buff_header = ilclient_get_input_buffer(component, 130, 1 /* block */);
266 | }
267 | }
268 | return r;
269 | }
270 |
271 | int img_width, img_height;
272 |
273 | int SendDecoderConfig(COMPONENT_T *component)
274 | {
275 | OMX_ERRORTYPE omx_err = OMX_ErrorNone;
276 |
277 | /* send decoder config */
278 | if(extradatasize > 0 && extradata != NULL)
279 | {
280 |
281 | OMX_BUFFERHEADERTYPE *omx_buffer = ilclient_get_input_buffer(component,130, 1 /* block */);
282 |
283 | if(omx_buffer == NULL)
284 | {
285 | fprintf(stderr, "%s - buffer error 0x%08x", __func__, omx_err);
286 | return 0;
287 | }
288 |
289 | omx_buffer->nOffset = 0;
290 | omx_buffer->nFilledLen = extradatasize;
291 | if(omx_buffer->nFilledLen > omx_buffer->nAllocLen)
292 | {
293 | fprintf(stderr, "%s - omx_buffer->nFilledLen > omx_buffer->nAllocLen", __func__);
294 | return 0;
295 | }
296 |
297 | memset((unsigned char *)omx_buffer->pBuffer, 0x0, omx_buffer->nAllocLen);
298 | memcpy((unsigned char *)omx_buffer->pBuffer, extradata, omx_buffer->nFilledLen);
299 | omx_buffer->nFlags = OMX_BUFFERFLAG_CODECCONFIG | OMX_BUFFERFLAG_ENDOFFRAME;
300 |
301 | omx_err = OMX_EmptyThisBuffer(ilclient_get_handle(component), omx_buffer);
302 | if (omx_err != OMX_ErrorNone)
303 | {
304 | fprintf(stderr, "%s - OMX_EmptyThisBuffer() failed with result(0x%x)\n", __func__, omx_err);
305 | return 0;
306 | } else
307 | {
308 | printf("Config sent, emptying buffer %d\n", extradatasize);
309 | }
310 | }
311 | return 1;
312 | }
313 |
314 | OMX_ERRORTYPE set_video_decoder_input_format(COMPONENT_T *component)
315 | {
316 | int err;
317 |
318 | // set input video format
319 | printf("Setting video decoder format\n");
320 | OMX_VIDEO_PARAM_PORTFORMATTYPE videoPortFormat;
321 |
322 | memset(&videoPortFormat, 0, sizeof(OMX_VIDEO_PARAM_PORTFORMATTYPE));
323 | videoPortFormat.nSize = sizeof(OMX_VIDEO_PARAM_PORTFORMATTYPE);
324 | videoPortFormat.nVersion.nVersion = OMX_VERSION;
325 | videoPortFormat.nPortIndex = 130;
326 |
327 | err = OMX_GetParameter(ilclient_get_handle(component),
328 | OMX_IndexParamVideoPortFormat, &videoPortFormat);
329 | if (err != OMX_ErrorNone)
330 | {
331 | fprintf(stderr, "Error getting video decoder format %s\n", err2str(err));
332 | return err;
333 | }
334 |
335 | videoPortFormat.nPortIndex = 130;
336 | videoPortFormat.nIndex = 0;
337 | videoPortFormat.eCompressionFormat = OMX_VIDEO_CodingAVC;
338 | videoPortFormat.eColorFormat = OMX_COLOR_FormatUnused;
339 | videoPortFormat.xFramerate = 0;
340 |
341 | // doesn't seem to make any difference!!!
342 | videoPortFormat.xFramerate = (long long)(1<<16)*fpsrate / fpsscale;
343 | printf("FPS num %d den %d\n", fpsrate, fpsscale);
344 | printf("Set frame rate to %d\n", videoPortFormat.xFramerate);
345 | //
346 | err = OMX_SetParameter(ilclient_get_handle(component), OMX_IndexParamVideoPortFormat, &videoPortFormat);
347 | if (err != OMX_ErrorNone)
348 | {
349 | fprintf(stderr, "Error setting video decoder format %s\n", err2str(err));
350 | return err;
351 | } else
352 | {
353 | printf("Video decoder format set up ok\n");
354 | }
355 |
356 | OMX_PARAM_PORTDEFINITIONTYPE portParam;
357 | memset(&portParam, 0, sizeof( OMX_PARAM_PORTDEFINITIONTYPE));
358 | portParam.nSize = sizeof( OMX_PARAM_PORTDEFINITIONTYPE);
359 | portParam.nVersion.nVersion = OMX_VERSION;
360 |
361 | portParam.nPortIndex = 130;
362 |
363 | err = OMX_GetParameter(ilclient_get_handle(component), OMX_IndexParamPortDefinition, &portParam);
364 | if(err != OMX_ErrorNone)
365 | {
366 | fprintf(stderr, "COMXVideo::Open error OMX_IndexParamPortDefinition omx_err(0x%08x)\n", err);
367 | return err;
368 | }
369 |
370 | printf("Default framerate %d\n", portParam.format.video.xFramerate);
371 |
372 | portParam.nPortIndex = 130;
373 | portParam.nBufferSize = 163840*2;
374 | portParam.format.video.nFrameWidth = img_width;
375 | portParam.format.video.nFrameHeight = img_height;
376 |
377 | err = OMX_SetParameter(ilclient_get_handle(component), OMX_IndexParamPortDefinition, &portParam);
378 | if(err != OMX_ErrorNone)
379 | {
380 | fprintf(stderr, "COMXVideo::Open error OMX_IndexParamPortDefinition omx_err(0x%08x)\n", err);
381 | return err;
382 | }
383 |
384 | OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE errconceal;
385 | memset(&errconceal, 0, sizeof(OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE));
386 | errconceal.nSize = sizeof(OMX_PARAM_BRCMVIDEODECODEERRORCONCEALMENTTYPE);
387 | errconceal.nVersion.nVersion = OMX_VERSION;
388 | errconceal.bStartWithValidFrame = OMX_FALSE;
389 |
390 |
391 | err = OMX_SetParameter(ilclient_get_handle(component), OMX_IndexParamBrcmVideoDecodeErrorConcealment, &errconceal);
392 | if (err != OMX_ErrorNone)
393 | {
394 | fprintf(stderr, "error concealment error(0x%08x)\n", err);
395 | return err;
396 | }
397 | printf("no error in setting!\n");
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 | return OMX_ErrorNone;
407 | }
408 |
409 | int setup_demuxer(const char *filename) {
410 | // Register all formats and codecs
411 | av_register_all();
412 | if(avformat_open_input(&pFormatCtx, filename, NULL, NULL)!=0) {
413 | fprintf(stderr, "Can't get format\n");
414 | return -1; // Couldn't open file
415 | }
416 | // Retrieve stream information
417 | if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
418 | return -1; // Couldn't find stream information
419 | }
420 | printf("Format:\n");
421 | av_dump_format(pFormatCtx, 0, filename, 0);
422 |
423 | int ret;
424 | ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
425 | if (ret >= 0)
426 | {
427 | video_stream_idx = ret;
428 |
429 | video_stream = pFormatCtx->streams[video_stream_idx];
430 | video_dec_ctx = video_stream->codec;
431 |
432 | img_width = video_stream->codec->width;
433 | img_height = video_stream->codec->height;
434 | extradata = video_stream->codec->extradata;
435 | extradatasize = video_stream->codec->extradata_size;
436 | fpsscale = video_stream->r_frame_rate.den;
437 | fpsrate = video_stream->r_frame_rate.num;
438 | time_base_num = video_stream->time_base.num;
439 | time_base_den = video_stream->time_base.den;
440 |
441 | printf("Rate %d scale %d time base %d %d\n",
442 | video_stream->r_frame_rate.num,
443 | video_stream->r_frame_rate.den,
444 | video_stream->time_base.num,
445 | video_stream->time_base.den);
446 |
447 | AVCodec *codec = avcodec_find_decoder(video_stream->codec->codec_id);
448 |
449 | if (codec)
450 | {
451 | printf("Codec name %s\n", codec->name);
452 | }
453 | }
454 | ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
455 | if (ret >= 0)
456 | {
457 | audio_stream_idx = ret;
458 |
459 | audio_stream = pFormatCtx->streams[audio_stream_idx];
460 | audio_dec_ctx = audio_stream->codec;
461 |
462 |
463 | AVCodec *codec = avcodec_find_decoder(audio_stream->codec->codec_id);
464 | codec_context = avcodec_alloc_context3(codec);
465 | if (codec)
466 | {
467 | printf("Codec name %s\n", codec->name);
468 | }
469 |
470 | if (!avcodec_open2(codec_context, codec, NULL) < 0)
471 | {
472 | fprintf(stderr, "Could not find open the needed codec");
473 | exit(1);
474 | }
475 | }
476 | else
477 | {
478 | audio_stream_idx = 1;
479 |
480 | audio_stream = pFormatCtx->streams[audio_stream_idx];
481 | audio_dec_ctx = audio_stream->codec;
482 |
483 |
484 | AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_AAC);
485 | codec_context = avcodec_alloc_context3(codec);
486 | if (codec)
487 | {
488 | printf("Codec name %s\n", codec->name);
489 | }
490 |
491 | if (!avcodec_open2(codec_context, codec, NULL) < 0)
492 | {
493 | fprintf(stderr, "Could not find open the needed codec");
494 | exit(1);
495 | }
496 | }
497 |
498 |
499 |
500 |
501 | return 0;
502 | }
503 |
504 | void setup_decodeComponent(ILCLIENT_T *handle, char *decodeComponentName, COMPONENT_T **decodeComponent)
505 | {
506 | int err;
507 |
508 | err = ilclient_create_component(handle,
509 | decodeComponent,
510 | decodeComponentName,
511 | ILCLIENT_DISABLE_ALL_PORTS
512 | |
513 | ILCLIENT_ENABLE_INPUT_BUFFERS
514 | |
515 | ILCLIENT_ENABLE_OUTPUT_BUFFERS
516 | );
517 | if (err == -1)
518 | {
519 | fprintf(stderr, "DecodeComponent create failed\n");
520 | exit(1);
521 | }
522 | printState(ilclient_get_handle(*decodeComponent));
523 |
524 | err = ilclient_change_component_state(*decodeComponent, OMX_StateIdle);
525 | if (err < 0)
526 | {
527 | fprintf(stderr, "Couldn't change state to Idle\n");
528 | exit(1);
529 | }
530 | printState(ilclient_get_handle(*decodeComponent));
531 |
532 | // must be before we enable buffers
533 | set_video_decoder_input_format(*decodeComponent);
534 | }
535 |
536 | void setup_renderComponent(ILCLIENT_T *handle,char *renderComponentName, COMPONENT_T **renderComponent)
537 | {
538 | int err;
539 |
540 | err = ilclient_create_component(handle, renderComponent, renderComponentName,
541 | ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS);
542 | if (err == -1)
543 | {
544 | fprintf(stderr, "RenderComponent create failed\n");
545 | exit(1);
546 | }
547 | printState(ilclient_get_handle(*renderComponent));
548 |
549 | err = ilclient_change_component_state(*renderComponent, OMX_StateIdle);
550 | if (err < 0)
551 | {
552 | fprintf(stderr, "Couldn't change state to Idle\n");
553 | exit(1);
554 | }
555 | printState(ilclient_get_handle(*renderComponent));
556 | }
557 |
558 | void setup_schedulerComponent(ILCLIENT_T *handle,char *schedulerComponentName, COMPONENT_T **schedulerComponent)
559 | {
560 | int err;
561 |
562 | err = ilclient_create_component(handle, schedulerComponent,schedulerComponentName,
563 | ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS);
564 | if (err == -1)
565 | {
566 | fprintf(stderr, "SchedulerComponent create failed\n");
567 | exit(1);
568 | }
569 | printState(ilclient_get_handle(*schedulerComponent));
570 |
571 | err = ilclient_change_component_state(*schedulerComponent, OMX_StateIdle);
572 | if (err < 0)
573 | {
574 | fprintf(stderr, "Couldn't change state to Idle\n");
575 | exit(1);
576 | }
577 | printState(ilclient_get_handle(*schedulerComponent));
578 | }
579 |
580 | void setup_clockComponent(ILCLIENT_T *handle, char *clockComponentName,COMPONENT_T **clockComponent)
581 | {
582 | int err;
583 |
584 | err = ilclient_create_component(handle, clockComponent,clockComponentName,
585 | ILCLIENT_DISABLE_ALL_PORTS);
586 | if (err == -1)
587 | {
588 | fprintf(stderr, "ClockComponent create failed\n");
589 | exit(1);
590 | }
591 | printState(ilclient_get_handle(*clockComponent));
592 |
593 | err = ilclient_change_component_state(*clockComponent, OMX_StateIdle);
594 | if (err < 0)
595 | {
596 | fprintf(stderr, "Couldn't change state to Idle\n");
597 | exit(1);
598 | }
599 | printState(ilclient_get_handle(*clockComponent));
600 | printClockState(*clockComponent);
601 |
602 | OMX_COMPONENTTYPE*clock = ilclient_get_handle(*clockComponent);
603 |
604 | OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE refClock;
605 | refClock.nSize = sizeof(OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE);
606 | refClock.nVersion.nVersion = OMX_VERSION;
607 | refClock.eClock = OMX_TIME_RefClockVideo; // OMX_CLOCKPORT0;
608 |
609 | err = OMX_SetConfig(ilclient_get_handle(*clockComponent), OMX_IndexConfigTimeActiveRefClock, &refClock);
610 | if(err != OMX_ErrorNone)
611 | {
612 | fprintf(stderr, "COMXCoreComponent::SetConfig - %s failed with omx_err(0x%x)\n", "clock", err);
613 | }
614 |
615 | OMX_TIME_CONFIG_SCALETYPE scaleType;
616 | scaleType.nSize = sizeof(OMX_TIME_CONFIG_SCALETYPE);
617 | scaleType.nVersion.nVersion = OMX_VERSION;
618 | scaleType.xScale = 0x00010000;
619 |
620 | err = OMX_SetConfig(ilclient_get_handle(*clockComponent),
621 | OMX_IndexConfigTimeScale, &scaleType);
622 | if(err != OMX_ErrorNone)
623 | {
624 | fprintf(stderr, "COMXCoreComponent::SetConfig - %s failed with omx_err(0x%x)\n", "clock", err);
625 | }
626 | }
627 |
628 | static void set_audio_render_input_format(COMPONENT_T *component)
629 | {
630 | // set input audio format
631 | printf("Setting audio render format\n");
632 | OMX_AUDIO_PARAM_PORTFORMATTYPE audioPortFormat;
633 | memset(&audioPortFormat, 0, sizeof(OMX_AUDIO_PARAM_PORTFORMATTYPE));
634 | audioPortFormat.nSize = sizeof(OMX_AUDIO_PARAM_PORTFORMATTYPE);
635 | audioPortFormat.nVersion.nVersion = OMX_VERSION;
636 | audioPortFormat.nPortIndex = 100;
637 | OMX_GetParameter(ilclient_get_handle(component), OMX_IndexParamAudioPortFormat, &audioPortFormat);
638 | audioPortFormat.eEncoding = OMX_AUDIO_CodingPCM;
639 | OMX_SetParameter(ilclient_get_handle(component), OMX_IndexParamAudioPortFormat, &audioPortFormat);
640 |
641 | OMX_AUDIO_PARAM_PCMMODETYPE sPCMMode;
642 | OMX_ERRORTYPE err;
643 | memset(&sPCMMode, 0, sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
644 | sPCMMode.nSize = sizeof(OMX_AUDIO_PARAM_PCMMODETYPE);
645 | sPCMMode.nVersion.nVersion = OMX_VERSION;
646 | sPCMMode.nPortIndex = 100;
647 | err = OMX_GetParameter(ilclient_get_handle(component), OMX_IndexParamAudioPcm, &sPCMMode);
648 |
649 | sPCMMode.nSamplingRate = 48000; // for anything
650 | sPCMMode.nChannels = 2;
651 | err = OMX_SetParameter(ilclient_get_handle(component), OMX_IndexParamAudioPcm, &sPCMMode);
652 | if (err != OMX_ErrorNone)
653 | {
654 | fprintf(stderr, "PCM mode unsupported\n");
655 | return;
656 | }
657 |
658 |
659 |
660 | }
661 |
662 | void setOutputDevice(OMX_HANDLETYPE handle, const char *name)
663 | {
664 | OMX_ERRORTYPE err;
665 | OMX_CONFIG_BRCMAUDIODESTINATIONTYPE arDest;
666 |
667 | if (name && strlen(name) < sizeof(arDest.sName))
668 | {
669 | memset(&arDest, 0, sizeof(OMX_CONFIG_BRCMAUDIODESTINATIONTYPE));
670 | arDest.nSize = sizeof(OMX_CONFIG_BRCMAUDIODESTINATIONTYPE);
671 | arDest.nVersion.nVersion = OMX_VERSION;
672 |
673 | strcpy((char *)arDest.sName, name);
674 |
675 | err = OMX_SetParameter(handle, OMX_IndexConfigBrcmAudioDestination, &arDest);
676 | if (err != OMX_ErrorNone)
677 | {
678 | fprintf(stderr, "Error on setting audio destination\n");
679 | exit(1);
680 | }
681 | }
682 | }
683 |
684 | void setup_audio_renderComponent(ILCLIENT_T *handle, char *componentName, COMPONENT_T **component, int dest)
685 | {
686 | int err;
687 | err = ilclient_create_component(handle, component, componentName,
688 | ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS);
689 | if (err == -1)
690 | {
691 | fprintf(stderr, "Component create failed\n");
692 | exit(1);
693 | }
694 | printState(ilclient_get_handle(*component));
695 |
696 | err = ilclient_change_component_state(*component, OMX_StateIdle);
697 | if (err < 0)
698 | {
699 | fprintf(stderr, "Couldn't change state to Idle\n");
700 | exit(1);
701 | }
702 | printState(ilclient_get_handle(*component));
703 |
704 | // must be before we enable buffers
705 | set_audio_render_input_format(*component);
706 |
707 | if (dest == 1)
708 | setOutputDevice(ilclient_get_handle(*component), "local");
709 | else
710 | setOutputDevice(ilclient_get_handle(*component), "hdmi");
711 |
712 |
713 | // input port
714 | ilclient_enable_port_buffers(*component, 100, NULL, NULL, NULL);
715 | ilclient_enable_port(*component, 100);
716 |
717 | err = ilclient_change_component_state(*component, OMX_StateExecuting);
718 | if (err < 0)
719 | {
720 | fprintf(stderr, "Couldn't change state to Executing\n");
721 | exit(1);
722 | }
723 | printState(ilclient_get_handle(*component));
724 | }
725 |
726 | uint32_t audioplay_get_latency(COMPONENT_T *component)
727 | {
728 | OMX_PARAM_U32TYPE param;
729 | OMX_ERRORTYPE error;
730 |
731 | memset(¶m, 0, sizeof(OMX_PARAM_U32TYPE));
732 | param.nSize = sizeof(OMX_PARAM_U32TYPE);
733 | param.nVersion.nVersion = OMX_VERSION;
734 | param.nPortIndex = 100;
735 |
736 | error = OMX_GetConfig(ilclient_get_handle(component), OMX_IndexConfigAudioRenderingLatency, ¶m);
737 |
738 | return param.nU32;
739 | }
740 | int latmax = 3000;
741 | OMX_ERRORTYPE read_audio_into_buffer_and_empty(AVFrame *decoded_frame, COMPONENT_T *component) // OMX_BUFFERHEADERTYPE *buff_header
742 | {
743 | uint32_t latency = audioplay_get_latency(component);
744 | //printf("%d\n", latency);
745 |
746 | if (latency > latmax)
747 | {
748 | //printf("drop, %d\n", latency);
749 | return 0;
750 | }
751 | else if (latency<1000)
752 | {
753 | latmax = 9600;
754 | }
755 |
756 | if (latmax > 6000)
757 | latmax -= 20;
758 |
759 | OMX_ERRORTYPE r;
760 | OMX_BUFFERHEADERTYPE *buff_header = NULL;
761 |
762 |
763 | int16_t sbuffer[2 * 1024];
764 |
765 | float* fbuffer1 = (float*)(decoded_frame->extended_data[0]);
766 | float* fbuffer2 = (float*)(decoded_frame->extended_data[1]);
767 | int j = 0;
768 | for (int i = 0; i < 1024; i++)
769 | {
770 | sbuffer[j++] = (short)(fbuffer1[i] * 32767.0f);
771 | sbuffer[j++] = (short)(fbuffer2[i] * 32767.0f);
772 | }
773 |
774 |
775 |
776 | buff_header = ilclient_get_input_buffer(component, 100, 1);
777 |
778 | memcpy(buff_header->pBuffer, sbuffer, 4096);
779 | buff_header->nFilledLen = 4096;
780 |
781 | r = OMX_EmptyThisBuffer(ilclient_get_handle(component), buff_header);
782 |
783 |
784 | return r;
785 | }
786 |
787 |
788 |
789 |
790 | typedef struct Node
791 | {
792 | AVPacket* pbuff;
793 | struct Node* next;
794 | } Nodetype;
795 |
796 |
797 | static void* receivepkt(Nodetype* oldnode)
798 | {
799 | while(1)
800 | {
801 | if (av_read_frame(pFormatCtx, &pkt) < 0)
802 | continue;
803 | if (atomic_load(&numofnode) < 0)
804 | {
805 | printf("terminate\n");
806 | break;
807 | }
808 |
809 | oldnode->pbuff = malloc(sizeof(AVPacket));
810 |
811 |
812 | (*oldnode->pbuff) = pkt;
813 | oldnode->next = malloc(sizeof(Nodetype));
814 |
815 | Nodetype* pnext = oldnode->next;
816 | pnext->next = NULL;
817 |
818 | oldnode = pnext;
819 | atomic_fetch_add(&numofnode, 1);
820 | }
821 |
822 |
823 | }
824 |
825 | int largers(int a, int b)
826 | {
827 | if (abs(a - b) < 32768)
828 | return a > b;
829 | else if (a - b <= -32768)
830 | return 1;
831 | else
832 | return 0;
833 | }
834 |
835 |
836 | int idrsockport = -1;
837 | char* sourceip;
838 | static void* addnullpacket()
839 | {
840 | struct sockaddr_in addr1, addr2, addr3;
841 | struct sockaddr_in sourceaddr;
842 | socklen_t addrlen = sizeof(sourceaddr);
843 | int fd, fd2, fd3;
844 |
845 |
846 |
847 | if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
848 | {
849 | perror("cannot create socket\n");
850 | return 0;
851 | }
852 | if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
853 | {
854 | perror("cannot create socket 2\n");
855 | return 0;
856 | }
857 | if ((fd3 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
858 | {
859 | perror("cannot create socket 2\n");
860 | return 0;
861 | }
862 |
863 | memset((char *)&addr1, 0, sizeof(addr1));
864 | addr1.sin_family = AF_INET;
865 | addr1.sin_addr.s_addr = inet_addr(sourceip);
866 | addr1.sin_port = htons(1028);
867 |
868 | memset((char *)&addr2, 0, sizeof(addr2));
869 | addr2.sin_family = AF_INET;
870 | addr2.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
871 | addr2.sin_port = htons(57823);
872 |
873 | memset((char *)&addr3, 0, sizeof(addr3));
874 | addr3.sin_family = AF_INET;
875 | addr3.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
876 | addr3.sin_port = htons(idrsockport);
877 |
878 | if (bind(fd, (struct sockaddr *)&addr1, sizeof(addr1)) < 0)
879 | {
880 | perror("bind failed");
881 | return 0;
882 | }
883 |
884 |
885 |
886 |
887 | typedef struct srtppacket
888 | {
889 | unsigned char* buf;
890 | int recvlen;
891 | int seqnum;
892 | struct srtppacket* next;
893 | } rtppacket;
894 |
895 |
896 | rtppacket* head = NULL;
897 | int numofpacket = 0;
898 | int osn = -1;
899 | int hold = 0;
900 | int sentseqnum = -1;
901 | atomic_store(&stoprender, 0);
902 |
903 | ////error injection
904 | int err = 1000;
905 |
906 | ////
907 |
908 | unsigned char padpacket[2048];
909 | padpacket[0] = 0x80;
910 | padpacket[1] = 0x21;
911 | for (int i = 12; i < 2048; i++)
912 | padpacket[i] = 0xFF;
913 |
914 | while (1)
915 | {
916 | rtppacket* p1= malloc(sizeof(rtppacket));
917 | p1->buf = malloc(2048 * sizeof(unsigned char));
918 | p1->recvlen = recvfrom(fd, p1->buf, 2048, 0, (struct sockaddr *)&sourceaddr, &addrlen);
919 | if (p1->recvlen <= 0)
920 | {
921 | free(p1->buf);
922 | free(p1);
923 | continue;
924 | }
925 | #ifdef injecterror
926 | if (err-- <= 0)
927 | {
928 | err = 5000;
929 | free(p1->buf);
930 | free(p1);
931 | continue;
932 | }
933 | #endif
934 |
935 | p1->seqnum = (p1->buf[2] << 8) + p1->buf[3];
936 | p1->next = NULL;
937 |
938 | if (largers(sentseqnum, p1->seqnum) && sentseqnum > 0)
939 | {
940 | printf("drop:%d\n", p1->seqnum);
941 | free(p1->buf);
942 | free(p1);
943 | continue;
944 | }
945 |
946 | if (numofpacket == 0)
947 | {
948 | head = p1;
949 | }
950 | else
951 | {
952 | rtppacket* currentp = head;
953 | rtppacket* prevp = NULL;
954 |
955 |
956 | while (currentp != NULL)
957 | {
958 | //printf("%d,", currentp->seqnum);
959 |
960 | if (largers(currentp->seqnum, p1->seqnum))
961 | {
962 | if (prevp == NULL)
963 | head = p1;
964 | else
965 | prevp->next = p1;
966 | p1->next = currentp;
967 | //printf("%d,", p1->seqnum);
968 |
969 | break;
970 | }
971 | prevp = currentp;
972 | currentp = currentp->next;
973 | }
974 |
975 |
976 | if (currentp == NULL)//end
977 | {
978 | prevp->next = p1;
979 | }
980 |
981 | }
982 |
983 | numofpacket++;
984 |
985 | if (head->seqnum == osn)
986 | {
987 | hold = 0;
988 |
989 | }else if (numofpacket > 16)
990 | {
991 | hold = 0;
992 | printf("start:%d, end:%d\n",osn,head->seqnum);
993 |
994 | #ifdef insertpacket
995 | while (osn != head->seqnum)
996 | {
997 | padpacket[2] = 0xFF & (osn >> 8);
998 | padpacket[3] = 0xFF & (osn);
999 | for (int i = 4; i < 12; i++)
1000 | padpacket[i] = head->buf[i];
1001 |
1002 |
1003 | if (sendto(fd2, padpacket, 12, 0, (struct sockaddr *)&addr2, addrlen) < 0)
1004 | perror("sendto error");
1005 | osn = 0xFFFF & (osn + 1);
1006 | }
1007 | #else
1008 | osn = head->seqnum;
1009 | #endif
1010 | sentseqnum = osn;
1011 | atomic_store(&stoprender, 1);
1012 |
1013 | }
1014 | else if (idrsockport > 0 && (numofpacket == 12 || numofpacket == 14 || numofpacket == 16))
1015 | {
1016 | unsigned char topython[12];
1017 | if (sendto(fd3, topython, 12, 0, (struct sockaddr *)&addr3, addrlen) < 0)
1018 | perror("sendto error");
1019 | printf("idr:%d\n", numofpacket);
1020 | }
1021 |
1022 | //printf("\n");
1023 | while (numofpacket > 0 && !hold)
1024 | {
1025 | if (osn != head->seqnum)
1026 | {
1027 | //printf("osn:%d, hsn:%d\n", osn,head->seqnum);
1028 | hold = 1;
1029 | break;
1030 | }
1031 | if (sendto(fd2, head->buf, head->recvlen, 0, (struct sockaddr *)&addr2, addrlen) < 0)
1032 | perror("sendto error");
1033 | //printf("%d\n", osn);
1034 | sentseqnum = osn;
1035 |
1036 | if (numofpacket == 12 || numofpacket == 14 || numofpacket == 16)
1037 | {
1038 | unsigned char topython[12];
1039 | if (sendto(fd3, topython, 12, 0, (struct sockaddr *)&addr3, addrlen) < 0)
1040 | perror("sendto error");
1041 | printf("idr:%d\n", numofpacket);
1042 | }
1043 |
1044 |
1045 | osn = 0xFFFF & (osn + 1);
1046 | rtppacket* nexttemp = head->next;
1047 | free(head->buf);
1048 | free(head);
1049 | head = nexttemp;
1050 | numofpacket--;
1051 |
1052 | }
1053 |
1054 |
1055 |
1056 |
1057 | }
1058 |
1059 |
1060 | }
1061 |
1062 |
1063 | int main(int argc, char** argv)
1064 | {
1065 | char *audiorenderComponentName;
1066 | char *decodeComponentName;
1067 | char *renderComponentName;
1068 | char *schedulerComponentName;
1069 | char *clockComponentName;
1070 | int err;
1071 | ILCLIENT_T *handle;
1072 | COMPONENT_T *audiorenderComponent;
1073 | COMPONENT_T *decodeComponent;
1074 | COMPONENT_T *renderComponent;
1075 | COMPONENT_T *schedulerComponent;
1076 | COMPONENT_T *clockComponent;
1077 |
1078 |
1079 |
1080 | avformat_network_init();
1081 |
1082 | if (argc > 1)
1083 | {
1084 | idrsockport = atoi(argv[1]);
1085 | printf("idrsockport:%d\n", idrsockport);
1086 | }
1087 | int audiodest = 0;
1088 | if (argc > 2)
1089 | {
1090 | audiodest = atoi(argv[2]);
1091 | printf("audiodest:%d\n", audiodest);
1092 | }
1093 |
1094 | sourceip = "192.168.173.1";
1095 | if (argc > 3)
1096 | {
1097 | sourceip = argv[3];
1098 | }
1099 | printf("argv3:%s\n", argv[3]);
1100 | printf("sourceip:%s\n", sourceip);
1101 |
1102 | pthread_t npthread;
1103 | if (pthread_create(&npthread, NULL, addnullpacket, NULL) != 0)
1104 | exit(1);
1105 |
1106 | setup_demuxer("rtp://127.0.0.1:57823");
1107 | pFormatCtx->max_delay = 100;
1108 | printf("mdly:%d\n",pFormatCtx->max_delay);
1109 |
1110 | audiorenderComponentName = "audio_render";
1111 | decodeComponentName = "video_decode";
1112 | renderComponentName = "video_render";
1113 | schedulerComponentName = "video_scheduler";
1114 | clockComponentName = "clock";
1115 |
1116 | bcm_host_init();
1117 |
1118 | handle = ilclient_init();
1119 | vcos_log_set_level(VCOS_LOG_CATEGORY, VCOS_LOG_TRACE);
1120 | if (handle == NULL)
1121 | {
1122 | fprintf(stderr, "IL client init failed\n");
1123 | exit(1);
1124 | }
1125 |
1126 | if (OMX_Init() != OMX_ErrorNone)
1127 | {
1128 | ilclient_destroy(handle);
1129 | fprintf(stderr, "OMX init failed\n");
1130 | exit(1);
1131 | }
1132 |
1133 | ilclient_set_error_callback(handle,error_callback,NULL);
1134 | ilclient_set_eos_callback(handle,eos_callback,NULL);
1135 | ilclient_set_port_settings_callback(handle,port_settings_callback,NULL);
1136 | ilclient_set_empty_buffer_done_callback(handle,empty_buffer_done_callback,NULL);
1137 |
1138 | setup_audio_renderComponent(handle, audiorenderComponentName, &audiorenderComponent, audiodest);
1139 | setup_decodeComponent(handle, decodeComponentName, &decodeComponent);
1140 | setup_renderComponent(handle, renderComponentName, &renderComponent);
1141 | setup_schedulerComponent(handle, schedulerComponentName, &schedulerComponent);
1142 | setup_clockComponent(handle, clockComponentName, &clockComponent);
1143 | // both components now in Idle state, no buffers, ports disabled
1144 |
1145 |
1146 | fprintf(stderr, "Num channels for resmapling %d\n",
1147 | av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO));
1148 |
1149 |
1150 |
1151 | // input port
1152 | err = ilclient_enable_port_buffers(decodeComponent, 130,NULL, NULL, NULL);
1153 | if (err < 0)
1154 | {
1155 | fprintf(stderr, "Couldn't enable buffers\n");
1156 | exit(1);
1157 | }
1158 | ilclient_enable_port(decodeComponent, 130);
1159 |
1160 | err = ilclient_change_component_state(decodeComponent, OMX_StateExecuting);
1161 |
1162 | if (err < 0)
1163 | {
1164 | fprintf(stderr, "Couldn't change state to Executing\n");
1165 | exit(1);
1166 | }
1167 | printState(ilclient_get_handle(decodeComponent));
1168 |
1169 | SendDecoderConfig(decodeComponent);
1170 |
1171 |
1172 | /* read frames from the file */
1173 | while (av_read_frame(pFormatCtx, &pkt) >= 0)
1174 | {
1175 | //printf("Read pkt %d\n", pkt.size);
1176 |
1177 | AVPacket orig_pkt = pkt;
1178 | if (pkt.stream_index == video_stream_idx)
1179 | {
1180 | //printf(" read video pkt %d\n", pkt.size);
1181 | copy_into_buffer_and_empty(&pkt, decodeComponent);
1182 |
1183 | err = ilclient_wait_for_event(decodeComponent,
1184 | OMX_EventPortSettingsChanged,
1185 | 131, 0, 0, 1,
1186 | ILCLIENT_EVENT_ERROR | ILCLIENT_PARAMETER_CHANGED,
1187 | 0);
1188 | if (err < 0)
1189 | {
1190 | //printf("No port settings change\n");
1191 | //exit(1);
1192 | }
1193 | else
1194 | {
1195 | printf("Port settings changed\n");
1196 | // exit(0);
1197 | break;
1198 | }
1199 |
1200 |
1201 | if (ilclient_remove_event(decodeComponent, OMX_EventPortSettingsChanged, 131, 0, 0, 1) == 0)
1202 | {
1203 | printf("Removed port settings event\n");
1204 | //exit(0);
1205 | break;
1206 | }
1207 | else
1208 | {
1209 | printf("No portr settting seen yet\n");
1210 | }
1211 | }
1212 | av_free_packet(&orig_pkt);
1213 | }
1214 | while(1)
1215 | {
1216 |
1217 | TUNNEL_T decodeTunnel;
1218 | set_tunnel(&decodeTunnel, decodeComponent, 131, schedulerComponent, 10);
1219 | if ((err = ilclient_setup_tunnel(&decodeTunnel, 0, 0)) < 0)
1220 | {
1221 | fprintf(stderr, "Error setting up decode tunnel %X\n", err);
1222 | exit(1);
1223 | } else
1224 | {
1225 | printf("Decode tunnel set up ok\n");
1226 | }
1227 |
1228 | TUNNEL_T schedulerTunnel;
1229 | set_tunnel(&schedulerTunnel, schedulerComponent, 11, renderComponent, 90);
1230 | if ((err = ilclient_setup_tunnel(&schedulerTunnel, 0, 0)) < 0)
1231 | {
1232 | fprintf(stderr, "Error setting up scheduler tunnel %X\n", err);
1233 | exit(1);
1234 | } else
1235 | {
1236 | printf("Scheduler tunnel set up ok\n");
1237 | }
1238 | //assertion failure:ilclient.c:1082:ilclient_setup_tunnel():error == OMX_ErrorNone
1239 | //Aborted
1240 |
1241 |
1242 | TUNNEL_T clockTunnel;
1243 | set_tunnel(&clockTunnel, clockComponent, 80, schedulerComponent, 12);
1244 | if ((err = ilclient_setup_tunnel(&clockTunnel, 0, 0)) < 0)
1245 | {
1246 | fprintf(stderr, "Error setting up clock tunnel %X\n", err);
1247 | exit(1);
1248 | } else
1249 | {
1250 | printf("Clock tunnel set up ok\n");
1251 | }
1252 | startClock(clockComponent);
1253 | printClockState(clockComponent);
1254 |
1255 | // Okay to go back to processing data
1256 | // enable the decode output ports
1257 |
1258 | OMX_SendCommand(ilclient_get_handle(decodeComponent), OMX_CommandPortEnable, 131, NULL);
1259 |
1260 | ilclient_enable_port(decodeComponent, 131);
1261 |
1262 | // enable the clock output ports
1263 | OMX_SendCommand(ilclient_get_handle(clockComponent), OMX_CommandPortEnable, 80, NULL);
1264 |
1265 | ilclient_enable_port(clockComponent, 80);
1266 |
1267 | // enable the scheduler ports
1268 | OMX_SendCommand(ilclient_get_handle(schedulerComponent), OMX_CommandPortEnable, 10, NULL);
1269 |
1270 | ilclient_enable_port(schedulerComponent, 10);
1271 |
1272 | OMX_SendCommand(ilclient_get_handle(schedulerComponent), OMX_CommandPortEnable, 11, NULL);
1273 |
1274 | ilclient_enable_port(schedulerComponent, 11);
1275 |
1276 |
1277 | OMX_SendCommand(ilclient_get_handle(schedulerComponent), OMX_CommandPortEnable, 12, NULL);
1278 |
1279 | ilclient_enable_port(schedulerComponent, 12);
1280 |
1281 | // enable the render input ports
1282 |
1283 | OMX_SendCommand(ilclient_get_handle(renderComponent), OMX_CommandPortEnable,90, NULL);
1284 |
1285 | ilclient_enable_port(renderComponent, 90);
1286 |
1287 |
1288 |
1289 | // set both components to executing state
1290 | err = ilclient_change_component_state(decodeComponent, OMX_StateExecuting);
1291 | if (err < 0)
1292 | {
1293 | fprintf(stderr, "Couldn't change state to Idle\n");
1294 | exit(1);
1295 | }
1296 | err = ilclient_change_component_state(renderComponent, OMX_StateExecuting);
1297 | if (err < 0)
1298 | {
1299 | fprintf(stderr, "Couldn't change state to Idle\n");
1300 | exit(1);
1301 | }
1302 |
1303 | err = ilclient_change_component_state(schedulerComponent, OMX_StateExecuting);
1304 | if (err < 0)
1305 | {
1306 | fprintf(stderr, "Couldn't change state to Idle\n");
1307 | exit(1);
1308 | }
1309 |
1310 | err = ilclient_change_component_state(clockComponent, OMX_StateExecuting);
1311 | if (err < 0)
1312 | {
1313 | fprintf(stderr, "Couldn't change state to Idle\n");
1314 | exit(1);
1315 | }
1316 |
1317 | AVFrame *frame = av_frame_alloc(); // av_frame_alloc
1318 |
1319 |
1320 | Nodetype* oldnode = malloc(sizeof(Nodetype));
1321 | Nodetype* oldnodecopy = oldnode;
1322 | atomic_store(&numofnode, 0);
1323 |
1324 |
1325 | pthread_t thread;
1326 | if (pthread_create(&thread, NULL, receivepkt, oldnodecopy) != 0)
1327 | exit(1);
1328 |
1329 |
1330 | while (1)
1331 | {
1332 | if (atomic_load(&numofnode) < 2)
1333 | {
1334 | usleep(10);
1335 | continue;
1336 | }
1337 | //else if (numofnode != 1)
1338 | //printf("numofnode: %d\n", numofnode);
1339 |
1340 |
1341 | AVPacket renderpkt = *(oldnode->pbuff);
1342 |
1343 |
1344 | if (renderpkt.stream_index == video_stream_idx)
1345 | {
1346 |
1347 | copy_into_buffer_and_empty(&renderpkt, decodeComponent);
1348 |
1349 | if (ilclient_wait_for_event(decodeComponent, OMX_EventPortSettingsChanged, 131, 0, 0, 1, ILCLIENT_EVENT_ERROR | ILCLIENT_PARAMETER_CHANGED, 0) >= 0)
1350 | {
1351 | printf("port change\n");
1352 | break;
1353 | }
1354 | }
1355 | else if (renderpkt.stream_index == audio_stream_idx)
1356 | {
1357 |
1358 | int got_frame;
1359 |
1360 | if (((err = avcodec_decode_audio4(codec_context, frame, &got_frame, &renderpkt)) < 0) ||
1361 | !got_frame)
1362 | continue;//"Error decoding
1363 |
1364 | read_audio_into_buffer_and_empty(frame, audiorenderComponent);
1365 |
1366 |
1367 | }
1368 |
1369 | av_free_packet(&renderpkt);
1370 | Nodetype* pnext = oldnode->next;
1371 | free(oldnode);
1372 |
1373 | oldnode = pnext;
1374 | atomic_fetch_sub(&numofnode, 1);
1375 |
1376 |
1377 | }
1378 | atomic_fetch_sub(&numofnode, 10000);
1379 |
1380 |
1381 | if (pthread_join(thread, NULL) != 0)
1382 | exit(1);
1383 |
1384 | while (1)
1385 | {
1386 | if (oldnode->next == NULL)
1387 | {
1388 | free(oldnode);
1389 | break;
1390 | }
1391 | AVPacket renderpkt = *(oldnode->pbuff);
1392 |
1393 | av_free_packet(&renderpkt);
1394 | Nodetype* pnext = oldnode->next;
1395 | free(oldnode);
1396 |
1397 | oldnode = pnext;
1398 | }
1399 |
1400 |
1401 |
1402 | //free(oldnode);
1403 |
1404 |
1405 |
1406 | }
1407 |
1408 |
1409 | if (pthread_join(npthread, NULL) != 0)
1410 | exit(1);
1411 |
1412 | exit(0);
1413 | }
1414 |
--------------------------------------------------------------------------------
/project.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | This software is part of lazycast, a simple wireless display receiver for Raspberry Pi
4 | Copyright (C) 2020 Hsun-Wei Cho
5 | Using any part of the code in commercial products is prohibited.
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | """
17 | import socket
18 | from time import sleep
19 | import os
20 | import uuid
21 | commands = {}
22 | commands[1] = 'SOURCE_READY'
23 | commands[2] = 'STOP_PROJECTION'
24 | commands[3] = 'SECURITY_HANDSHAKE'
25 | commands[4] = 'SESSION_REQUEST'
26 | commands[5] = 'PIN_CHALLENGE'
27 | commands[6] = 'PIN_RESPONSE'
28 |
29 | types = {}
30 | types[0] = 'FRIENDLY_NAME'
31 | types[2] = 'RTSP_PORT'
32 | types[3] = 'SOURCE_ID'
33 | types[4] = 'SECURITY_TOKEN'
34 | types[5] = 'SECURITY_OPTIONS'
35 | types[6] = 'PIN_CHALLENGE'
36 | types[7] = 'PIN_RESPONSE_REASON'
37 |
38 | if os.path.exists('uuid.txt'):
39 | uuidfile = open('uuid.txt','r')
40 | lines = uuidfile.readlines()
41 | uuidfile.close()
42 | uuidstr = lines[0]
43 | else:
44 | uuidstr = str(uuid.uuid4()).upper()
45 | uuidfile = open('uuid.txt','w')
46 | uuidfile.write(uuidstr)
47 | uuidfile.close()
48 |
49 | hostname = socket.gethostname()
50 | print('The hostname of this machine is: '+hostname)
51 |
52 | print(uuidstr)
53 |
54 | dnsstr = 'avahi-publish-service '+hostname+' _display._tcp 7250 container_id={'+uuidstr+'}'
55 | print(dnsstr)
56 | os.system(dnsstr+' &')
57 |
58 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59 | sock.bind(('',7250))
60 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
61 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62 |
63 | sock.listen(1)
64 |
65 | while True:
66 | (conn, addr) = sock.accept()
67 | print('Connected by', addr)
68 | sourceip = addr[0]
69 |
70 |
71 | while True:
72 | data = conn.recv(1024)
73 | # print data
74 | print(data.hex())
75 |
76 | if len(data) == 0:
77 | break
78 |
79 |
80 | data = data.hex()
81 | size = int(data[0:4],16)
82 | version = int(data[4:6])
83 | command = int(data[6:8])
84 |
85 | print (size,version,command)
86 |
87 | messagetype = commands[command]
88 | print(messagetype)
89 |
90 | if messagetype == 'SOURCE_READY':
91 | os.system('./d2.py '+sourceip+' &')
92 |
93 |
94 | i = 8
95 | while i scan.txt')
7 |
8 | infile = open('scan.txt','r')
9 | lines = infile.readlines()
10 | infile.close()
11 |
12 | display = False
13 |
14 |
15 | for line in lines:
16 | if 'DIRECT' in line:
17 | display = True
18 | loop = False
19 | elif 'Cell' in line:
20 | display = False
21 | if display:
22 | print line,
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/vlcbased.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #################################################################################
3 | # Run script for lazycast
4 | # Licensed under GNU General Public License v3.0 GPL-3 (in short)
5 | #
6 | # You may copy, distribute and modify the software as long as you track
7 | # changes/dates in source files. Any modifications to our software
8 | # including (via compiler) GPL-licensed code must also be made available
9 | # under the GPL along with build & install instructions.
10 | #
11 | #################################################################################
12 | managefrequency=1
13 | while :
14 | do
15 | p2pdevinterface=$(sudo wpa_cli interface | grep -E "p2p-dev" | tail -1)
16 | wlaninterface=$(echo $p2pdevinterface | cut -c1-8 --complement)
17 | echo $p2pdevinterface
18 | echo $wlaninterface
19 | ain="$(sudo wpa_cli interface)"
20 | echo "${ain}"
21 | if [ `echo "${ain}" | grep -c "p2p-wl"` -gt 0 ]
22 | then
23 | echo "already on"
24 |
25 | else
26 | sudo wpa_cli -i$p2pdevinterface p2p_find type=progessive
27 | sudo wpa_cli -i$p2pdevinterface set device_name "$(uname -n)"
28 | sudo wpa_cli -i$p2pdevinterface set device_type 7-0050F204-1
29 | sudo wpa_cli -i$p2pdevinterface set p2p_go_ht40 1
30 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 0 000600111c44012c
31 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 1 0006000000000000
32 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 6 000700000000000000
33 | perentry="$(sudo wpa_cli -i$p2pdevinterface list_networks | grep "\[DISABLED\]\[P2P-PERSISTENT\]" | tail -1)"
34 | echo "${perentry}"
35 | if [ `echo "${perentry}" | grep -c "P2P-PERSISTENT"` -gt 0 ]
36 | then
37 | networkid=${perentry%%D*}
38 | perstr="=${networkid}"
39 | else
40 | perstr=""
41 | fi
42 | echo "${perstr}"
43 | echo "${p2pdevinterface}"
44 | wlanfreq=$(sudo wpa_cli -i$wlaninterface status | grep "freq")
45 | if [ "$managefrequency" == "0" ]
46 | then
47 | wlanfreq=""
48 | fi
49 | if [ "$wlanfreq" != "" ]
50 | then
51 | echo $wlaninterface": "$wlanfreq
52 | echo "Setting up wifi p2p with "$wlanfreq
53 | fi
54 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
55 | do
56 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
57 | do
58 | #sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr freq=2
59 | result=$(sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr $wlanfreq)
60 | if [ "$result" == "FAIL" ]
61 | then
62 | wlanfreq=""
63 | managefrequency=0
64 | fi
65 | sleep 2
66 | ain="$(sudo wpa_cli interface)"
67 | echo "$ain"
68 | done
69 | sleep 5
70 | ain="$(sudo wpa_cli interface)"
71 | echo "$ain"
72 | done
73 |
74 | fi
75 |
76 | p2pinterface=$(echo "${ain}" | grep "p2p-wl" | grep -v "interface")
77 | echo $p2pinterface
78 |
79 | sudo ifconfig $p2pinterface 192.168.173.1
80 | printf "start 192.168.173.80\n">udhcpd.conf
81 | printf "end 192.168.173.80\n">>udhcpd.conf
82 | printf "interface $p2pinterface\n">>udhcpd.conf
83 | printf "option subnet 255.255.255.0\n">>udhcpd.conf
84 | printf "option lease 10">>udhcpd.conf
85 | sleep 3
86 | sudo busybox udhcpd ./udhcpd.conf
87 | echo "The display is ready"
88 | echo "Your device is called: "$(uname -n)""
89 | while :
90 | do
91 | echo "PIN:"
92 | sudo wpa_cli -i$p2pinterface wps_pin any 31415926
93 | echo ""
94 | ./d2vlc.py
95 |
96 | done
97 | done
98 |
--------------------------------------------------------------------------------
/win10debug.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #################################################################################
3 | # Run script for lazycast
4 | # Licensed under GNU General Public License v3.0 GPL-3 (in short)
5 | #
6 | # You may copy, distribute and modify the software as long as you track
7 | # changes/dates in source files. Any modifications to our software
8 | # including (via compiler) GPL-licensed code must also be made available
9 | # under the GPL along with build & install instructions.
10 | #
11 | #################################################################################
12 | managefrequency=1
13 | LD_LIBRARY_PATH=/opt/vc/lib
14 | export LD_LIBRARY_PATH
15 | while :
16 | do
17 | p2pdevinterface=$(sudo wpa_cli interface | grep -E "p2p-dev" | tail -1)
18 | wlaninterface=$(echo $p2pdevinterface | cut -c1-8 --complement)
19 | echo $p2pdevinterface
20 | echo $wlaninterface
21 | ain="$(sudo wpa_cli interface)"
22 | echo "${ain}"
23 | if [ `echo "${ain}" | grep -c "p2p-wl"` -gt 0 ]
24 | then
25 | echo "already on"
26 |
27 | else
28 | sudo wpa_cli -i$p2pdevinterface p2p_find type=progessive
29 | sudo wpa_cli -i$p2pdevinterface set device_name "$(uname -n)"
30 | sudo wpa_cli -i$p2pdevinterface set device_type 7-0050F204-1
31 | sudo wpa_cli -i$p2pdevinterface set p2p_go_ht40 1
32 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 0 000600111c44012c
33 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 1 0006000000000000
34 | sudo wpa_cli -i$p2pdevinterface wfd_subelem_set 6 000700000000000000
35 | perentry="$(sudo wpa_cli -i$p2pdevinterface list_networks | grep "\[DISABLED\]\[P2P-PERSISTENT\]" | tail -1)"
36 | echo "${perentry}"
37 | if [ `echo "${perentry}" | grep -c "P2P-PERSISTENT"` -gt 0 ]
38 | then
39 | networkid=${perentry%%D*}
40 | perstr="=${networkid}"
41 | else
42 | perstr=""
43 | fi
44 | echo "${perstr}"
45 | echo "${p2pdevinterface}"
46 | wlanfreq=$(sudo wpa_cli -i$wlaninterface status | grep "freq")
47 | if [ "$managefrequency" == "0" ]
48 | then
49 | wlanfreq=""
50 | fi
51 | if [ "$wlanfreq" != "" ]
52 | then
53 | echo $wlaninterface": "$wlanfreq
54 | echo "Setting up wifi p2p with "$wlanfreq
55 | fi
56 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
57 | do
58 | while [ `echo "${ain}" | grep -c "p2p-wl"` -lt 1 ]
59 | do
60 | #sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr freq=2
61 | result=$(sudo wpa_cli p2p_group_add -i$p2pdevinterface persistent$perstr freq=2)
62 | if [ "$result" == "FAIL" ]
63 | then
64 | wlanfreq=""
65 | managefrequency=0
66 | fi
67 | sleep 2
68 | ain="$(sudo wpa_cli interface)"
69 | echo "$ain"
70 | done
71 | sleep 5
72 | ain="$(sudo wpa_cli interface)"
73 | echo "$ain"
74 | done
75 |
76 | fi
77 |
78 | p2pinterface=$(echo "${ain}" | grep "p2p-wl" | grep -v "interface")
79 | echo $p2pinterface
80 |
81 | sudo ifconfig $p2pinterface 192.168.173.1
82 | printf "start 192.168.173.80\n">udhcpd.conf
83 | printf "end 192.168.173.80\n">>udhcpd.conf
84 | printf "interface $p2pinterface\n">>udhcpd.conf
85 | printf "option subnet 255.255.255.0\n">>udhcpd.conf
86 | printf "option lease 10000">>udhcpd.conf
87 | sleep 3
88 | sudo busybox udhcpd ./udhcpd.conf
89 | echo "The display is ready"
90 | echo "Your device is called: "$(uname -n)""
91 | while :
92 | do
93 | echo "PIN:"
94 | sudo wpa_cli -i$p2pinterface wps_pin any 31415926
95 | echo ""
96 | ./d2win10debug.py
97 | if [ `sudo wpa_cli interface | grep -c "p2p-wl"` == 0 ]
98 | then
99 | break
100 | fi
101 |
102 |
103 |
104 | done
105 | done
106 |
--------------------------------------------------------------------------------
/wiresharkscript.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | sudo iw dev wlo1 interface add mon0 type monitor
3 | sudo ip link set mon0 up
4 | wireshark
--------------------------------------------------------------------------------