├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── firmware
├── LICENSE
├── LICENSE CYPRESS
└── SDDC_FX3.img
├── include
├── CMakeLists.txt
└── libsddc.h
├── misc
└── 99-sddc.rules
└── src
├── CMakeLists.txt
├── ezusb.c
├── ezusb.h
├── libsddc.c
├── logging.c
├── logging.h
├── sddc_stream_test.c
├── sddc_test.c
├── sddc_vhf_stream_test.c
├── streaming.c
├── streaming.h
├── usb_device.c
├── usb_device.h
├── usb_device_internals.h
├── wavehdr.h
├── wavewrite.c
└── wavewrite.h
/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | *~
3 | .*.swp
4 | workdir/
5 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 by Franco Venturi
2 | #
3 | # SPDX-License-Identifier: GPL-3.0-or-later
4 | #
5 |
6 | ### project
7 | cmake_minimum_required(VERSION 3.13)
8 |
9 | project(libsddc VERSION 0.0.1)
10 |
11 |
12 | ### build options
13 | # default build type: Release
14 | if(NOT CMAKE_BUILD_TYPE)
15 | set(CMAKE_BUILD_TYPE "Release")
16 | endif(NOT CMAKE_BUILD_TYPE)
17 | message(STATUS "Build type: " ${CMAKE_BUILD_TYPE} " - Version: " ${VERSION} " / " ${LIBVER})
18 |
19 | include(GNUInstallDirs)
20 |
21 | add_compile_options(-Wall -Wextra -pedantic -Werror)
22 |
23 |
24 | ### dependencies
25 | find_package(PkgConfig)
26 | pkg_check_modules(LIBUSB REQUIRED libusb-1.0 IMPORTED_TARGET)
27 |
28 |
29 | ### subdirectories
30 | add_subdirectory(include)
31 | add_subdirectory(src)
32 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # libsddc - A low level library for wideband SDR receivers
2 |
3 | A library and a few simple applications for wideband SDR receivers like BBRF103, RX-666, RX888, HF103, etc
4 |
5 | **IMPORTANT: the development of this library has now become part of Oscar's ExtIO_sddc project: https://github.com/ik1xpv/ExtIO_sddc - since the Linux code in that repository is not yet fully functional, I am keeping this version around for now in order to provide an option for Linux users to be able to stream samples from the RX888**
6 |
7 |
8 | These SDR receivers and this library wouldn't be possible without all the excellent work by Oscar Steila, IK1XPV - a great deal of useful information about them is at and at .
9 |
10 | This library is similar in concept to librtlsdr (see and ).
11 |
12 | I wrote this library and the example applications from scratch (i.e. any bug in this code is exclusively my fault). Many parts of the code use Oscar's ExtIO dll driver for Windows () as a reference, and I want to really thank him for this wonderful project!
13 |
14 |
15 | NOTICE: this library expects the SDR to be running firmware 1.01 or above; for firmware versions 0.X (0.4, 0.5, etc), please see the 'rf103' project here: https://github.com/fventuri/RF103
16 |
17 |
18 | The firmware directory contains Oscar Steila's firmware for convenience. The source code for the firmware is here: https://github.com/ik1xpv/ExtIO_sddc/tree/master/SDDC_FX3
19 |
20 |
21 | ## Credits
22 |
23 | - Oscar Steila, IK1XPV for the BBRF103 and HF103 projects
24 | - Hayati Aygün for many improvements and bug fixes to the code, adding useful examples, and many useful suggestions
25 | - Jakob Ketterl, DD5JFK for many hours and days spent troubleshooting the code and fixing my bugs, and for his ideas on how to improve the library
26 | - Howard Su and Justin Peng for all their work and experimentation on the RX888 hardware, improving the firmware and teamwork for the Windows ExtIO dll driver
27 | - Takafumi JI3GAB for the latest set of fixes to be able to run using the provided firmware
28 |
29 |
30 | ## How to build
31 |
32 | ```
33 | cd libsddc
34 | mkdir build
35 | cd build
36 | cmake ..
37 | make
38 | sudo make install
39 | sudo ldconfig
40 | ```
41 |
42 | ## udev rules
43 |
44 | On Linux usually only root has full access to the USB devices. In order to be able to run these programs and other programs that use this library as a regular user, you may want to add some exception rules for these USB devices. A simple and effective way to create persistent rules (which will last even after a reboot) is to add the file to your udev rule directory '/etc/udev/rules.d' and tell 'udev' to reload its rules.
45 |
46 | These are the commands that need to be run only once using sudo to grant access to these SDRs to a regular user:
47 | ```
48 | sudo cp misc/99-sddc.rules /etc/udev/rules.d/
49 | sudo udevadm control --reload-rules
50 | ```
51 |
52 | For some distributions (like Linux Mint), you may also need this command (thanks to Jon Fear for finding out):
53 | ```
54 | sudo udevadm trigger
55 | ```
56 |
57 | ## Copyright
58 |
59 | (C) 2020 Franco Venturi - Licensed under the GNU GPL V3 (see )
60 |
61 | Firmware:
62 | Copyright (c) 2017-2020 Oscar Steila ik1xpvgmail.com
63 |
--------------------------------------------------------------------------------
/firmware/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2017-2020 Oscar Steila ik1xpvgmail.com
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.The MIT License (MIT)
22 | The MIT License (MIT)
23 |
--------------------------------------------------------------------------------
/firmware/LICENSE CYPRESS:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fventuri/libsddc/7eadf4f0f40fc8c0c52cbb960864173df51e8be2/firmware/LICENSE CYPRESS
--------------------------------------------------------------------------------
/firmware/SDDC_FX3.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fventuri/libsddc/7eadf4f0f40fc8c0c52cbb960864173df51e8be2/firmware/SDDC_FX3.img
--------------------------------------------------------------------------------
/include/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 by Franco Venturi
2 | #
3 | # SPDX-License-Identifier: GPL-3.0-or-later
4 | #
5 |
6 | ########################################################################
7 | # Install public header files
8 | ########################################################################
9 | install(FILES
10 | libsddc.h
11 | DESTINATION include
12 | )
13 |
--------------------------------------------------------------------------------
/include/libsddc.h:
--------------------------------------------------------------------------------
1 | /*
2 | * libsddc - low level functions for wideband SDR receivers like
3 | * BBRF103, RX-666, RX888, HF103, etc
4 | *
5 | * Copyright (C) 2020 by Franco Venturi
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | *
20 | * SPDX-License-Identifier: GPL-3.0-or-later
21 | */
22 |
23 | #ifndef __LIBSDDC_H
24 | #define __LIBSDDC_H
25 |
26 | #ifdef __cplusplus
27 | extern "C" {
28 | #endif
29 |
30 | #include
31 |
32 | typedef struct sddc sddc_t;
33 |
34 | struct sddc_device_info {
35 | unsigned char *manufacturer;
36 | unsigned char *product;
37 | unsigned char *serial_number;
38 | };
39 |
40 | enum SDDCStatus {
41 | SDDC_STATUS_OFF,
42 | SDDC_STATUS_READY,
43 | SDDC_STATUS_STREAMING,
44 | SDDC_STATUS_FAILED = 0xff
45 | };
46 |
47 | enum SDDCHWModel {
48 | HW_NORADIO,
49 | HW_BBRF103,
50 | HW_HF103,
51 | HW_RX888,
52 | HW_RX888R2,
53 | HW_RX999
54 | };
55 |
56 | enum RFMode {
57 | NO_RF_MODE,
58 | HF_MODE,
59 | VHF_MODE
60 | };
61 |
62 | enum LEDColors {
63 | LED_YELLOW = 0x01,
64 | LED_RED = 0x02,
65 | LED_BLUE = 0x04
66 | };
67 |
68 |
69 | /* basic functions */
70 | int sddc_get_device_count();
71 |
72 | int sddc_get_device_info(struct sddc_device_info **sddc_device_infos);
73 |
74 | int sddc_free_device_info(struct sddc_device_info *sddc_device_infos);
75 |
76 | sddc_t *sddc_open(int index, const char* imagefile);
77 |
78 | void sddc_close(sddc_t *this);
79 |
80 | enum SDDCStatus sddc_get_status(sddc_t *this);
81 |
82 | enum SDDCHWModel sddc_get_hw_model(sddc_t *this);
83 |
84 | const char *sddc_get_hw_model_name(sddc_t *this);
85 |
86 | uint16_t sddc_get_firmware(sddc_t *this);
87 |
88 | const double *sddc_get_frequency_range(sddc_t *this);
89 |
90 | enum RFMode sddc_get_rf_mode(sddc_t *this);
91 |
92 | int sddc_set_rf_mode(sddc_t *this, enum RFMode rf_mode);
93 |
94 |
95 | /* LED functions */
96 | int sddc_led_on(sddc_t *this, uint8_t led_pattern);
97 |
98 | int sddc_led_off(sddc_t *this, uint8_t led_pattern);
99 |
100 | int sddc_led_toggle(sddc_t *this, uint8_t led_pattern);
101 |
102 |
103 | /* ADC functions */
104 | int sddc_get_adc_dither(sddc_t *this);
105 |
106 | int sddc_set_adc_dither(sddc_t *this, int dither);
107 |
108 | int sddc_get_adc_random(sddc_t *this);
109 |
110 | int sddc_set_adc_random(sddc_t *this, int random);
111 |
112 |
113 | /* HF block functions */
114 | double sddc_get_hf_attenuation(sddc_t *this);
115 |
116 | int sddc_set_hf_attenuation(sddc_t *this, double attenuation);
117 |
118 | int sddc_get_hf_bias(sddc_t *this);
119 |
120 | int sddc_set_hf_bias(sddc_t *this, int bias);
121 |
122 |
123 | /* VHF block and VHF/UHF tuner functions */
124 | double sddc_get_tuner_frequency(sddc_t *this);
125 |
126 | int sddc_set_tuner_frequency(sddc_t *this, double frequency);
127 |
128 | int sddc_get_tuner_rf_attenuations(sddc_t *this, const double *attenuations[]);
129 |
130 | double sddc_get_tuner_rf_attenuation(sddc_t *this);
131 |
132 | int sddc_set_tuner_rf_attenuation(sddc_t *this, double attenuation);
133 |
134 | int sddc_get_tuner_if_attenuations(sddc_t *this, const double *attenuations[]);
135 |
136 | double sddc_get_tuner_if_attenuation(sddc_t *this);
137 |
138 | int sddc_set_tuner_if_attenuation(sddc_t *this, double attenuation);
139 |
140 | int sddc_get_vhf_bias(sddc_t *this);
141 |
142 | int sddc_set_vhf_bias(sddc_t *this, int bias);
143 |
144 |
145 | /* streaming functions */
146 | typedef void (*sddc_read_async_cb_t)(uint32_t data_size, uint8_t *data,
147 | void *context);
148 |
149 | double sddc_get_sample_rate(sddc_t *this);
150 |
151 | int sddc_set_sample_rate(sddc_t *this, double sample_rate);
152 |
153 | int sddc_set_async_params(sddc_t *this, uint32_t frame_size,
154 | uint32_t num_frames, sddc_read_async_cb_t callback,
155 | void *callback_context);
156 |
157 | int sddc_start_streaming(sddc_t *this);
158 |
159 | int sddc_handle_events(sddc_t *this);
160 |
161 | int sddc_stop_streaming(sddc_t *this);
162 |
163 | int sddc_reset_status(sddc_t *this);
164 |
165 | int sddc_read_sync(sddc_t *this, uint8_t *data, int length, int *transferred);
166 |
167 |
168 | /* Misc functions */
169 | double sddc_get_frequency_correction(sddc_t *this);
170 |
171 | int sddc_set_frequency_correction(sddc_t *this, double correction);
172 |
173 | #ifdef __cplusplus
174 | }
175 | #endif
176 |
177 | #endif /* __LIBSDDC_H */
178 |
--------------------------------------------------------------------------------
/misc/99-sddc.rules:
--------------------------------------------------------------------------------
1 | SUBSYSTEM=="usb",ENV{DEVTYPE}=="usb_device",ATTRS{idVendor}=="04b4",ATTRS{idProduct}=="00f1",MODE:="0666"
2 | SUBSYSTEM=="usb",ENV{DEVTYPE}=="usb_device",ATTRS{idVendor}=="04b4",ATTRS{idProduct}=="00f3",MODE:="0666"
3 |
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 by Franco Venturi
2 | #
3 | # SPDX-License-Identifier: GPL-3.0-or-later
4 | #
5 |
6 | ### shared library
7 | add_library(sddc SHARED
8 | libsddc.c
9 | ezusb.c
10 | logging.c
11 | usb_device.c
12 | streaming.c
13 | )
14 | set_target_properties(sddc PROPERTIES VERSION ${PROJECT_VERSION})
15 | set_target_properties(sddc PROPERTIES SOVERSION 0)
16 |
17 | target_include_directories(sddc PUBLIC
18 | $
19 | $ # /include
20 | )
21 | target_link_libraries(sddc PkgConfig::LIBUSB)
22 |
23 |
24 | # applications
25 | add_executable(sddc_test sddc_test.c)
26 | target_link_libraries(sddc_test sddc)
27 | add_executable(sddc_stream_test sddc_stream_test.c wavewrite.c)
28 | target_link_libraries(sddc_stream_test sddc)
29 | add_executable(sddc_vhf_stream_test sddc_vhf_stream_test.c wavewrite.c)
30 | target_link_libraries(sddc_vhf_stream_test sddc)
31 |
32 |
33 | # install
34 | install(TARGETS sddc
35 | LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
36 | )
37 |
38 | install(TARGETS sddc_test sddc_stream_test sddc_vhf_stream_test
39 | DESTINATION ${CMAKE_INSTALL_BINDIR}
40 | )
41 |
--------------------------------------------------------------------------------
/src/ezusb.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2001 Stephen Williams (steve@icarus.com)
3 | * Copyright © 2001-2002 David Brownell (dbrownell@users.sourceforge.net)
4 | * Copyright © 2008 Roger Williams (rawqux@users.sourceforge.net)
5 | * Copyright © 2012 Pete Batard (pete@akeo.ie)
6 | * Copyright © 2013 Federico Manzan (f.manzan@gmail.com)
7 | *
8 | * This source code is free software; you can redistribute it
9 | * and/or modify it in source code form under the terms of the GNU
10 | * General Public License as published by the Free Software
11 | * Foundation; either version 2 of the License, or (at your option)
12 | * any later version.
13 | *
14 | * This program is distributed in the hope that it will be useful,
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | * GNU General Public License for more details.
18 | *
19 | * You should have received a copy of the GNU General Public License
20 | * along with this program; if not, write to the Free Software
21 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
22 | */
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | #include "libusb.h"
31 | #include "ezusb.h"
32 |
33 | //extern void logerror(const char *format, ...)
34 | // __attribute__ ((format(printf, 1, 2)));
35 | //
36 |
37 | void logerror(const char *format, ...)
38 | __attribute__ ((format (__printf__, 1, 2)));
39 |
40 | void logerror(const char *format, ...)
41 | {
42 | va_list ap;
43 | va_start(ap, format);
44 | vfprintf(stderr, format, ap);
45 | va_end(ap);
46 | }
47 |
48 |
49 | /*
50 | * This file contains functions for uploading firmware into Cypress
51 | * EZ-USB microcontrollers. These chips use control endpoint 0 and vendor
52 | * specific commands to support writing into the on-chip SRAM. They also
53 | * support writing into the CPUCS register, which is how we reset the
54 | * processor after loading firmware (including the reset vector).
55 | *
56 | * These Cypress devices are 8-bit 8051 based microcontrollers with
57 | * special support for USB I/O. They come in several packages, and
58 | * some can be set up with external memory when device costs allow.
59 | * Note that the design was originally by AnchorChips, so you may find
60 | * references to that vendor (which was later merged into Cypress).
61 | * The Cypress FX parts are largely compatible with the Anchorhip ones.
62 | */
63 |
64 | int verbose = 1;
65 |
66 | /*
67 | * return true if [addr,addr+len] includes external RAM
68 | * for Anchorchips EZ-USB or Cypress EZ-USB FX
69 | */
70 | static bool fx_is_external(uint32_t addr, size_t len)
71 | {
72 | /* with 8KB RAM, 0x0000-0x1b3f can be written
73 | * we can't tell if it's a 4KB device here
74 | */
75 | if (addr <= 0x1b3f)
76 | return ((addr + len) > 0x1b40);
77 |
78 | /* there may be more RAM; unclear if we can write it.
79 | * some bulk buffers may be unused, 0x1b3f-0x1f3f
80 | * firmware can set ISODISAB for 2KB at 0x2000-0x27ff
81 | */
82 | return true;
83 | }
84 |
85 | /*
86 | * return true if [addr,addr+len] includes external RAM
87 | * for Cypress EZ-USB FX2
88 | */
89 | static bool fx2_is_external(uint32_t addr, size_t len)
90 | {
91 | /* 1st 8KB for data/code, 0x0000-0x1fff */
92 | if (addr <= 0x1fff)
93 | return ((addr + len) > 0x2000);
94 |
95 | /* and 512 for data, 0xe000-0xe1ff */
96 | else if (addr >= 0xe000 && addr <= 0xe1ff)
97 | return ((addr + len) > 0xe200);
98 |
99 | /* otherwise, it's certainly external */
100 | else
101 | return true;
102 | }
103 |
104 | /*
105 | * return true if [addr,addr+len] includes external RAM
106 | * for Cypress EZ-USB FX2LP
107 | */
108 | static bool fx2lp_is_external(uint32_t addr, size_t len)
109 | {
110 | /* 1st 16KB for data/code, 0x0000-0x3fff */
111 | if (addr <= 0x3fff)
112 | return ((addr + len) > 0x4000);
113 |
114 | /* and 512 for data, 0xe000-0xe1ff */
115 | else if (addr >= 0xe000 && addr <= 0xe1ff)
116 | return ((addr + len) > 0xe200);
117 |
118 | /* otherwise, it's certainly external */
119 | else
120 | return true;
121 | }
122 |
123 |
124 | /*****************************************************************************/
125 |
126 | /*
127 | * These are the requests (bRequest) that the bootstrap loader is expected
128 | * to recognize. The codes are reserved by Cypress, and these values match
129 | * what EZ-USB hardware, or "Vend_Ax" firmware (2nd stage loader) uses.
130 | * Cypress' "a3load" is nice because it supports both FX and FX2, although
131 | * it doesn't have the EEPROM support (subset of "Vend_Ax").
132 | */
133 | #define RW_INTERNAL 0xA0 /* hardware implements this one */
134 | #define RW_MEMORY 0xA3
135 |
136 | /*
137 | * Issues the specified vendor-specific write request.
138 | */
139 | static int ezusb_write(libusb_device_handle *device, const char *label,
140 | uint8_t opcode, uint32_t addr, const unsigned char *data, size_t len)
141 | {
142 | int status;
143 |
144 | if (verbose > 1)
145 | logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, (unsigned)len, (unsigned)len);
146 | status = libusb_control_transfer(device,
147 | LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
148 | opcode, addr & 0xFFFF, addr >> 16,
149 | (unsigned char*)data, (uint16_t)len, 1000);
150 | if (status != (signed)len) {
151 | if (status < 0)
152 | logerror("%s: %s\n", label, libusb_error_name(status));
153 | else
154 | logerror("%s ==> %d\n", label, status);
155 | }
156 | return (status < 0) ? -EIO : 0;
157 | }
158 |
159 | /*
160 | * Issues the specified vendor-specific read request.
161 | */
162 | static int ezusb_read(libusb_device_handle *device, const char *label,
163 | uint8_t opcode, uint32_t addr, const unsigned char *data, size_t len)
164 | {
165 | int status;
166 |
167 | if (verbose > 1)
168 | logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, (unsigned)len, (unsigned)len);
169 | status = libusb_control_transfer(device,
170 | LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
171 | opcode, addr & 0xFFFF, addr >> 16,
172 | (unsigned char*)data, (uint16_t)len, 1000);
173 | if (status != (signed)len) {
174 | if (status < 0)
175 | logerror("%s: %s\n", label, libusb_error_name(status));
176 | else
177 | logerror("%s ==> %d\n", label, status);
178 | }
179 | return (status < 0) ? -EIO : 0;
180 | }
181 |
182 | /*
183 | * Modifies the CPUCS register to stop or reset the CPU.
184 | * Returns false on error.
185 | */
186 | static bool ezusb_cpucs(libusb_device_handle *device, uint32_t addr, bool doRun)
187 | {
188 | int status;
189 | uint8_t data = doRun ? 0x00 : 0x01;
190 |
191 | if (verbose)
192 | logerror("%s\n", data ? "stop CPU" : "reset CPU");
193 | status = libusb_control_transfer(device,
194 | LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
195 | RW_INTERNAL, addr & 0xFFFF, addr >> 16,
196 | &data, 1, 1000);
197 | if ((status != 1) &&
198 | /* We may get an I/O error from libusb as the device disappears */
199 | ((!doRun) || (status != LIBUSB_ERROR_IO)))
200 | {
201 | const char *mesg = "can't modify CPUCS";
202 | if (status < 0)
203 | logerror("%s: %s\n", mesg, libusb_error_name(status));
204 | else
205 | logerror("%s\n", mesg);
206 | return false;
207 | } else
208 | return true;
209 | }
210 |
211 | /*
212 | * Send an FX3 jumpt to address command
213 | * Returns false on error.
214 | */
215 | static bool ezusb_fx3_jump(libusb_device_handle *device, uint32_t addr)
216 | {
217 | int status;
218 |
219 | if (verbose)
220 | logerror("transfer execution to Program Entry at 0x%08x\n", addr);
221 | status = libusb_control_transfer(device,
222 | LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
223 | RW_INTERNAL, addr & 0xFFFF, addr >> 16,
224 | NULL, 0, 1000);
225 | /* We may get an I/O error from libusb as the device disappears */
226 | if ((status != 0) && (status != LIBUSB_ERROR_IO))
227 | {
228 | const char *mesg = "failed to send jump command";
229 | if (status < 0)
230 | logerror("%s: %s\n", mesg, libusb_error_name(status));
231 | else
232 | logerror("%s\n", mesg);
233 | return false;
234 | } else
235 | return true;
236 | }
237 |
238 | /*****************************************************************************/
239 |
240 | /*
241 | * Parse an Intel HEX image file and invoke the poke() function on the
242 | * various segments to implement policies such as writing to RAM (with
243 | * a one or two stage loader setup, depending on the firmware) or to
244 | * EEPROM (two stages required).
245 | *
246 | * image - the hex image file
247 | * context - for use by poke()
248 | * is_external - if non-null, used to check which segments go into
249 | * external memory (writable only by software loader)
250 | * poke - called with each memory segment; errors indicated
251 | * by returning negative values.
252 | *
253 | * Caller is responsible for halting CPU as needed, such as when
254 | * overwriting a second stage loader.
255 | */
256 | static int parse_ihex(FILE *image, void *context,
257 | bool (*is_external)(uint32_t addr, size_t len),
258 | int (*poke) (void *context, uint32_t addr, bool external,
259 | const unsigned char *data, size_t len))
260 | {
261 | unsigned char data[1023];
262 | uint32_t data_addr = 0;
263 | size_t data_len = 0;
264 | int rc;
265 | int first_line = 1;
266 | bool external = false;
267 |
268 | /* Read the input file as an IHEX file, and report the memory segments
269 | * as we go. Each line holds a max of 16 bytes, but uploading is
270 | * faster (and EEPROM space smaller) if we merge those lines into larger
271 | * chunks. Most hex files keep memory segments together, which makes
272 | * such merging all but free. (But it may still be worth sorting the
273 | * hex files to make up for undesirable behavior from tools.)
274 | *
275 | * Note that EEPROM segments max out at 1023 bytes; the upload protocol
276 | * allows segments of up to 64 KBytes (more than a loader could handle).
277 | */
278 | for (;;) {
279 | char buf[512], *cp;
280 | char tmp, type;
281 | size_t len;
282 | unsigned idx, off;
283 |
284 | cp = fgets(buf, sizeof(buf), image);
285 | if (cp == NULL) {
286 | logerror("EOF without EOF record!\n");
287 | break;
288 | }
289 |
290 | /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
291 | if (buf[0] == '#')
292 | continue;
293 |
294 | if (buf[0] != ':') {
295 | logerror("not an ihex record: %s", buf);
296 | return -2;
297 | }
298 |
299 | /* ignore any newline */
300 | cp = strchr(buf, '\n');
301 | if (cp)
302 | *cp = 0;
303 |
304 | if (verbose >= 3)
305 | logerror("** LINE: %s\n", buf);
306 |
307 | /* Read the length field (up to 16 bytes) */
308 | tmp = buf[3];
309 | buf[3] = 0;
310 | len = strtoul(buf+1, NULL, 16);
311 | buf[3] = tmp;
312 |
313 | /* Read the target offset (address up to 64KB) */
314 | tmp = buf[7];
315 | buf[7] = 0;
316 | off = (unsigned int)strtoul(buf+3, NULL, 16);
317 | buf[7] = tmp;
318 |
319 | /* Initialize data_addr */
320 | if (first_line) {
321 | data_addr = off;
322 | first_line = 0;
323 | }
324 |
325 | /* Read the record type */
326 | tmp = buf[9];
327 | buf[9] = 0;
328 | type = (char)strtoul(buf+7, NULL, 16);
329 | buf[9] = tmp;
330 |
331 | /* If this is an EOF record, then make it so. */
332 | if (type == 1) {
333 | if (verbose >= 2)
334 | logerror("EOF on hexfile\n");
335 | break;
336 | }
337 |
338 | if (type != 0) {
339 | logerror("unsupported record type: %u\n", type);
340 | return -3;
341 | }
342 |
343 | if ((len * 2) + 11 > strlen(buf)) {
344 | logerror("record too short?\n");
345 | return -4;
346 | }
347 |
348 | /* FIXME check for _physically_ contiguous not just virtually
349 | * e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
350 | * memory so it's not really contiguous */
351 |
352 | /* flush the saved data if it's not contiguous,
353 | * or when we've buffered as much as we can.
354 | */
355 | if (data_len != 0
356 | && (off != (data_addr + data_len)
357 | /* || !merge */
358 | || (data_len + len) > sizeof(data))) {
359 | if (is_external)
360 | external = is_external(data_addr, data_len);
361 | rc = poke(context, data_addr, external, data, data_len);
362 | if (rc < 0)
363 | return -1;
364 | data_addr = off;
365 | data_len = 0;
366 | }
367 |
368 | /* append to saved data, flush later */
369 | for (idx = 0, cp = buf+9 ; idx < len ; idx += 1, cp += 2) {
370 | tmp = cp[2];
371 | cp[2] = 0;
372 | data[data_len + idx] = (uint8_t)strtoul(cp, NULL, 16);
373 | cp[2] = tmp;
374 | }
375 | data_len += len;
376 | }
377 |
378 |
379 | /* flush any data remaining */
380 | if (data_len != 0) {
381 | if (is_external)
382 | external = is_external(data_addr, data_len);
383 | rc = poke(context, data_addr, external, data, data_len);
384 | if (rc < 0)
385 | return -1;
386 | }
387 | return 0;
388 | }
389 |
390 | /*
391 | * Parse a binary image file and write it as is to the target.
392 | * Applies to Cypress BIX images for RAM or Cypress IIC images
393 | * for EEPROM.
394 | *
395 | * image - the BIX image file
396 | * context - for use by poke()
397 | * is_external - if non-null, used to check which segments go into
398 | * external memory (writable only by software loader)
399 | * poke - called with each memory segment; errors indicated
400 | * by returning negative values.
401 | *
402 | * Caller is responsible for halting CPU as needed, such as when
403 | * overwriting a second stage loader.
404 | */
405 | static int parse_bin(FILE *image, void *context,
406 | bool (*is_external)(uint32_t addr, size_t len), int (*poke)(void *context,
407 | uint32_t addr, bool external, const unsigned char *data, size_t len))
408 | {
409 | unsigned char data[4096];
410 | uint32_t data_addr = 0;
411 | size_t data_len = 0;
412 | int rc;
413 | bool external = false;
414 |
415 | for (;;) {
416 | data_len = fread(data, 1, 4096, image);
417 | if (data_len == 0)
418 | break;
419 | if (is_external)
420 | external = is_external(data_addr, data_len);
421 | rc = poke(context, data_addr, external, data, data_len);
422 | if (rc < 0)
423 | return -1;
424 | data_addr += (uint32_t)data_len;
425 | }
426 | return feof(image)?0:-1;
427 | }
428 |
429 | /*
430 | * Parse a Cypress IIC image file and invoke the poke() function on the
431 | * various segments for writing to RAM
432 | *
433 | * image - the IIC image file
434 | * context - for use by poke()
435 | * is_external - if non-null, used to check which segments go into
436 | * external memory (writable only by software loader)
437 | * poke - called with each memory segment; errors indicated
438 | * by returning negative values.
439 | *
440 | * Caller is responsible for halting CPU as needed, such as when
441 | * overwriting a second stage loader.
442 | */
443 | static int parse_iic(FILE *image, void *context,
444 | bool (*is_external)(uint32_t addr, size_t len),
445 | int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
446 | {
447 | unsigned char data[4096];
448 | uint32_t data_addr = 0;
449 | size_t data_len = 0, read_len;
450 | uint8_t block_header[4];
451 | int rc;
452 | bool external = false;
453 | long file_size, initial_pos;
454 |
455 | initial_pos = ftell(image);
456 | if (initial_pos < 0)
457 | return -1;
458 |
459 | if (fseek(image, 0L, SEEK_END) != 0)
460 | return -1;
461 | file_size = ftell(image);
462 | if (fseek(image, initial_pos, SEEK_SET) != 0)
463 | return -1;
464 | for (;;) {
465 | /* Ignore the trailing reset IIC data (5 bytes) */
466 | if (ftell(image) >= (file_size - 5))
467 | break;
468 | if (fread(&block_header, 1, sizeof(block_header), image) != 4) {
469 | logerror("unable to read IIC block header\n");
470 | return -1;
471 | }
472 | data_len = (block_header[0] << 8) + block_header[1];
473 | data_addr = (block_header[2] << 8) + block_header[3];
474 | if (data_len > sizeof(data)) {
475 | /* If this is ever reported as an error, switch to using malloc/realloc */
476 | logerror("IIC data block too small - please report this error to libusb.info\n");
477 | return -1;
478 | }
479 | read_len = fread(data, 1, data_len, image);
480 | if (read_len != data_len) {
481 | logerror("read error\n");
482 | return -1;
483 | }
484 | if (is_external)
485 | external = is_external(data_addr, data_len);
486 | rc = poke(context, data_addr, external, data, data_len);
487 | if (rc < 0)
488 | return -1;
489 | }
490 | return 0;
491 | }
492 |
493 | /* the parse call will be selected according to the image type */
494 | static int (*parse[IMG_TYPE_MAX])(FILE *image, void *context, bool (*is_external)(uint32_t addr, size_t len),
495 | int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
496 | = { parse_ihex, parse_iic, parse_bin };
497 |
498 | /*****************************************************************************/
499 |
500 | /*
501 | * For writing to RAM using a first (hardware) or second (software)
502 | * stage loader and 0xA0 or 0xA3 vendor requests
503 | */
504 | typedef enum {
505 | _undef = 0,
506 | internal_only, /* hardware first-stage loader */
507 | skip_internal, /* first phase, second-stage loader */
508 | skip_external /* second phase, second-stage loader */
509 | } ram_mode;
510 |
511 | struct ram_poke_context {
512 | libusb_device_handle *device;
513 | ram_mode mode;
514 | size_t total, count;
515 | };
516 |
517 | #define RETRY_LIMIT 5
518 |
519 | static int ram_poke(void *context, uint32_t addr, bool external,
520 | const unsigned char *data, size_t len)
521 | {
522 | struct ram_poke_context *ctx = (struct ram_poke_context*)context;
523 | int rc;
524 | unsigned retry = 0;
525 |
526 | switch (ctx->mode) {
527 | case internal_only: /* CPU should be stopped */
528 | if (external) {
529 | logerror("can't write %u bytes external memory at 0x%08x\n",
530 | (unsigned)len, addr);
531 | return -EINVAL;
532 | }
533 | break;
534 | case skip_internal: /* CPU must be running */
535 | if (!external) {
536 | if (verbose >= 2) {
537 | logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
538 | (unsigned)len, addr);
539 | }
540 | return 0;
541 | }
542 | break;
543 | case skip_external: /* CPU should be stopped */
544 | if (external) {
545 | if (verbose >= 2) {
546 | logerror("SKIP external RAM, %u bytes at 0x%08x\n",
547 | (unsigned)len, addr);
548 | }
549 | return 0;
550 | }
551 | break;
552 | case _undef:
553 | default:
554 | logerror("bug\n");
555 | return -EDOM;
556 | }
557 |
558 | ctx->total += len;
559 | ctx->count++;
560 |
561 | /* Retry this till we get a real error. Control messages are not
562 | * NAKed (just dropped) so time out means is a real problem.
563 | */
564 | while ((rc = ezusb_write(ctx->device,
565 | external ? "write external" : "write on-chip",
566 | external ? RW_MEMORY : RW_INTERNAL,
567 | addr, data, len)) < 0
568 | && retry < RETRY_LIMIT) {
569 | if (rc != LIBUSB_ERROR_TIMEOUT)
570 | break;
571 | retry += 1;
572 | }
573 | return rc;
574 | }
575 |
576 | /*
577 | * Load a Cypress Image file into target RAM.
578 | * See http://www.cypress.com/?docID=41351 (AN76405 PDF) for more info.
579 | */
580 | static int fx3_load_ram(libusb_device_handle *device, const char *path)
581 | {
582 | uint32_t dCheckSum, dExpectedCheckSum, dAddress, i, dLen, dLength;
583 | uint32_t* dImageBuf;
584 | unsigned char *bBuf, hBuf[4], blBuf[4], rBuf[4096];
585 | FILE *image;
586 | int ret = 0;
587 |
588 | image = fopen(path, "rb");
589 | if (image == NULL) {
590 | logerror("unable to open '%s' for input\n", path);
591 | return -2;
592 | } else if (verbose)
593 | logerror("open firmware image %s for RAM upload\n", path);
594 |
595 | // Read header
596 | if (fread(hBuf, sizeof(char), sizeof(hBuf), image) != sizeof(hBuf)) {
597 | logerror("could not read image header");
598 | ret = -3;
599 | goto exit;
600 | }
601 |
602 | // check "CY" signature byte and format
603 | if ((hBuf[0] != 'C') || (hBuf[1] != 'Y')) {
604 | logerror("image doesn't have a CYpress signature\n");
605 | ret = -3;
606 | goto exit;
607 | }
608 |
609 | // Check bImageType
610 | switch(hBuf[3]) {
611 | case 0xB0:
612 | if (verbose)
613 | logerror("normal FW binary %s image with checksum\n", (hBuf[2]&0x01)?"data":"executable");
614 | break;
615 | case 0xB1:
616 | logerror("security binary image is not currently supported\n");
617 | ret = -3;
618 | goto exit;
619 | case 0xB2:
620 | logerror("VID:PID image is not currently supported\n");
621 | ret = -3;
622 | goto exit;
623 | default:
624 | logerror("invalid image type 0x%02X\n", hBuf[3]);
625 | ret = -3;
626 | goto exit;
627 | }
628 |
629 | // Read the bootloader version
630 | if (verbose) {
631 | if ((ezusb_read(device, "read bootloader version", RW_INTERNAL, 0xFFFF0020, blBuf, 4) < 0)) {
632 | logerror("Could not read bootloader version\n");
633 | ret = -8;
634 | goto exit;
635 | }
636 | logerror("FX3 bootloader version: 0x%02X%02X%02X%02X\n", blBuf[3], blBuf[2], blBuf[1], blBuf[0]);
637 | }
638 |
639 | dCheckSum = 0;
640 | if (verbose)
641 | logerror("writing image...\n");
642 | while (1) {
643 | if ((fread(&dLength, sizeof(uint32_t), 1, image) != 1) || // read dLength
644 | (fread(&dAddress, sizeof(uint32_t), 1, image) != 1)) { // read dAddress
645 | logerror("could not read image");
646 | ret = -3;
647 | goto exit;
648 | }
649 | if (dLength == 0)
650 | break; // done
651 |
652 | // coverity[tainted_data]
653 | dImageBuf = (uint32_t*)calloc(dLength, sizeof(uint32_t));
654 | if (dImageBuf == NULL) {
655 | logerror("could not allocate buffer for image chunk\n");
656 | ret = -4;
657 | goto exit;
658 | }
659 |
660 | // read sections
661 | if (fread(dImageBuf, sizeof(uint32_t), dLength, image) != dLength) {
662 | logerror("could not read image");
663 | free(dImageBuf);
664 | ret = -3;
665 | goto exit;
666 | }
667 | for (i = 0; i < dLength; i++)
668 | dCheckSum += dImageBuf[i];
669 | dLength <<= 2; // convert to Byte length
670 | bBuf = (unsigned char*) dImageBuf;
671 |
672 | while (dLength > 0) {
673 | dLen = 4096; // 4K max
674 | if (dLen > dLength)
675 | dLen = dLength;
676 | if ((ezusb_write(device, "write firmware", RW_INTERNAL, dAddress, bBuf, dLen) < 0) ||
677 | (ezusb_read(device, "read firmware", RW_INTERNAL, dAddress, rBuf, dLen) < 0)) {
678 | logerror("R/W error\n");
679 | free(dImageBuf);
680 | ret = -5;
681 | goto exit;
682 | }
683 | // Verify data: rBuf with bBuf
684 | for (i = 0; i < dLen; i++) {
685 | if (rBuf[i] != bBuf[i]) {
686 | logerror("verify error");
687 | free(dImageBuf);
688 | ret = -6;
689 | goto exit;
690 | }
691 | }
692 |
693 | dLength -= dLen;
694 | bBuf += dLen;
695 | dAddress += dLen;
696 | }
697 | free(dImageBuf);
698 | }
699 |
700 | // read pre-computed checksum data
701 | if ((fread(&dExpectedCheckSum, sizeof(uint32_t), 1, image) != 1) ||
702 | (dCheckSum != dExpectedCheckSum)) {
703 | logerror("checksum error\n");
704 | ret = -7;
705 | goto exit;
706 | }
707 |
708 | // transfer execution to Program Entry
709 | if (!ezusb_fx3_jump(device, dAddress)) {
710 | ret = -6;
711 | }
712 |
713 | exit:
714 | fclose(image);
715 | return ret;
716 | }
717 |
718 | /*
719 | * Load a firmware file into target RAM. device is the open libusb
720 | * device, and the path is the name of the source file. Open the file,
721 | * parse the bytes, and write them in one or two phases.
722 | *
723 | * If stage == 0, this uses the first stage loader, built into EZ-USB
724 | * hardware but limited to writing on-chip memory or CPUCS. Everything
725 | * is written during one stage, unless there's an error such as the image
726 | * holding data that needs to be written to external memory.
727 | *
728 | * Otherwise, things are written in two stages. First the external
729 | * memory is written, expecting a second stage loader to have already
730 | * been loaded. Then file is re-parsed and on-chip memory is written.
731 | */
732 | int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, int img_type, int stage)
733 | {
734 | FILE *image;
735 | uint32_t cpucs_addr;
736 | bool (*is_external)(uint32_t off, size_t len);
737 | struct ram_poke_context ctx;
738 | int status;
739 | uint8_t iic_header[8] = { 0 };
740 | int ret = 0;
741 |
742 | if (fx_type == FX_TYPE_FX3)
743 | return fx3_load_ram(device, path);
744 |
745 | image = fopen(path, "rb");
746 | if (image == NULL) {
747 | logerror("%s: unable to open for input.\n", path);
748 | return -2;
749 | } else if (verbose > 1)
750 | logerror("open firmware image %s for RAM upload\n", path);
751 |
752 | if (img_type == IMG_TYPE_IIC) {
753 | if ( (fread(iic_header, 1, sizeof(iic_header), image) != sizeof(iic_header))
754 | || (((fx_type == FX_TYPE_FX2LP) || (fx_type == FX_TYPE_FX2)) && (iic_header[0] != 0xC2))
755 | || ((fx_type == FX_TYPE_AN21) && (iic_header[0] != 0xB2))
756 | || ((fx_type == FX_TYPE_FX1) && (iic_header[0] != 0xB6)) ) {
757 | logerror("IIC image does not contain executable code - cannot load to RAM.\n");
758 | ret = -1;
759 | goto exit;
760 | }
761 | }
762 |
763 | /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
764 | switch(fx_type) {
765 | case FX_TYPE_FX2LP:
766 | cpucs_addr = 0xe600;
767 | is_external = fx2lp_is_external;
768 | break;
769 | case FX_TYPE_FX2:
770 | cpucs_addr = 0xe600;
771 | is_external = fx2_is_external;
772 | break;
773 | default:
774 | cpucs_addr = 0x7f92;
775 | is_external = fx_is_external;
776 | break;
777 | }
778 |
779 | /* use only first stage loader? */
780 | if (stage == 0) {
781 | ctx.mode = internal_only;
782 |
783 | /* if required, halt the CPU while we overwrite its code/data */
784 | if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
785 | {
786 | ret = -1;
787 | goto exit;
788 | }
789 |
790 | /* 2nd stage, first part? loader was already uploaded */
791 | } else {
792 | ctx.mode = skip_internal;
793 |
794 | /* let CPU run; overwrite the 2nd stage loader later */
795 | if (verbose)
796 | logerror("2nd stage: write external memory\n");
797 | }
798 |
799 | /* scan the image, first (maybe only) time */
800 | ctx.device = device;
801 | ctx.total = ctx.count = 0;
802 | status = parse[img_type](image, &ctx, is_external, ram_poke);
803 | if (status < 0) {
804 | logerror("unable to upload %s\n", path);
805 | ret = status;
806 | goto exit;
807 | }
808 |
809 | /* second part of 2nd stage: rescan */
810 | // TODO: what should we do for non HEX images there?
811 | if (stage) {
812 | ctx.mode = skip_external;
813 |
814 | /* if needed, halt the CPU while we overwrite the 1st stage loader */
815 | if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
816 | {
817 | ret = -1;
818 | goto exit;
819 | }
820 |
821 | /* at least write the interrupt vectors (at 0x0000) for reset! */
822 | rewind(image);
823 | if (verbose)
824 | logerror("2nd stage: write on-chip memory\n");
825 | status = parse_ihex(image, &ctx, is_external, ram_poke);
826 | if (status < 0) {
827 | logerror("unable to completely upload %s\n", path);
828 | ret = status;
829 | goto exit;
830 | }
831 | }
832 |
833 | if (verbose && (ctx.count != 0)) {
834 | logerror("... WROTE: %d bytes, %d segments, avg %d\n",
835 | (int)ctx.total, (int)ctx.count, (int)(ctx.total/ctx.count));
836 | }
837 |
838 | /* if required, reset the CPU so it runs what we just uploaded */
839 | if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, true))
840 | ret = -1;
841 |
842 | exit:
843 | fclose(image);
844 | return ret;
845 | }
846 |
--------------------------------------------------------------------------------
/src/ezusb.h:
--------------------------------------------------------------------------------
1 | #ifndef ezusb_H
2 | #define ezusb_H
3 | /*
4 | * Copyright © 2001 Stephen Williams (steve@icarus.com)
5 | * Copyright © 2002 David Brownell (dbrownell@users.sourceforge.net)
6 | * Copyright © 2013 Federico Manzan (f.manzan@gmail.com)
7 | *
8 | * This source code is free software; you can redistribute it
9 | * and/or modify it in source code form under the terms of the GNU
10 | * General Public License as published by the Free Software
11 | * Foundation; either version 2 of the License, or (at your option)
12 | * any later version.
13 | *
14 | * This program is distributed in the hope that it will be useful,
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | * GNU General Public License for more details.
18 | *
19 | * You should have received a copy of the GNU General Public License
20 | * along with this program; if not, write to the Free Software
21 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
22 | */
23 |
24 | #if defined(_MSC_VER)
25 | #define __attribute__(x)
26 | #if defined(_PREFAST_)
27 | #pragma warning(disable:28193)
28 | #endif
29 | #endif
30 |
31 | #include
32 |
33 | #define FX_TYPE_UNDEFINED -1
34 | #define FX_TYPE_AN21 0 /* Original AnchorChips parts */
35 | #define FX_TYPE_FX1 1 /* Updated Cypress versions */
36 | #define FX_TYPE_FX2 2 /* USB 2.0 versions */
37 | #define FX_TYPE_FX2LP 3 /* Updated FX2 */
38 | #define FX_TYPE_FX3 4 /* USB 3.0 versions */
39 | #define FX_TYPE_MAX 5
40 | #define FX_TYPE_NAMES { "an21", "fx", "fx2", "fx2lp", "fx3" }
41 |
42 | #define IMG_TYPE_UNDEFINED -1
43 | #define IMG_TYPE_HEX 0 /* Intel HEX */
44 | #define IMG_TYPE_IIC 1 /* Cypress 8051 IIC */
45 | #define IMG_TYPE_BIX 2 /* Cypress 8051 BIX */
46 | #define IMG_TYPE_IMG 3 /* Cypress IMG format */
47 | #define IMG_TYPE_MAX 4
48 | #define IMG_TYPE_NAMES { "Intel HEX", "Cypress 8051 IIC", "Cypress 8051 BIX", "Cypress IMG format" }
49 |
50 | #ifdef __cplusplus
51 | extern "C" {
52 | #endif
53 |
54 | /*
55 | * Automatically identified devices (VID, PID, type, designation).
56 | * TODO: Could use some validation. Also where's the FX2?
57 | */
58 | typedef struct {
59 | uint16_t vid;
60 | uint16_t pid;
61 | int type;
62 | const char* designation;
63 | } fx_known_device;
64 |
65 | #define FX_KNOWN_DEVICES { \
66 | { 0x0547, 0x2122, FX_TYPE_AN21, "Cypress EZ-USB (2122S)" },\
67 | { 0x0547, 0x2125, FX_TYPE_AN21, "Cypress EZ-USB (2121S/2125S)" },\
68 | { 0x0547, 0x2126, FX_TYPE_AN21, "Cypress EZ-USB (2126S)" },\
69 | { 0x0547, 0x2131, FX_TYPE_AN21, "Cypress EZ-USB (2131Q/2131S/2135S)" },\
70 | { 0x0547, 0x2136, FX_TYPE_AN21, "Cypress EZ-USB (2136S)" },\
71 | { 0x0547, 0x2225, FX_TYPE_AN21, "Cypress EZ-USB (2225)" },\
72 | { 0x0547, 0x2226, FX_TYPE_AN21, "Cypress EZ-USB (2226)" },\
73 | { 0x0547, 0x2235, FX_TYPE_AN21, "Cypress EZ-USB (2235)" },\
74 | { 0x0547, 0x2236, FX_TYPE_AN21, "Cypress EZ-USB (2236)" },\
75 | { 0x04b4, 0x6473, FX_TYPE_FX1, "Cypress EZ-USB FX1" },\
76 | { 0x04b4, 0x8613, FX_TYPE_FX2LP, "Cypress EZ-USB FX2LP (68013A/68014A/68015A/68016A)" }, \
77 | { 0x04b4, 0x00f3, FX_TYPE_FX3, "Cypress FX3" },\
78 | }
79 |
80 | /*
81 | * This function uploads the firmware from the given file into RAM.
82 | * Stage == 0 means this is a single stage load (or the first of
83 | * two stages). Otherwise it's the second of two stages; the
84 | * caller having preloaded the second stage loader.
85 | *
86 | * The target processor is reset at the end of this upload.
87 | */
88 | extern int ezusb_load_ram(libusb_device_handle *device,
89 | const char *path, int fx_type, int img_type, int stage);
90 |
91 | /*
92 | * This function uploads the firmware from the given file into EEPROM.
93 | * This uses the right CPUCS address to terminate the EEPROM load with
94 | * a reset command where FX parts behave differently than FX2 ones.
95 | * The configuration byte is as provided here (zero for an21xx parts)
96 | * and the EEPROM type is set so that the microcontroller will boot
97 | * from it.
98 | *
99 | * The caller must have preloaded a second stage loader that knows
100 | * how to respond to the EEPROM write request.
101 | */
102 | extern int ezusb_load_eeprom(libusb_device_handle *device,
103 | const char *path, int fx_type, int img_type, int config);
104 |
105 | /* Verbosity level (default 1). Can be increased or decreased with options v/q */
106 | extern int verbose;
107 |
108 | #ifdef __cplusplus
109 | }
110 | #endif
111 |
112 | #endif
113 |
--------------------------------------------------------------------------------
/src/libsddc.c:
--------------------------------------------------------------------------------
1 | /*
2 | * libsddc.c - low level functions for wideband SDR receivers like
3 | * BBRF103, RX-666, RX888, HF103, etc
4 | *
5 | * Copyright (C) 2020 by Franco Venturi
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | *
20 | * SPDX-License-Identifier: GPL-3.0-or-later
21 | */
22 |
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | #include "libsddc.h"
29 | #include "logging.h"
30 | #include "usb_device.h"
31 | #include "streaming.h"
32 |
33 | typedef struct sddc sddc_t;
34 |
35 |
36 | /* internal functions */
37 | static int sddc_set_vhf_gpios(sddc_t *this);
38 |
39 |
40 | typedef struct sddc {
41 | enum SDDCStatus status;
42 | enum SDDCHWModel model;
43 | uint16_t firmware;
44 | enum RFMode rf_mode;
45 | usb_device_t *usb_device;
46 | streaming_t *streaming;
47 | int has_clock_source;
48 | int has_vhf_tuner;
49 | int hf_attenuator_levels;
50 | double hf_attenuation;
51 | double sample_rate;
52 | double tuner_frequency;
53 | double tuner_attenuation;
54 | double tuner_clock;
55 | double freq_corr_ppm;
56 | double frequency_range[2];
57 | } sddc_t;
58 |
59 |
60 | static const double DEFAULT_SAMPLE_RATE = 64e6; /* 64Msps */
61 | static const double DEFAULT_TUNER_FREQUENCY = 999e3; /* MW station in Turin */
62 | static const double DEFAULT_FREQ_CORR_PPM = 0.0; /* frequency correction PPM */
63 | static const double DEFAULT_HF_ATTENUATION = 0; /* no attenuation */
64 | static const double DEFAULT_TUNER_ATTENUATION = 0; /* no gain */
65 |
66 | static const double TUNER_CLOCK = 32E6; /* tuner expects 32MHz when running */
67 |
68 |
69 | /******************************
70 | * basic functions
71 | ******************************/
72 |
73 | int sddc_get_device_count()
74 | {
75 | return usb_device_count_devices();
76 | }
77 |
78 | int sddc_get_device_info(struct sddc_device_info **sddc_device_infos)
79 | {
80 | int ret_val = -1;
81 |
82 | /* no more info to add from usb_device_get_device_list() for now */
83 | struct usb_device_info *list;
84 | int ret = usb_device_get_device_list(&list);
85 | if (ret < 0) {
86 | goto FAIL0;
87 | }
88 |
89 | int count = ret;
90 | struct sddc_device_info *device_infos = (struct sddc_device_info *) malloc((count + 1) * sizeof(struct sddc_device_info));
91 | /* use the first element to save the pointer to the underlying list,
92 | so we can use it to free it later on */
93 | *((void **) device_infos) = list;
94 | device_infos++;
95 | for (int i = 0; i < count; ++i) {
96 | device_infos[i].manufacturer = list[i].manufacturer;
97 | device_infos[i].product = list[i].product;
98 | device_infos[i].serial_number = list[i].serial_number;
99 | }
100 |
101 | *sddc_device_infos = device_infos;
102 | ret_val = count;
103 |
104 | FAIL0:
105 | return ret_val;
106 | }
107 |
108 | int sddc_free_device_info(struct sddc_device_info *sddc_device_infos)
109 | {
110 | /* just free our structure and call usb_device_free_device_list() to free
111 | underlying data structure */
112 | /* retrieve the underlying usb_device list pointer first */
113 | sddc_device_infos--;
114 | struct usb_device_info *list = (struct usb_device_info *) *((void **) sddc_device_infos);
115 | free(sddc_device_infos);
116 | int ret = usb_device_free_device_list(list);
117 | return ret;
118 | }
119 |
120 | sddc_t *sddc_open(int index, const char* imagefile)
121 | {
122 | sddc_t *ret_val = 0;
123 |
124 | usb_device_t *usb_device = usb_device_open(index, imagefile, 0);
125 | if (usb_device == 0) {
126 | fprintf(stderr, "ERROR - usb_device_open() failed\n");
127 | goto FAIL0;
128 | }
129 | uint8_t data[4];
130 | int ret = usb_device_control(usb_device, TESTFX3, 0, 0, data, sizeof(data));
131 | if (ret < 0) {
132 | fprintf(stderr, "ERROR - usb_device_control(TESTFX3) failed\n");
133 | goto FAIL1;
134 | }
135 |
136 | sddc_t *this = (sddc_t *) malloc(sizeof(sddc_t));
137 | this->status = SDDC_STATUS_READY;
138 | this->model = (enum SDDCHWModel) data[0];
139 | this->firmware = (data[1] << 8) | data[2];
140 | this->rf_mode = HF_MODE;
141 | this->usb_device = usb_device;
142 | this->streaming = 0;
143 | switch (this->model) {
144 | case HW_BBRF103:
145 | case HW_RX888:
146 | this->has_clock_source = 1;
147 | this->has_vhf_tuner = 1;
148 | this->hf_attenuator_levels = 3;
149 | this->frequency_range[0] = 10e3;
150 | this->frequency_range[1] = 1750e6;
151 | break;
152 | case HW_HF103:
153 | this->has_clock_source = 0;
154 | this->has_vhf_tuner = 0;
155 | this->hf_attenuator_levels = 32;
156 | this->frequency_range[0] = 0;
157 | this->frequency_range[1] = 32e6;
158 | break;
159 | default:
160 | this->has_clock_source = 0;
161 | this->has_vhf_tuner = 0;
162 | this->hf_attenuator_levels = 0;
163 | this->frequency_range[0] = 0;
164 | this->frequency_range[1] = 0;
165 | break;
166 | }
167 | this->sample_rate = DEFAULT_SAMPLE_RATE; /* default sample rate */
168 | this->hf_attenuation = DEFAULT_HF_ATTENUATION; /* default HF attenuation */
169 | this->tuner_frequency = DEFAULT_TUNER_FREQUENCY; /* default tuner frequency */
170 | this->tuner_attenuation = DEFAULT_TUNER_ATTENUATION; /* default gain */
171 | this->tuner_clock = 0; /* tuner off */
172 | this->freq_corr_ppm = DEFAULT_FREQ_CORR_PPM; /* default frequency correction PPM */
173 |
174 | ret_val = this;
175 | return ret_val;
176 |
177 | FAIL1:
178 | usb_device_close(usb_device);
179 | FAIL0:
180 | return ret_val;
181 | }
182 |
183 | void sddc_close(sddc_t *this)
184 | {
185 | usb_device_close(this->usb_device);
186 | free(this);
187 | return;
188 | }
189 |
190 | enum SDDCStatus sddc_get_status(sddc_t *this)
191 | {
192 | return this->status;
193 | }
194 |
195 | enum SDDCHWModel sddc_get_hw_model(sddc_t *this)
196 | {
197 | return this->model;
198 | }
199 |
200 | uint16_t sddc_get_firmware(sddc_t *this)
201 | {
202 | return this->firmware;
203 | }
204 |
205 | const double *sddc_get_frequency_range(sddc_t *this)
206 | {
207 | return this->frequency_range;
208 | }
209 |
210 | enum RFMode sddc_get_rf_mode(sddc_t *this)
211 | {
212 | return this->rf_mode;
213 | }
214 |
215 | int sddc_set_rf_mode(sddc_t *this, enum RFMode rf_mode)
216 | {
217 | int ret;
218 | switch (rf_mode) {
219 | case HF_MODE:
220 | this->rf_mode = HF_MODE;
221 |
222 | /* stop tuner */
223 | ret = usb_device_control(this->usb_device, R82XXSTDBY, 0, 0, 0, 0);
224 | if (ret < 0) {
225 | fprintf(stderr, "ERROR - usb_device_control(R82XXSTDBY) failed\n");
226 | return -1;
227 | }
228 |
229 | /* switch to HF input and restore hf attenuation */
230 | ret = sddc_set_hf_attenuation(this, this->hf_attenuation);
231 | if (ret < 0) {
232 | fprintf(stderr, "ERROR - sddc_set_hf_attenuation() failed\n");
233 | return -1;
234 | }
235 |
236 | break;
237 | case VHF_MODE:
238 | if (!this->has_vhf_tuner) {
239 | fprintf(stderr, "WARNING - no VHF/UHF tuner found\n");
240 | return -1;
241 | }
242 | this->rf_mode = VHF_MODE;
243 |
244 | /* switch to VHF input */
245 | ret = sddc_set_vhf_gpios(this);
246 | if (ret < 0) {
247 | fprintf(stderr, "ERROR - sddc_set_vhf_gpios() failed\n");
248 | return -1;
249 | }
250 |
251 | /* initialize tuner */
252 | /* tuner reference frequency */
253 | double correction = 1e-6 * this->freq_corr_ppm * this->tuner_clock;
254 | uint32_t data = (uint32_t) (this->tuner_clock + correction);
255 | ret = usb_device_control(this->usb_device, R82XXINIT, 0, 0,
256 | (uint8_t *) &data, sizeof(data));
257 | if (ret < 0) {
258 | fprintf(stderr, "ERROR - usb_device_control(R82XXINIT) failed\n");
259 | return -1;
260 | }
261 |
262 | break;
263 | default:
264 | fprintf(stderr, "WARNING - invalid RF mode: %d\n", rf_mode);
265 | return -1;
266 | }
267 | return 0;
268 | }
269 |
270 |
271 | enum GPIOBits {
272 | GPIO_ADC_SHDN = 0x0020,
273 | GPIO_ADC_DITH = 0x0040,
274 | GPIO_ADC_RAND = 0x0080,
275 | GPIO_BIAS_HF = 0x0100,
276 | GPIO_BIAS_VHF = 0x0200,
277 | GPIO_LED_YELLOW = 0x0400,
278 | GPIO_LED_RED = 0x0800,
279 | GPIO_LED_BLUE = 0x1000,
280 | GPIO_ATT_SEL0 = 0x2000,
281 | GPIO_ATT_SEL1 = 0x4000,
282 | GPIO_VHF_EN = 0x8000
283 | };
284 |
285 | static const uint16_t GPIO_LED_SHIFT = 10;
286 |
287 |
288 | enum FWRegAddresses {
289 | FW_REG_R82XX_ATTENUATOR = 0x01, /* R8xx lna/mixer gain - range: 0-29 */
290 | FW_REG_R82XX_VGA = 0x02, /* R8xx vga gain - range: 0-15 */
291 | FW_REG_R82XX_SIDEBAND = 0x03, /* R8xx sideband - {0,1} */
292 | FW_REG_R82XX_HARMONIC = 0x04, /* R8xx harmonic - {0,1} */
293 | FW_REG_DAT31_ATT = 0x0a, /* DAT-31 att - range: 0-63 */
294 | FW_REG_AD8340_VGA = 0x0b, /* AD8340 chip vga - range: 0-255 */
295 | FW_REG_PRESELECTOR = 0x0c /* preselector - range: 0-2 */
296 | };
297 |
298 |
299 | /*****************
300 | * LED functions *
301 | *****************/
302 | int sddc_led_on(sddc_t *this, uint8_t led_pattern)
303 | {
304 | if (led_pattern & ~(LED_YELLOW | LED_RED | LED_BLUE)) {
305 | fprintf(stderr, "ERROR - invalid LED pattern: 0x%02x\n", led_pattern);
306 | return -1;
307 | }
308 | return usb_device_gpio_on(this->usb_device, (uint16_t) led_pattern << GPIO_LED_SHIFT);
309 | }
310 |
311 | int sddc_led_off(sddc_t *this, uint8_t led_pattern)
312 | {
313 | if (led_pattern & ~(LED_YELLOW | LED_RED | LED_BLUE)) {
314 | fprintf(stderr, "ERROR - invalid LED pattern: 0x%02x\n", led_pattern);
315 | return -1;
316 | }
317 | return usb_device_gpio_off(this->usb_device, (uint16_t) led_pattern << GPIO_LED_SHIFT);
318 | }
319 |
320 | int sddc_led_toggle(sddc_t *this, uint8_t led_pattern)
321 | {
322 | if (led_pattern & ~(LED_YELLOW | LED_RED | LED_BLUE)) {
323 | fprintf(stderr, "ERROR - invalid LED pattern: 0x%02x\n", led_pattern);
324 | return -1;
325 | }
326 | return usb_device_gpio_toggle(this->usb_device, (uint16_t) led_pattern << GPIO_LED_SHIFT);
327 | }
328 |
329 |
330 | /*****************
331 | * ADC functions *
332 | *****************/
333 | int sddc_get_adc_dither(sddc_t *this)
334 | {
335 | return (usb_device_gpio_get(this->usb_device) & GPIO_ADC_DITH) != 0;
336 | }
337 |
338 | int sddc_set_adc_dither(sddc_t *this, int dither)
339 | {
340 | if (dither) {
341 | return usb_device_gpio_on(this->usb_device, GPIO_ADC_DITH);
342 | } else {
343 | return usb_device_gpio_off(this->usb_device, GPIO_ADC_DITH);
344 | }
345 | }
346 |
347 | int sddc_get_adc_random(sddc_t *this)
348 | {
349 | return (usb_device_gpio_get(this->usb_device) & GPIO_ADC_RAND) != 0;
350 | }
351 |
352 | int sddc_set_adc_random(sddc_t *this, int random)
353 | {
354 | if (random) {
355 | return usb_device_gpio_on(this->usb_device, GPIO_ADC_RAND);
356 | } else {
357 | return usb_device_gpio_off(this->usb_device, GPIO_ADC_RAND);
358 | }
359 | }
360 |
361 |
362 | /**********************
363 | * HF block functions *
364 | **********************/
365 | double sddc_get_hf_attenuation(sddc_t *this)
366 | {
367 | return this->hf_attenuation;
368 | }
369 |
370 | int sddc_set_hf_attenuation(sddc_t *this, double attenuation)
371 | {
372 | if (this->hf_attenuator_levels == 0) {
373 | /* no attenuator */
374 | return 0;
375 | } else if (this->hf_attenuator_levels == 3) {
376 | /* old style attenuator with just 0dB, 10dB, and 20Db */
377 | uint16_t bit_pattern = 0;
378 | switch ((int) attenuation) {
379 | case 0:
380 | bit_pattern = GPIO_ATT_SEL1;
381 | break;
382 | case 10:
383 | bit_pattern = GPIO_ATT_SEL0 | GPIO_ATT_SEL1;
384 | break;
385 | case 20:
386 | bit_pattern = GPIO_ATT_SEL0;
387 | break;
388 | default:
389 | fprintf(stderr, "ERROR - invalid HF attenuation: %lf\n", attenuation);
390 | return -1;
391 | }
392 | this->hf_attenuation = attenuation;
393 | return usb_device_gpio_set(this->usb_device, bit_pattern,
394 | GPIO_ATT_SEL0 | GPIO_ATT_SEL1);
395 | } else if (this->hf_attenuator_levels == 32) {
396 | /* new style attenuator with 1dB increments */
397 | if (attenuation < 0.0 || attenuation > this->hf_attenuator_levels - 1) {
398 | fprintf(stderr, "ERROR - invalid HF attenuation: %lf\n", attenuation);
399 | return -1;
400 | }
401 | this->hf_attenuation = attenuation;
402 | uint16_t dat31_att = (this->hf_attenuator_levels - 1 - (int) attenuation);
403 | return usb_device_set_fw_register(this->usb_device, FW_REG_DAT31_ATT,
404 | dat31_att);
405 | }
406 |
407 | /* should never get here */
408 | fprintf(stderr, "ERROR - invalid number of HF attenuator levels: %d\n",
409 | this->hf_attenuator_levels);
410 | return -1;
411 | }
412 |
413 | int sddc_get_hf_bias(sddc_t *this)
414 | {
415 | return (usb_device_gpio_get(this->usb_device) & GPIO_BIAS_HF) != 0;
416 | }
417 |
418 | int sddc_set_hf_bias(sddc_t *this, int bias)
419 | {
420 | if (bias) {
421 | return usb_device_gpio_on(this->usb_device, GPIO_BIAS_HF);
422 | } else {
423 | return usb_device_gpio_off(this->usb_device, GPIO_BIAS_HF);
424 | }
425 | }
426 |
427 |
428 | /*****************************************
429 | * VHF block and VHF/UHF tuner functions *
430 | *****************************************/
431 | double sddc_get_tuner_frequency(sddc_t *this)
432 | {
433 | return this->tuner_frequency;
434 | }
435 |
436 | int sddc_set_tuner_frequency(sddc_t *this, double frequency)
437 | {
438 | uint64_t data = (uint64_t) frequency;
439 | int ret = usb_device_control(this->usb_device, R82XXTUNE, 0, 0,
440 | (uint8_t *) &data, sizeof(data));
441 | if (ret < 0) {
442 | fprintf(stderr, "ERROR - usb_device_control(R82XXTUNE) failed\n");
443 | return -1;
444 | }
445 | this->tuner_frequency = frequency;
446 | return 0;
447 | }
448 |
449 |
450 | /* tuner attenuations - LNA/mixer */
451 | static const double tuner_rf_attenuations_table[] = {
452 | 0.0, 0.9, 1.4, 2.7, 3.7, 7.7, 8.7, 12.5, 14.4, 15.7, 16.6, 19.7, 20.7,
453 | 22.9, 25.4, 28.0, 29.7, 32.8, 33.8, 36.4, 37.2, 38.6, 40.2, 42.1, 43.4,
454 | 43.9, 44.5, 48.0, 49.6
455 | };
456 |
457 | int sddc_get_tuner_rf_attenuations(sddc_t *this __attribute__((unused)),
458 | const double *attenuations[])
459 | {
460 | *attenuations = tuner_rf_attenuations_table;
461 | return sizeof(tuner_rf_attenuations_table) / sizeof(tuner_rf_attenuations_table[0]);
462 | }
463 |
464 | double sddc_get_tuner_rf_attenuation(sddc_t *this)
465 | {
466 | uint16_t r82xx_attenuator = usb_device_get_fw_register(this->usb_device,
467 | FW_REG_R82XX_ATTENUATOR);
468 | return tuner_rf_attenuations_table[(int) r82xx_attenuator];
469 | }
470 |
471 | int sddc_set_tuner_rf_attenuation(sddc_t *this, double attenuation)
472 | {
473 | int rf_attenuation_table_size = sizeof(tuner_rf_attenuations_table) /
474 | sizeof(tuner_rf_attenuations_table[0]);
475 | uint16_t idx = 0;
476 | double idx_att = fabs(attenuation - tuner_rf_attenuations_table[idx]);
477 | for (int i = 1; i < rf_attenuation_table_size; ++i) {
478 | double att = fabs(attenuation - tuner_rf_attenuations_table[i]);
479 | if (att < idx_att) {
480 | idx = i;
481 | idx_att = att;
482 | }
483 | }
484 |
485 | int ret = usb_device_set_fw_register(this->usb_device,
486 | FW_REG_R82XX_ATTENUATOR, idx);
487 | if (ret < 0) {
488 | fprintf(stderr, "ERROR - usb_device_set_fw_register(FW_REG_R82XX_ATTENUATOR) failed\n");
489 | return -1;
490 | }
491 |
492 | fprintf(stderr, "INFO - RF tuner attenuation set to %.1f\n",
493 | tuner_rf_attenuations_table[idx]);
494 | return 0;
495 | }
496 |
497 |
498 | /* tuner attenuations - VGA */
499 | static const double tuner_if_attenuations_table[] = {
500 | -4.7, -2.1, 0.5, 3.5, 7.7, 11.2, 13.6, 14.9, 16.3, 19.5, 23.1, 26.5,
501 | 30.0, 33.7, 37.2, 40.8
502 | };
503 |
504 | int sddc_get_tuner_if_attenuations(sddc_t *this __attribute__((unused)),
505 | const double *attenuations[])
506 | {
507 | *attenuations = tuner_if_attenuations_table;
508 | return sizeof(tuner_if_attenuations_table) / sizeof(tuner_if_attenuations_table[0]);
509 | }
510 |
511 | double sddc_get_tuner_if_attenuation(sddc_t *this)
512 | {
513 | uint16_t r82xx_vga = usb_device_get_fw_register(this->usb_device,
514 | FW_REG_R82XX_VGA);
515 | return tuner_if_attenuations_table[(int) r82xx_vga];
516 | }
517 |
518 | int sddc_set_tuner_if_attenuation(sddc_t *this, double attenuation)
519 | {
520 | int if_attenuation_table_size = sizeof(tuner_if_attenuations_table) /
521 | sizeof(tuner_if_attenuations_table[0]);
522 | uint16_t idx = 0;
523 | double idx_att = fabs(attenuation - tuner_if_attenuations_table[idx]);
524 | for (int i = 1; i < if_attenuation_table_size; ++i) {
525 | double att = fabs(attenuation - tuner_if_attenuations_table[i]);
526 | if (att < idx_att) {
527 | idx = i;
528 | idx_att = att;
529 | }
530 | }
531 |
532 | int ret = usb_device_set_fw_register(this->usb_device, FW_REG_R82XX_VGA, idx);
533 | if (ret < 0) {
534 | fprintf(stderr, "ERROR - usb_device_set_fw_register(FW_REG_R82XX_VGA) failed\n");
535 | return -1;
536 | }
537 |
538 | fprintf(stderr, "INFO - IF tuner attenuation set to %.1f\n",
539 | tuner_if_attenuations_table[idx]);
540 | return 0;
541 | }
542 |
543 | int sddc_get_vhf_bias(sddc_t *this)
544 | {
545 | return (usb_device_gpio_get(this->usb_device) & GPIO_BIAS_VHF) != 0;
546 | }
547 |
548 | int sddc_set_vhf_bias(sddc_t *this, int bias)
549 | {
550 | if (bias) {
551 | return usb_device_gpio_on(this->usb_device, GPIO_BIAS_VHF);
552 | } else {
553 | return usb_device_gpio_off(this->usb_device, GPIO_BIAS_VHF);
554 | }
555 | }
556 |
557 |
558 | /******************************
559 | * streaming related functions
560 | ******************************/
561 | int sddc_set_sample_rate(sddc_t *this, double sample_rate)
562 | {
563 | /* no checks yet */
564 | this->sample_rate = sample_rate;
565 |
566 | return 0;
567 | }
568 |
569 | int sddc_set_async_params(sddc_t *this, uint32_t frame_size,
570 | uint32_t num_frames, sddc_read_async_cb_t callback,
571 | void *callback_context)
572 | {
573 | if (this->streaming) {
574 | fprintf(stderr, "ERROR - sddc_set_async_params() failed: streaming already configured\n");
575 | return -1;
576 | }
577 |
578 | this->streaming = streaming_open_async(this->usb_device, frame_size,
579 | num_frames, callback,
580 | callback_context);
581 | if (this->streaming == 0) {
582 | fprintf(stderr, "ERROR - streaming_open_async() failed\n");
583 | return -1;
584 | }
585 |
586 | return 0;
587 | }
588 |
589 | int sddc_start_streaming(sddc_t *this)
590 | {
591 | if (this->status != SDDC_STATUS_READY) {
592 | fprintf(stderr, "ERROR - sddc_start_streaming() called with SDR status not READY: %d\n", this->status);
593 | return -1;
594 | }
595 |
596 | /* ADC sampling frequency */
597 | double correction = 1e-6 * this->freq_corr_ppm * this->sample_rate;
598 | uint32_t data = (uint32_t) (this->sample_rate + correction);
599 |
600 | int ret = usb_device_control(this->usb_device, STARTADC, 0, 0,
601 | (uint8_t *) &data, sizeof(data));
602 | if (ret < 0) {
603 | fprintf(stderr, "ERROR - usb_device_control(STARTADC) failed\n");
604 | return -1;
605 | }
606 |
607 | /* initialize tuner */
608 | if (this->rf_mode == VHF_MODE) {
609 | /* tuner reference frequency */
610 | double correction = 1e-6 * this->freq_corr_ppm * TUNER_CLOCK;
611 | uint32_t data = (uint32_t) (TUNER_CLOCK + correction);
612 |
613 | int ret = usb_device_control(this->usb_device, R82XXINIT, 0, 0,
614 | (uint8_t *) &data, sizeof(data));
615 | if (ret < 0) {
616 | fprintf(stderr, "ERROR - usb_device_control(R82XXINIT) failed\n");
617 | return -1;
618 | }
619 | }
620 |
621 | /* start async streaming */
622 | if (this->streaming) {
623 | streaming_set_sample_rate(this->streaming, (uint32_t) this->sample_rate);
624 | int ret = streaming_start(this->streaming);
625 | if (ret < 0) {
626 | fprintf(stderr, "ERROR - streaming_start() failed\n");
627 | return -1;
628 | }
629 | }
630 |
631 | /* start the producer */
632 | ret = usb_device_control(this->usb_device, STARTFX3, 0, 0, 0, 0);
633 | if (ret < 0) {
634 | fprintf(stderr, "ERROR - usb_device_control(STARTFX3) failed\n");
635 | return -1;
636 | }
637 |
638 | /* all good */
639 | this->status = SDDC_STATUS_STREAMING;
640 | return 0;
641 | }
642 |
643 | int sddc_handle_events(sddc_t *this)
644 | {
645 | return usb_device_handle_events(this->usb_device);
646 | }
647 |
648 | int sddc_stop_streaming(sddc_t *this)
649 | {
650 | if (this->status != SDDC_STATUS_STREAMING) {
651 | fprintf(stderr, "ERROR - sddc_stop_streaming() called with SDR status not STREAMING: %d\n", this->status);
652 | return -1;
653 | }
654 |
655 | /* stop the producer */
656 | int ret = usb_device_control(this->usb_device, STOPFX3, 0, 0, 0, 0);
657 | if (ret < 0) {
658 | fprintf(stderr, "ERROR - usb_device_control(STOPFX3) failed\n");
659 | return -1;
660 | }
661 |
662 | /* stop async streaming */
663 | if (this->streaming) {
664 | int ret = streaming_stop(this->streaming);
665 | if (ret < 0) {
666 | fprintf(stderr, "ERROR - streaming_stop() failed\n");
667 | return -1;
668 | }
669 |
670 | streaming_close(this->streaming);
671 | }
672 |
673 | /* stop tuner */
674 | if (this->rf_mode == VHF_MODE) {
675 | int ret = usb_device_control(this->usb_device, R82XXSTDBY, 0, 0, 0, 0);
676 | if (ret < 0) {
677 | fprintf(stderr, "ERROR - usb_device_control(R82XXSTDBY) failed\n");
678 | return -1;
679 | }
680 | }
681 |
682 | /* stop ADC */
683 | ret = usb_device_gpio_on(this->usb_device, GPIO_ADC_SHDN);
684 | if (ret < 0) {
685 | fprintf(stderr, "ERROR - usb_device_gpio_on(ADC_SHDN) failed\n");
686 | return -1;
687 | }
688 |
689 | /* all good */
690 | this->status = SDDC_STATUS_READY;
691 | return 0;
692 | }
693 |
694 | int sddc_reset_status(sddc_t *this)
695 | {
696 | int ret = streaming_reset_status(this->streaming);
697 | if (ret < 0) {
698 | fprintf(stderr, "ERROR - streaming_reset_status() failed\n");
699 | return -1;
700 | }
701 | return 0;
702 | }
703 |
704 | int sddc_read_sync(sddc_t *this, uint8_t *data, int length, int *transferred)
705 | {
706 | return streaming_read_sync(this->streaming, data, length, transferred);
707 | }
708 |
709 |
710 | /******************************
711 | * Misc functions
712 | ******************************/
713 | double sddc_get_frequency_correction(sddc_t *this)
714 | {
715 | return this->freq_corr_ppm;
716 | }
717 |
718 | int sddc_set_frequency_correction(sddc_t *this, double correction)
719 | {
720 | if (this->status == SDDC_STATUS_STREAMING) {
721 | fprintf(stderr, "ERROR - sddc_set_frequency_correction() failed - device is streaming\n");
722 | return -1;
723 | }
724 | this->freq_corr_ppm = correction;
725 | return 0;
726 | }
727 |
728 |
729 | /* internal functions */
730 | /* helper method to configure GPIOs for VHF */
731 | int sddc_set_vhf_gpios(sddc_t* this) {
732 | return usb_device_gpio_set(this->usb_device, 0, GPIO_ATT_SEL0 | GPIO_ATT_SEL1);
733 | }
734 |
--------------------------------------------------------------------------------
/src/logging.c:
--------------------------------------------------------------------------------
1 | /*
2 | * logging.c - logging functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #include
23 | #include
24 |
25 | #include "logging.h"
26 |
27 |
28 | void log_error(const char *error_message, const char *function,
29 | const char *file, int line) {
30 | fprintf(stderr, "ERROR - %s in %s at %s:%d\n", error_message, function,
31 | file, line);
32 | return;
33 | }
34 |
35 | void log_usb_error(int usb_error_code, const char *function, const char *file,
36 | int line) {
37 | fprintf(stderr, "ERROR - USB error %s in %s at %s:%d\n",
38 | libusb_error_name(usb_error_code), function, file, line);
39 | return;
40 | }
41 |
42 | void log_usb_warning(int usb_error_code, const char *function, const char *file,
43 | int line) {
44 | fprintf(stderr, "WARNING - USB warning %s in %s at %s:%d\n",
45 | libusb_error_name(usb_error_code), function, file, line);
46 | return;
47 | }
48 |
--------------------------------------------------------------------------------
/src/logging.h:
--------------------------------------------------------------------------------
1 | /*
2 | * logging.h - logging functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #ifndef __LOGGING_H
23 | #define __LOGGING_H
24 |
25 | #include
26 |
27 |
28 | #ifdef __cplusplus
29 | extern "C" {
30 | #endif
31 |
32 | void log_error(const char *error_message, const char *function,
33 | const char *file, int line);
34 | void log_usb_error(int usb_error_code, const char *function, const char *file,
35 | int line);
36 | void log_usb_warning(int usb_error_code, const char *function, const char *file,
37 | int line);
38 |
39 | #ifdef __cplusplus
40 | }
41 | #endif
42 |
43 | #endif /* __LOGGING_H */
44 |
--------------------------------------------------------------------------------
/src/sddc_stream_test.c:
--------------------------------------------------------------------------------
1 | /*
2 | * sddc_stream_test - simple stream test program for libsddc
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | #include "libsddc.h"
29 | #include "wavewrite.h"
30 |
31 |
32 | static void count_bytes_callback(uint32_t data_size, uint8_t *data,
33 | void *context);
34 |
35 | static unsigned long long received_samples = 0;
36 | static unsigned long long total_samples = 0;
37 | static int num_callbacks;
38 | static int16_t *sampleData = 0;
39 | static int runtime = 3000;
40 | static struct timespec clk_start, clk_end;
41 | static int stop_reception = 0;
42 |
43 | static double clk_diff() {
44 | return ((double)clk_end.tv_sec + 1.0e-9*clk_end.tv_nsec) -
45 | ((double)clk_start.tv_sec + 1.0e-9*clk_start.tv_nsec);
46 | }
47 |
48 |
49 | int main(int argc, char **argv)
50 | {
51 | if (argc < 3) {
52 | fprintf(stderr, "usage: %s [ []\n", argv[0]);
53 | return -1;
54 | }
55 | char *imagefile = argv[1];
56 | const char *outfilename = 0;
57 | double sample_rate = 0.0;
58 | sscanf(argv[2], "%lf", &sample_rate);
59 | if (3 < argc)
60 | runtime = atoi(argv[3]);
61 | if (4 < argc)
62 | outfilename = argv[4];
63 |
64 | if (sample_rate <= 0) {
65 | fprintf(stderr, "ERROR - given samplerate '%f' should be > 0\n", sample_rate);
66 | return -1;
67 | }
68 |
69 | int ret_val = -1;
70 |
71 | sddc_t *sddc = sddc_open(0, imagefile);
72 | if (sddc == 0) {
73 | fprintf(stderr, "ERROR - sddc_open() failed\n");
74 | return -1;
75 | }
76 |
77 | if (sddc_set_sample_rate(sddc, sample_rate) < 0) {
78 | fprintf(stderr, "ERROR - sddc_set_sample_rate() failed\n");
79 | goto DONE;
80 | }
81 |
82 | if (sddc_set_async_params(sddc, 0, 0, count_bytes_callback, sddc) < 0) {
83 | fprintf(stderr, "ERROR - sddc_set_async_params() failed\n");
84 | goto DONE;
85 | }
86 |
87 | if (sddc_set_rf_mode(sddc, HF_MODE) < 0) {
88 | fprintf(stderr, "ERROR - sddc_set_rf_mode failed\n");
89 | goto DONE;
90 | }
91 |
92 | /* TODO - double check */
93 | if (sddc_set_hf_bias(sddc, 1) < 0) {
94 | fprintf(stderr, "ERROR - sddc_set_hf_bias failed\n");
95 | goto DONE;
96 | }
97 |
98 | received_samples = 0;
99 | num_callbacks = 0;
100 | if (sddc_start_streaming(sddc) < 0) {
101 | fprintf(stderr, "ERROR - sddc_start_streaming() failed\n");
102 | return -1;
103 | }
104 |
105 | fprintf(stderr, "started streaming .. for %d ms ..\n", runtime);
106 | total_samples = (unsigned long long)(runtime * sample_rate / 1000.0);
107 |
108 | if (outfilename)
109 | sampleData = (int16_t*)malloc(total_samples * sizeof(int16_t));
110 |
111 | /* todo: move this into a thread */
112 | stop_reception = 0;
113 | clock_gettime(CLOCK_REALTIME, &clk_start);
114 | while (!stop_reception)
115 | sddc_handle_events(sddc);
116 |
117 | fprintf(stderr, "finished. now stop streaming ..\n");
118 | if (sddc_stop_streaming(sddc) < 0) {
119 | fprintf(stderr, "ERROR - sddc_stop_streaming() failed\n");
120 | return -1;
121 | }
122 |
123 | double dur = clk_diff();
124 | fprintf(stderr, "received=%llu 16-Bit samples in %d callbacks\n", received_samples, num_callbacks);
125 | fprintf(stderr, "run for %f sec\n", dur);
126 | fprintf(stderr, "approx. samplerate is %f kSamples/sec\n", received_samples / (1000.0*dur) );
127 |
128 | if (outfilename && sampleData && received_samples) {
129 | FILE * f = fopen(outfilename, "wb");
130 | if (f) {
131 | fprintf(stderr, "saving received real samples to file ..\n");
132 | waveWriteHeader( (unsigned)(0.5 + sample_rate), 0U /*frequency*/, 16 /*bitsPerSample*/, 1 /*numChannels*/, f);
133 | for ( unsigned long long off = 0; off + 65536 < received_samples; off += 65536 )
134 | waveWriteSamples(f, sampleData + off, 65536, 0 /*needCleanData*/);
135 | waveFinalizeHeader(f);
136 | fclose(f);
137 | }
138 | }
139 |
140 | /* done - all good */
141 | ret_val = 0;
142 |
143 | DONE:
144 | sddc_close(sddc);
145 |
146 | return ret_val;
147 | }
148 |
149 | static void count_bytes_callback(uint32_t data_size,
150 | uint8_t *data,
151 | void *context __attribute__((unused)) )
152 | {
153 | if (stop_reception)
154 | return;
155 | ++num_callbacks;
156 | unsigned N = data_size / sizeof(int16_t);
157 | if ( received_samples + N < total_samples ) {
158 | if (sampleData)
159 | memcpy( sampleData+received_samples, data, data_size);
160 | received_samples += N;
161 | }
162 | else {
163 | clock_gettime(CLOCK_REALTIME, &clk_end);
164 | stop_reception = 1;
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/src/sddc_test.c:
--------------------------------------------------------------------------------
1 | /*
2 | * sddc_test - simple test program for libsddc
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #include
23 | #include
24 |
25 | #include "libsddc.h"
26 |
27 |
28 | static void blink_led(sddc_t *sddc, uint8_t color);
29 |
30 |
31 | int main(int argc, char **argv)
32 | {
33 | if (argc != 2) {
34 | fprintf(stderr, "usage: %s \n", argv[0]);
35 | return -1;
36 | }
37 | char *imagefile = argv[1];
38 |
39 | /* count devices */
40 | int count = sddc_get_device_count();
41 | if (count < 0) {
42 | fprintf(stderr, "ERROR - sddc_get_device_count() failed\n");
43 | return -1;
44 | }
45 | printf("device count=%d\n", count);
46 |
47 | /* get device info */
48 | struct sddc_device_info *sddc_device_infos;
49 | count = sddc_get_device_info(&sddc_device_infos);
50 | if (count < 0) {
51 | fprintf(stderr, "ERROR - sddc_get_device_info() failed\n");
52 | return -1;
53 | }
54 | for (int i = 0; i < count; ++i) {
55 | printf("%d - manufacturer=\"%s\" product=\"%s\" serial number=\"%s\"\n",
56 | i, sddc_device_infos[i].manufacturer, sddc_device_infos[i].product,
57 | sddc_device_infos[i].serial_number);
58 | }
59 | sddc_free_device_info(sddc_device_infos);
60 |
61 | /* open and close device */
62 | sddc_t *sddc = sddc_open(0, imagefile);
63 | if (sddc == 0) {
64 | fprintf(stderr, "ERROR - sddc_open() failed\n");
65 | return -1;
66 | }
67 |
68 | /* blink the LEDs */
69 | printf("blinking the red LED\n");
70 | blink_led(sddc, LED_RED);
71 | printf("blinking the yellow LED\n");
72 | blink_led(sddc, LED_YELLOW);
73 | printf("blinking the blue LED\n");
74 | blink_led(sddc, LED_BLUE);
75 |
76 | /* done */
77 | sddc_close(sddc);
78 |
79 | return 0;
80 | }
81 |
82 | static void blink_led(sddc_t *sddc, uint8_t color)
83 | {
84 | for (int i = 0; i < 5; ++i) {
85 | int ret = sddc_led_on(sddc, color);
86 | if (ret < 0) {
87 | fprintf(stderr, "ERROR - sddc_led_on(%02x) failed\n", color);
88 | return;
89 | }
90 | sleep(1);
91 | ret = sddc_led_off(sddc, color);
92 | if (ret < 0) {
93 | fprintf(stderr, "ERROR - sddc_led_off(%02x) failed\n", color);
94 | return;
95 | }
96 | sleep(1);
97 | }
98 | return;
99 | }
100 |
--------------------------------------------------------------------------------
/src/sddc_vhf_stream_test.c:
--------------------------------------------------------------------------------
1 | /*
2 | * sddc_vhf_stream_test - simple VHF/UHF stream test program for libsddc
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | #include "libsddc.h"
29 | #include "wavewrite.h"
30 |
31 |
32 | static void count_bytes_callback(uint32_t data_size, uint8_t *data,
33 | void *context);
34 |
35 | static unsigned long long received_samples = 0;
36 | static unsigned long long total_samples = 0;
37 | static int num_callbacks;
38 | static int16_t *sampleData = 0;
39 | static int runtime = 3000;
40 | static struct timespec clk_start, clk_end;
41 | static int stop_reception = 0;
42 |
43 | static double clk_diff() {
44 | return ((double)clk_end.tv_sec + 1.0e-9*clk_end.tv_nsec) -
45 | ((double)clk_start.tv_sec + 1.0e-9*clk_start.tv_nsec);
46 | }
47 |
48 |
49 | int main(int argc, char **argv)
50 | {
51 | if (argc < 3) {
52 | fprintf(stderr, "usage: %s [ []\n", argv[0]);
53 | return -1;
54 | }
55 | char *imagefile = argv[1];
56 | const char *outfilename = 0;
57 | double sample_rate = 0.0;
58 |
59 | double vhf_frequency = 100e6;
60 | double vhf_attenuation = 20; /* 20dB attenuation */
61 |
62 | sscanf(argv[2], "%lf", &sample_rate);
63 | if (3 < argc)
64 | runtime = atoi(argv[3]);
65 | if (4 < argc)
66 | outfilename = argv[4];
67 |
68 | if (sample_rate <= 0) {
69 | fprintf(stderr, "ERROR - given samplerate '%f' should be > 0\n", sample_rate);
70 | return -1;
71 | }
72 |
73 | int ret_val = -1;
74 |
75 | sddc_t *sddc = sddc_open(0, imagefile);
76 | if (sddc == 0) {
77 | fprintf(stderr, "ERROR - sddc_open() failed\n");
78 | return -1;
79 | }
80 |
81 | if (sddc_set_sample_rate(sddc, sample_rate) < 0) {
82 | fprintf(stderr, "ERROR - sddc_set_sample_rate() failed\n");
83 | goto DONE;
84 | }
85 |
86 | if (sddc_set_async_params(sddc, 0, 0, count_bytes_callback, sddc) < 0) {
87 | fprintf(stderr, "ERROR - sddc_set_async_params() failed\n");
88 | goto DONE;
89 | }
90 |
91 | if (sddc_set_rf_mode(sddc, VHF_MODE) < 0) {
92 | fprintf(stderr, "ERROR - sddc_set_rf_mode() failed\n");
93 | goto DONE;
94 | }
95 |
96 | if (sddc_set_tuner_frequency(sddc, vhf_frequency) < 0) {
97 | fprintf(stderr, "ERROR - sddc_set_vhf_frequency() failed\n");
98 | goto DONE;
99 | }
100 |
101 | if (sddc_set_tuner_rf_attenuation(sddc, vhf_attenuation) < 0) {
102 | fprintf(stderr, "ERROR - sddc_set_tuner_rf_attenuation() failed\n");
103 | goto DONE;
104 | }
105 |
106 | received_samples = 0;
107 | num_callbacks = 0;
108 | if (sddc_start_streaming(sddc) < 0) {
109 | fprintf(stderr, "ERROR - sddc_start_streaming() failed\n");
110 | return -1;
111 | }
112 |
113 | fprintf(stderr, "started streaming .. for %d ms ..\n", runtime);
114 | total_samples = (unsigned long long)(runtime * sample_rate / 1000.0);
115 |
116 | if (outfilename)
117 | sampleData = (int16_t*)malloc(total_samples * sizeof(int16_t));
118 |
119 | /* todo: move this into a thread */
120 | stop_reception = 0;
121 | clock_gettime(CLOCK_REALTIME, &clk_start);
122 | while (!stop_reception)
123 | sddc_handle_events(sddc);
124 |
125 | fprintf(stderr, "finished. now stop streaming ..\n");
126 | if (sddc_stop_streaming(sddc) < 0) {
127 | fprintf(stderr, "ERROR - sddc_stop_streaming() failed\n");
128 | return -1;
129 | }
130 |
131 | double dur = clk_diff();
132 | fprintf(stderr, "received=%llu 16-Bit samples in %d callbacks\n", received_samples, num_callbacks);
133 | fprintf(stderr, "run for %f sec\n", dur);
134 | fprintf(stderr, "approx. samplerate is %f kSamples/sec\n", received_samples / (1000.0*dur) );
135 |
136 | if (outfilename && sampleData && received_samples) {
137 | FILE * f = fopen(outfilename, "wb");
138 | if (f) {
139 | fprintf(stderr, "saving received real samples to file ..\n");
140 | waveWriteHeader( (unsigned)(0.5 + sample_rate), 0U /*frequency*/, 16 /*bitsPerSample*/, 1 /*numChannels*/, f);
141 | for ( unsigned long long off = 0; off + 65536 < received_samples; off += 65536 )
142 | waveWriteSamples(f, sampleData + off, 65536, 0 /*needCleanData*/);
143 | waveFinalizeHeader(f);
144 | fclose(f);
145 | }
146 | }
147 |
148 | /* done - all good */
149 | ret_val = 0;
150 |
151 | DONE:
152 | sddc_close(sddc);
153 |
154 | return ret_val;
155 | }
156 |
157 | static void count_bytes_callback(uint32_t data_size,
158 | uint8_t *data,
159 | void *context __attribute__((unused)) )
160 | {
161 | if (stop_reception)
162 | return;
163 | ++num_callbacks;
164 | unsigned N = data_size / sizeof(int16_t);
165 | if ( received_samples + N < total_samples ) {
166 | if (sampleData)
167 | memcpy( sampleData+received_samples, data, data_size);
168 | received_samples += N;
169 | }
170 | else {
171 | clock_gettime(CLOCK_REALTIME, &clk_end);
172 | stop_reception = 1;
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/src/streaming.c:
--------------------------------------------------------------------------------
1 | /*
2 | * streaming.c - streaming functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | /* References:
23 | * - librtlsdr.c: https://github.com/librtlsdr/librtlsdr/blob/development/src/librtlsdr.c
24 | * - Ettus Research UHD libusb1_zero_copy.cpp: https://github.com/EttusResearch/uhd/blob/master/host/lib/transport/libusb1_zero_copy.cpp
25 | */
26 |
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 | #include
37 |
38 | #include "streaming.h"
39 | #include "usb_device.h"
40 | #include "usb_device_internals.h"
41 | #include "logging.h"
42 |
43 |
44 | typedef struct streaming streaming_t;
45 |
46 | /* internal functions */
47 | static void streaming_read_async_callback(struct libusb_transfer *transfer);
48 |
49 |
50 | enum StreamingStatus {
51 | STREAMING_STATUS_OFF,
52 | STREAMING_STATUS_READY,
53 | STREAMING_STATUS_STREAMING,
54 | STREAMING_STATUS_CANCELLED,
55 | STREAMING_STATUS_FAILED = 0xff
56 | };
57 |
58 | typedef struct streaming {
59 | enum StreamingStatus status;
60 | int random;
61 | usb_device_t *usb_device;
62 | uint32_t sample_rate;
63 | uint32_t frame_size;
64 | uint32_t num_frames;
65 | sddc_read_async_cb_t callback;
66 | void *callback_context;
67 | uint8_t **frames;
68 | struct libusb_transfer **transfers;
69 | atomic_int active_transfers;
70 | } streaming_t;
71 |
72 |
73 | static const uint32_t DEFAULT_SAMPLE_RATE = 64000000; /* 64Msps */
74 | static uint32_t DEFAULT_FRAME_SIZE = (2 * DEFAULT_SAMPLE_RATE / 1000); /* ~ 1 ms */
75 | static const uint32_t DEFAULT_NUM_FRAMES = 96; /* we should not exceed 120 ms in total! */
76 | static const unsigned int BULK_XFER_TIMEOUT = 5000; // timeout (in ms) for each bulk transfer
77 |
78 |
79 | streaming_t *streaming_open_sync(usb_device_t *usb_device)
80 | {
81 | streaming_t *ret_val = 0;
82 |
83 | /* we must have a bulk in device to transfer data from */
84 | if (usb_device->bulk_in_endpoint_address == 0) {
85 | log_error("no USB bulk in endpoint found", __func__, __FILE__, __LINE__);
86 | return ret_val;
87 | }
88 |
89 | /* we are good here - create and initialize the streaming */
90 | streaming_t *this = (streaming_t *) malloc(sizeof(streaming_t));
91 | this->status = STREAMING_STATUS_READY;
92 | this->random = 0;
93 | this->usb_device = usb_device;
94 | this->sample_rate = DEFAULT_SAMPLE_RATE;
95 | this->frame_size = 0;
96 | this->num_frames = 0;
97 | this->callback = 0;
98 | this->callback_context = 0;
99 | this->frames = 0;
100 | this->transfers = 0;
101 | atomic_init(&this->active_transfers, 0);
102 |
103 | ret_val = this;
104 | return ret_val;
105 | }
106 |
107 |
108 | streaming_t *streaming_open_async(usb_device_t *usb_device, uint32_t frame_size,
109 | uint32_t num_frames, sddc_read_async_cb_t callback,
110 | void *callback_context)
111 | {
112 | streaming_t *ret_val = 0;
113 |
114 | /* we must have a bulk in device to transfer data from */
115 | if (usb_device->bulk_in_endpoint_address == 0) {
116 | log_error("no USB bulk in endpoint found", __func__, __FILE__, __LINE__);
117 | return ret_val;
118 | }
119 |
120 | /* frame size must be a multiple of max_packet_size * max_burst */
121 | uint32_t max_xfer_size = usb_device->bulk_in_max_packet_size *
122 | usb_device->bulk_in_max_burst;
123 | if ( !max_xfer_size ) {
124 | fprintf(stderr, "ERROR: maximum transfer size is 0. probably not connected at USB 3 port?!\n");
125 | return ret_val;
126 | }
127 |
128 | num_frames = num_frames > 0 ? num_frames : DEFAULT_NUM_FRAMES;
129 | frame_size = frame_size > 0 ? frame_size : DEFAULT_FRAME_SIZE;
130 | frame_size = max_xfer_size * ((frame_size +max_xfer_size -1) / max_xfer_size); // round up
131 | int iso_packets_per_frame = frame_size / usb_device->bulk_in_max_packet_size;
132 | fprintf(stderr, "frame_size = %u, iso_packets_per_frame = %d\n", (unsigned)frame_size, iso_packets_per_frame);
133 |
134 | if (frame_size % max_xfer_size != 0) {
135 | fprintf(stderr, "frame size must be a multiple of %d\n", max_xfer_size);
136 | return ret_val;
137 | }
138 |
139 | /* allocate frames for zerocopy USB bulk transfers */
140 | uint8_t **frames = (uint8_t **) malloc(num_frames * sizeof(uint8_t *));
141 | #if defined (__linux__) && LIBUSB_API_VERSION >= 0x01000105
142 | for (uint32_t i = 0; i < num_frames; ++i) {
143 | frames[i] = libusb_dev_mem_alloc(usb_device->dev_handle, frame_size);
144 | if (frames[i] == 0) {
145 | log_error("libusb_dev_mem_alloc() failed", __func__, __FILE__, __LINE__);
146 | for (uint32_t j = 0; j < i; j++) {
147 | libusb_dev_mem_free(usb_device->dev_handle, frames[j], frame_size);
148 | }
149 | return ret_val;
150 | }
151 | }
152 | #else
153 | for (uint32_t i = 0; i < num_frames; ++i) {
154 | frames[i] = malloc(num_frames);
155 | if (!frames[i])
156 | log_error("Memory allocation failed", __func__, __FILE__, __LINE__);
157 | }
158 | #endif
159 | /* we are good here - create and initialize the streaming */
160 | streaming_t *this = (streaming_t *) malloc(sizeof(streaming_t));
161 | this->status = STREAMING_STATUS_READY;
162 | this->random = 0;
163 | this->usb_device = usb_device;
164 | this->sample_rate = DEFAULT_SAMPLE_RATE;
165 | this->frame_size = frame_size > 0 ? frame_size : DEFAULT_FRAME_SIZE;
166 | this->num_frames = num_frames > 0 ? num_frames : DEFAULT_NUM_FRAMES;
167 | this->callback = callback;
168 | this->callback_context = callback_context;
169 | this->frames = frames;
170 |
171 | /* populate the required libusb_transfer fields */
172 | struct libusb_transfer **transfers = (struct libusb_transfer **) malloc(num_frames * sizeof(struct libusb_transfer *));
173 | for (uint32_t i = 0; i < num_frames; ++i) {
174 | transfers[i] = libusb_alloc_transfer(0); // iso_packets_per_frame ?
175 | libusb_fill_bulk_transfer(transfers[i], usb_device->dev_handle,
176 | usb_device->bulk_in_endpoint_address,
177 | frames[i], frame_size, streaming_read_async_callback,
178 | this, BULK_XFER_TIMEOUT);
179 | }
180 | this->transfers = transfers;
181 | atomic_init(&this->active_transfers, 0);
182 |
183 | ret_val = this;
184 | return ret_val;
185 | }
186 |
187 |
188 | void streaming_close(streaming_t *this)
189 | {
190 | if (this->transfers) {
191 | for (uint32_t i = 0; i < this->num_frames; ++i) {
192 | if (this->transfers[i]) {
193 | libusb_free_transfer(this->transfers[i]);
194 | }
195 | }
196 | free(this->transfers);
197 | this->transfers = NULL;
198 | }
199 |
200 | if (this->frames) {
201 | for (uint32_t i = 0; i < this->num_frames; ++i) {
202 | if (this->frames[i]) {
203 | #if defined (__linux__) && LIBUSB_API_VERSION >= 0x01000105
204 | libusb_dev_mem_free(this->usb_device->dev_handle, this->frames[i],
205 | this->frame_size);
206 | #else
207 | free(this->frames[i]);
208 | #endif
209 | }
210 | }
211 |
212 | free(this->frames);
213 | this->frames = NULL;
214 | free(this);
215 | }
216 | return;
217 | }
218 |
219 |
220 |
221 | int streaming_set_sample_rate(streaming_t *this, uint32_t sample_rate)
222 | {
223 | /* no checks yet */
224 | this->sample_rate = sample_rate;
225 | return 0;
226 | }
227 |
228 |
229 | int streaming_set_random(streaming_t *this, int random)
230 | {
231 | this->random = random;
232 | return 0;
233 | }
234 |
235 |
236 | int streaming_start(streaming_t *this)
237 | {
238 | if (this->status != STREAMING_STATUS_READY) {
239 | fprintf(stderr, "ERROR - streaming_start() called with streaming status not READY: %d\n", this->status);
240 | return -1;
241 | }
242 |
243 | /* if there is no callback, then streaming is synchronous - nothing to do */
244 | if (this->callback == 0) {
245 | this->status = STREAMING_STATUS_STREAMING;
246 | return 0;
247 | }
248 |
249 | /* submit all the transfers */
250 | atomic_init(&this->active_transfers, 0);
251 | for (uint32_t i = 0; i < this->num_frames; ++i) {
252 | int ret = libusb_submit_transfer(this->transfers[i]);
253 | if (ret < 0) {
254 | log_usb_error(ret, __func__, __FILE__, __LINE__);
255 | this->status = STREAMING_STATUS_FAILED;
256 | return -1;
257 | }
258 | atomic_fetch_add(&this->active_transfers, 1);
259 | }
260 |
261 | this->status = STREAMING_STATUS_STREAMING;
262 |
263 | return 0;
264 | }
265 |
266 |
267 | int streaming_stop(streaming_t *this)
268 | {
269 | /* if there is no callback, then streaming is synchronous - nothing to do */
270 | if (this->callback == 0) {
271 | if (this->status == STREAMING_STATUS_STREAMING) {
272 | this->status = STREAMING_STATUS_READY;
273 | }
274 | return 0;
275 | }
276 |
277 | this->status = STREAMING_STATUS_CANCELLED;
278 | /* cancel all the active transfers */
279 | for (uint32_t i = 0; i < this->num_frames; ++i) {
280 | int ret = libusb_cancel_transfer(this->transfers[i]);
281 | if (ret < 0) {
282 | if (ret == LIBUSB_ERROR_NOT_FOUND) {
283 | continue;
284 | }
285 | log_usb_error(ret, __func__, __FILE__, __LINE__);
286 | this->status = STREAMING_STATUS_FAILED;
287 | }
288 | }
289 |
290 | /* flush all the events */
291 | struct timeval noblock = { 0, 0 };
292 | int ret = libusb_handle_events_timeout_completed(this->usb_device->context, &noblock, 0);
293 | if (ret < 0) {
294 | log_usb_error(ret, __func__, __FILE__, __LINE__);
295 | this->status = STREAMING_STATUS_FAILED;
296 | }
297 |
298 | return 0;
299 | }
300 |
301 |
302 | int streaming_reset_status(streaming_t *this)
303 | {
304 | switch (this->status) {
305 | case STREAMING_STATUS_READY:
306 | /* nothing to do here */
307 | return 0;
308 | case STREAMING_STATUS_CANCELLED:
309 | case STREAMING_STATUS_FAILED:
310 | if (this->active_transfers > 0) {
311 | fprintf(stderr, "ERROR - streaming_reset_status() called with %d transfers still active\n",
312 | this->active_transfers);
313 | return -1;
314 | }
315 | break;
316 | default:
317 | fprintf(stderr, "ERROR - streaming_reset_status() called with invalid status: %d\n",
318 | this->status);
319 | return -1;
320 | }
321 |
322 | /* we are good here; reset the status */
323 | this->status = STREAMING_STATUS_READY;
324 | return 0;
325 | }
326 |
327 |
328 | int streaming_read_sync(streaming_t *this, uint8_t *data, int length, int *transferred)
329 | {
330 | int ret = libusb_bulk_transfer(this->usb_device->dev_handle,
331 | this->usb_device->bulk_in_endpoint_address,
332 | data, length, transferred, BULK_XFER_TIMEOUT);
333 | if (ret < 0) {
334 | log_usb_error(ret, __func__, __FILE__, __LINE__);
335 | return -1;
336 | }
337 |
338 | /* remove ADC randomization */
339 | if (this->random) {
340 | uint16_t *samples = (uint16_t *) data;
341 | int n = *transferred / 2;
342 | for (int i = 0; i < n; ++i) {
343 | if (samples[i] & 1) {
344 | samples[i] ^= 0xfffe;
345 | }
346 | }
347 | }
348 |
349 | return 0;
350 | }
351 |
352 |
353 | /* internal functions */
354 | static void LIBUSB_CALL streaming_read_async_callback(struct libusb_transfer *transfer)
355 | {
356 | streaming_t *this = (streaming_t *) transfer->user_data;
357 | int ret;
358 | switch (transfer->status) {
359 | case LIBUSB_TRANSFER_COMPLETED:
360 | /* success!!! */
361 | if (this->status == STREAMING_STATUS_STREAMING) {
362 | /* remove ADC randomization */
363 | if (this->random) {
364 | uint16_t *samples = (uint16_t *) transfer->buffer;
365 | int n = transfer->actual_length / 2;
366 | for (int i = 0; i < n; ++i) {
367 | if (samples[i] & 1) {
368 | samples[i] ^= 0xfffe;
369 | }
370 | }
371 | }
372 | this->callback(transfer->actual_length, transfer->buffer,
373 | this->callback_context);
374 | ret = libusb_submit_transfer(transfer);
375 | if (ret == 0) {
376 | return;
377 | }
378 | log_usb_error(ret, __func__, __FILE__, __LINE__);
379 | }
380 | break;
381 | case LIBUSB_TRANSFER_CANCELLED:
382 | /* librtlsdr does also ignore LIBUSB_TRANSFER_CANCELLED */
383 | return;
384 | case LIBUSB_TRANSFER_ERROR:
385 | case LIBUSB_TRANSFER_TIMED_OUT:
386 | case LIBUSB_TRANSFER_STALL:
387 | case LIBUSB_TRANSFER_NO_DEVICE:
388 | case LIBUSB_TRANSFER_OVERFLOW:
389 | log_usb_error(transfer->status, __func__, __FILE__, __LINE__);
390 | break;
391 | }
392 |
393 | this->status = STREAMING_STATUS_FAILED;
394 | atomic_fetch_sub(&this->active_transfers, 1);
395 | fprintf(stderr, "Cancelling\n");
396 | /* cancel all the active transfers */
397 | for (uint32_t i = 0; i < this->num_frames; ++i) {
398 | int ret = libusb_cancel_transfer(transfer);
399 | if (ret < 0) {
400 | if (ret == LIBUSB_ERROR_NOT_FOUND) {
401 | continue;
402 | }
403 | log_usb_error(ret, __func__, __FILE__, __LINE__);
404 | }
405 | }
406 | return;
407 | }
408 |
--------------------------------------------------------------------------------
/src/streaming.h:
--------------------------------------------------------------------------------
1 | /*
2 | * streaming.h - streaming functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #ifndef __STREAMING_H
23 | #define __STREAMING_H
24 |
25 | #include "usb_device.h"
26 | #include "libsddc.h"
27 |
28 |
29 | #ifdef __cplusplus
30 | extern "C" {
31 | #endif
32 |
33 | typedef struct streaming streaming_t;
34 |
35 | streaming_t *streaming_open_sync(usb_device_t *usb_device);
36 |
37 | streaming_t *streaming_open_async(usb_device_t *usb_device, uint32_t frame_size,
38 | uint32_t num_frames,
39 | sddc_read_async_cb_t callback,
40 | void *callback_context);
41 |
42 | void streaming_close(streaming_t *this);
43 |
44 | int streaming_set_sample_rate(streaming_t *this, uint32_t sample_rate);
45 |
46 | int streaming_set_random(streaming_t *this, int random);
47 |
48 | int streaming_start(streaming_t *this);
49 |
50 | int streaming_stop(streaming_t *this);
51 |
52 | int streaming_reset_status(streaming_t *this);
53 |
54 | int streaming_read_sync(streaming_t *this, uint8_t *data, int length,
55 | int *transferred);
56 |
57 | #ifdef __cplusplus
58 | }
59 | #endif
60 |
61 | #endif /* __STREAMING_H */
62 |
--------------------------------------------------------------------------------
/src/usb_device.c:
--------------------------------------------------------------------------------
1 | /*
2 | * usb_device.c - Basic USB and USB control functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | /* References:
23 | * - FX3 SDK for Linux Platforms (https://www.cypress.com/documentation/software-and-drivers/ez-usb-fx3-software-development-kit)
24 | * example: cyusb_linux_1.0.5/src/download_fx3.cpp
25 | */
26 |
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 | #include
37 |
38 | #include "usb_device.h"
39 | #include "usb_device_internals.h"
40 | #include "ezusb.h"
41 | #include "logging.h"
42 |
43 |
44 | typedef struct usb_device usb_device_t;
45 |
46 | /* internal functions */
47 | static libusb_device_handle *find_usb_device(int index, libusb_context *ctx,
48 | libusb_device **device, int *needs_firmware);
49 | static int load_image(libusb_device_handle *dev_handle,
50 | const char *imagefile);
51 | static int validate_image(const uint8_t *image, const size_t size);
52 | static int transfer_image(const uint8_t *image,
53 | libusb_device_handle *dev_handle);
54 | static int list_endpoints(struct libusb_endpoint_descriptor endpoints[],
55 | struct libusb_ss_endpoint_companion_descriptor ss_endpoints[],
56 | libusb_device *device);
57 |
58 |
59 | struct usb_device_id {
60 | uint16_t vid;
61 | uint16_t pid;
62 | int needs_firmware;
63 | };
64 |
65 |
66 | static struct usb_device_id usb_device_ids[] = {
67 | { 0x04b4, 0x00f3, 1 }, /* Cypress / FX3 Boot-loader */
68 | { 0x04b4, 0x00f1, 0 } /* Cypress / FX3 Streamer Example */
69 | };
70 | static int n_usb_device_ids = sizeof(usb_device_ids) / sizeof(usb_device_ids[0]);
71 |
72 |
73 | int usb_device_count_devices()
74 | {
75 | int ret_val = -1;
76 |
77 | int ret = libusb_init(0);
78 | if (ret < 0) {
79 | log_usb_error(ret, __func__, __FILE__, __LINE__);
80 | goto FAIL0;
81 | }
82 | libusb_device **list = 0;
83 | ssize_t nusbdevices = libusb_get_device_list(0, &list);
84 | if (nusbdevices < 0) {
85 | log_usb_error(nusbdevices, __func__, __FILE__, __LINE__);
86 | goto FAIL1;
87 | }
88 | int count = 0;
89 | for (ssize_t i = 0; i < nusbdevices; ++i) {
90 | libusb_device *dev = list[i];
91 | struct libusb_device_descriptor desc;
92 | ret = libusb_get_device_descriptor(dev, &desc);
93 | for (int i = 0; i < n_usb_device_ids; ++i) {
94 | if (desc.idVendor == usb_device_ids[i].vid &&
95 | desc.idProduct == usb_device_ids[i].pid) {
96 | count++;
97 | }
98 | }
99 | }
100 | libusb_free_device_list(list, 1);
101 |
102 | ret_val = count;
103 |
104 | FAIL1:
105 | libusb_exit(0);
106 | FAIL0:
107 | return ret_val;
108 | }
109 |
110 |
111 | int usb_device_get_device_list(struct usb_device_info **usb_device_infos)
112 | {
113 | const int MAX_STRING_BYTES = 256;
114 |
115 | int ret_val = -1;
116 |
117 | if (usb_device_infos == 0) {
118 | log_error("argument usb_device_infos is a null pointer", __func__, __FILE__, __LINE__);
119 | goto FAIL0;
120 | }
121 |
122 | int ret = libusb_init(0);
123 | if (ret < 0) {
124 | log_usb_error(ret, __func__, __FILE__, __LINE__);
125 | goto FAIL0;
126 | }
127 | libusb_device **list = 0;
128 | ssize_t nusbdevices = libusb_get_device_list(0, &list);
129 | if (nusbdevices < 0) {
130 | log_usb_error(nusbdevices, __func__, __FILE__, __LINE__);
131 | goto FAIL1;
132 | }
133 |
134 | struct usb_device_info *device_infos = (struct usb_device_info *) malloc((nusbdevices + 1) * sizeof(struct usb_device_info));
135 | int count = 0;
136 | for (ssize_t j = 0; j < nusbdevices; ++j) {
137 | libusb_device *device = list[j];
138 | struct libusb_device_descriptor desc;
139 | ret = libusb_get_device_descriptor(device, &desc);
140 | for (int i = 0; i < n_usb_device_ids; ++i) {
141 | if (!(desc.idVendor == usb_device_ids[i].vid &&
142 | desc.idProduct == usb_device_ids[i].pid)) {
143 | continue;
144 | }
145 |
146 | libusb_device_handle *dev_handle = 0;
147 | ret = libusb_open(device, &dev_handle);
148 | if (ret < 0) {
149 | log_usb_error(ret, __func__, __FILE__, __LINE__);
150 | goto FAIL2;
151 | }
152 |
153 | device_infos[count].manufacturer = (unsigned char *) malloc(MAX_STRING_BYTES);
154 | device_infos[count].manufacturer[0] = '\0';
155 | if (desc.iManufacturer) {
156 | ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iManufacturer,
157 | device_infos[count].manufacturer, MAX_STRING_BYTES);
158 | if (ret < 0) {
159 | log_usb_error(ret, __func__, __FILE__, __LINE__);
160 | goto FAIL3;
161 | }
162 | device_infos[count].manufacturer = (unsigned char *) realloc(device_infos[count].manufacturer, ret);
163 | }
164 |
165 | device_infos[count].product = (unsigned char *) malloc(MAX_STRING_BYTES);
166 | device_infos[count].product[0] = '\0';
167 | if (desc.iProduct) {
168 | ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iProduct,
169 | device_infos[count].product, MAX_STRING_BYTES);
170 | if (ret < 0) {
171 | log_usb_error(ret, __func__, __FILE__, __LINE__);
172 | goto FAIL3;
173 | }
174 | device_infos[count].product = (unsigned char *) realloc(device_infos[count].product, ret);
175 | }
176 |
177 | device_infos[count].serial_number = (unsigned char *) malloc(MAX_STRING_BYTES);
178 | device_infos[count].serial_number[0] = '\0';
179 | if (desc.iSerialNumber) {
180 | ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber,
181 | device_infos[count].serial_number, MAX_STRING_BYTES);
182 | if (ret < 0) {
183 | log_usb_error(ret, __func__, __FILE__, __LINE__);
184 | goto FAIL3;
185 | }
186 | device_infos[count].serial_number = (unsigned char *) realloc(device_infos[count].serial_number, ret);
187 | }
188 |
189 | ret = 0;
190 | FAIL3:
191 | libusb_close(dev_handle);
192 | if (ret < 0) {
193 | goto FAIL2;
194 | }
195 | count++;
196 | }
197 | }
198 |
199 | device_infos[count].manufacturer = 0;
200 | device_infos[count].product = 0;
201 | device_infos[count].serial_number = 0;
202 |
203 | *usb_device_infos = device_infos;
204 | ret_val = count;
205 |
206 | FAIL2:
207 | libusb_free_device_list(list, 1);
208 | FAIL1:
209 | libusb_exit(0);
210 | FAIL0:
211 | return ret_val;
212 | }
213 |
214 |
215 | int usb_device_free_device_list(struct usb_device_info *usb_device_infos)
216 | {
217 | for (struct usb_device_info *udi = usb_device_infos;
218 | udi->manufacturer || udi->product || udi->serial_number;
219 | ++udi) {
220 | if (udi->manufacturer) {
221 | free(udi->manufacturer);
222 | }
223 | if (udi->product) {
224 | free(udi->product);
225 | }
226 | if (udi->serial_number) {
227 | free(udi->serial_number);
228 | }
229 | }
230 | free(usb_device_infos);
231 | return 0;
232 | }
233 |
234 |
235 | usb_device_t *usb_device_open(int index, const char* imagefile,
236 | uint16_t gpio_register)
237 | {
238 | usb_device_t *ret_val = 0;
239 | libusb_context *ctx = 0;
240 |
241 | int ret = libusb_init(&ctx);
242 | if (ret < 0) {
243 | log_usb_error(ret, __func__, __FILE__, __LINE__);
244 | goto FAIL0;
245 | }
246 |
247 | libusb_device *device;
248 | int needs_firmware = 0;
249 | libusb_device_handle *dev_handle = find_usb_device(index, ctx, &device, &needs_firmware);
250 | if (dev_handle == 0) {
251 | goto FAIL1;
252 | }
253 |
254 | if (needs_firmware) {
255 | ret = load_image(dev_handle, imagefile);
256 | if (ret != 0) {
257 | log_error("load_image() failed", __func__, __FILE__, __LINE__);
258 | goto FAIL2;
259 | }
260 |
261 | /* rescan USB to get a new device handle */
262 | libusb_close(dev_handle);
263 |
264 | /* wait unitl firmware is ready */
265 | usleep(500 * 1000L);
266 |
267 | needs_firmware = 0;
268 | dev_handle = find_usb_device(index, ctx, &device, &needs_firmware);
269 | if (dev_handle == 0) {
270 | goto FAIL1;
271 | }
272 | if (needs_firmware) {
273 | log_error("device is still in boot loader mode", __func__, __FILE__, __LINE__);
274 | goto FAIL2;
275 | }
276 | }
277 |
278 | int speed = libusb_get_device_speed(device);
279 | if ( speed == LIBUSB_SPEED_LOW || speed == LIBUSB_SPEED_FULL || speed == LIBUSB_SPEED_HIGH ) {
280 | log_error("USB 3.x SuperSpeed connection failed", __func__, __FILE__, __LINE__);
281 | goto FAIL2;
282 | }
283 |
284 | /* list endpoints */
285 | struct libusb_endpoint_descriptor endpoints[MAX_ENDPOINTS];
286 | struct libusb_ss_endpoint_companion_descriptor ss_endpoints[MAX_ENDPOINTS];
287 | ret = list_endpoints(endpoints, ss_endpoints, device);
288 | if (ret < 0) {
289 | log_error("list_endpoints() failed", __func__, __FILE__, __LINE__);
290 | goto FAIL2;
291 | }
292 | int nendpoints = ret;
293 | uint8_t bulk_in_endpoint_address = 0;
294 | uint16_t bulk_in_max_packet_size = 0;
295 | uint8_t bulk_in_max_burst = 0;
296 | for (int i = 0; i < nendpoints; ++i) {
297 | if ((endpoints[i].bmAttributes & 0x03) == LIBUSB_TRANSFER_TYPE_BULK &&
298 | (endpoints[i].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) {
299 | bulk_in_endpoint_address = endpoints[i].bEndpointAddress;
300 | bulk_in_max_packet_size = endpoints[i].wMaxPacketSize;
301 | bulk_in_max_burst = ss_endpoints[i].bLength == 0 ? 0 :
302 | ss_endpoints[i].bMaxBurst;
303 | break;
304 | }
305 | }
306 | if (bulk_in_endpoint_address == 0) {
307 | fprintf(stderr, "ERROR - bulk in endpoint not found\n");
308 | goto FAIL2;
309 | }
310 |
311 | /* we are good here - create and initialize the usb_device */
312 | usb_device_t *this = (usb_device_t *) malloc(sizeof(usb_device_t));
313 | this->dev = device;
314 | this->dev_handle = dev_handle;
315 | this->context = ctx;
316 | this->completed = 0;
317 | this->nendpoints = nendpoints;
318 | memset(this->endpoints, 0, sizeof(this->endpoints));
319 | for (int i = 0; i < nendpoints; ++i) {
320 | this->endpoints[i] = endpoints[i];
321 | this->ss_endpoints[i] = ss_endpoints[i];
322 | }
323 | this->bulk_in_endpoint_address = bulk_in_endpoint_address;
324 | this->bulk_in_max_packet_size = bulk_in_max_packet_size;
325 | this->bulk_in_max_burst = bulk_in_max_burst;
326 | this->gpio_register = gpio_register;
327 | memset(this->fw_registers, 0, sizeof(this->fw_registers));
328 |
329 | ret_val = this;
330 | return ret_val;
331 |
332 | FAIL2:
333 | libusb_close(dev_handle);
334 | FAIL1:
335 | libusb_exit(0);
336 | FAIL0:
337 | return ret_val;
338 | }
339 |
340 |
341 | void usb_device_close(usb_device_t *this)
342 | {
343 | libusb_close(this->dev_handle);
344 | free(this);
345 | libusb_exit(0);
346 | return;
347 | }
348 |
349 |
350 | int usb_device_handle_events(usb_device_t *this)
351 | {
352 | return libusb_handle_events_completed(this->context, &this->completed);
353 | }
354 |
355 |
356 | int usb_device_control(usb_device_t *this, uint8_t request, uint16_t value,
357 | uint16_t index, uint8_t *data, uint16_t length) {
358 |
359 | const uint8_t bmWriteRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE;
360 | const uint8_t bmReadRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE;
361 | const unsigned int timeout = 5000; // timeout (in ms) for each command
362 |
363 | uint8_t dummy[] = { 0 };
364 |
365 | int ret;
366 | switch (request) {
367 | case STARTFX3:
368 | case STOPFX3:
369 | case RESETFX3:
370 | case R82XXSTDBY:
371 | ret = libusb_control_transfer(this->dev_handle, bmWriteRequestType,
372 | request, 0, 0, dummy, sizeof(dummy),
373 | timeout);
374 | if (ret < 0) {
375 | log_usb_error(ret, __func__, __FILE__, __LINE__);
376 | return -1;
377 | }
378 | break;
379 | case TESTFX3:
380 | case I2CRFX3:
381 | ret = libusb_control_transfer(this->dev_handle, bmReadRequestType,
382 | request, value, index, data, length,
383 | timeout);
384 | if (ret < 0) {
385 | log_usb_error(ret, __func__, __FILE__, __LINE__);
386 | return -1;
387 | }
388 | break;
389 | case GPIOFX3:
390 | case I2CWFX3:
391 | case STARTADC:
392 | case R82XXINIT:
393 | case R82XXTUNE:
394 | ret = libusb_control_transfer(this->dev_handle, bmWriteRequestType,
395 | request, value, index, data, length,
396 | timeout);
397 | if (ret < 0) {
398 | log_usb_error(ret, __func__, __FILE__, __LINE__);
399 | return -1;
400 | }
401 | break;
402 | case SETARGFX3:
403 | ret = libusb_control_transfer(this->dev_handle, bmWriteRequestType,
404 | request, value, index, dummy, sizeof(dummy),
405 | timeout);
406 | if (ret < 0) {
407 | log_usb_error(ret, __func__, __FILE__, __LINE__);
408 | return -1;
409 | }
410 | break;
411 | default:
412 | fprintf(stderr, "ERROR - unknown USB device control request: 0x%02x\n",
413 | request);
414 | return -1;
415 | }
416 | return 0;
417 | }
418 |
419 |
420 | uint16_t usb_device_gpio_get(usb_device_t *this) {
421 | return this->gpio_register;
422 | }
423 |
424 |
425 | int usb_device_gpio_set(usb_device_t *this, uint16_t bit_pattern,
426 | uint16_t bit_mask) {
427 | this->gpio_register = (this->gpio_register & ~bit_mask) | bit_pattern;
428 | return usb_device_control(this, GPIOFX3, 0, 0,
429 | (uint8_t *) &this->gpio_register,
430 | sizeof(this->gpio_register));
431 | }
432 |
433 |
434 | int usb_device_gpio_on(usb_device_t *this, uint16_t bit_pattern) {
435 | this->gpio_register |= bit_pattern;
436 | return usb_device_control(this, GPIOFX3, 0, 0,
437 | (uint8_t *) &this->gpio_register,
438 | sizeof(this->gpio_register));
439 | }
440 |
441 |
442 | int usb_device_gpio_off(usb_device_t *this, uint16_t bit_pattern) {
443 | this->gpio_register &= ~bit_pattern;
444 | return usb_device_control(this, GPIOFX3, 0, 0,
445 | (uint8_t *) &this->gpio_register,
446 | sizeof(this->gpio_register));
447 | }
448 |
449 |
450 | int usb_device_gpio_toggle(usb_device_t *this, uint16_t bit_pattern) {
451 | this->gpio_register ^= bit_pattern;
452 | return usb_device_control(this, GPIOFX3, 0, 0,
453 | (uint8_t *) &this->gpio_register,
454 | sizeof(this->gpio_register));
455 | }
456 |
457 |
458 | int usb_device_i2c_write(usb_device_t *this, uint8_t i2c_address,
459 | uint8_t register_address, uint8_t *data,
460 | uint8_t length) {
461 | return usb_device_control(this, I2CWFX3, (uint16_t) i2c_address,
462 | (uint16_t) register_address, data,
463 | (uint16_t) length);
464 | }
465 |
466 |
467 | int usb_device_i2c_write_byte(usb_device_t *this, uint8_t i2c_address,
468 | uint8_t register_address, uint8_t value) {
469 | uint8_t data[] = { value };
470 | return usb_device_control(this, I2CWFX3, (uint16_t) i2c_address,
471 | (uint16_t) register_address, data,
472 | sizeof(data));
473 | }
474 |
475 |
476 | int usb_device_i2c_read(usb_device_t *this, uint8_t i2c_address,
477 | uint8_t register_address, uint8_t *data,
478 | uint8_t length) {
479 | return usb_device_control(this, I2CRFX3, (uint16_t) i2c_address,
480 | (uint16_t) register_address, data,
481 | (uint16_t) length);
482 | }
483 |
484 |
485 | /* firmware registers */
486 | uint16_t usb_device_get_fw_register(usb_device_t *this, uint16_t address) {
487 | if (address >= MAX_FW_REGISTERS) {
488 | fprintf(stderr, "ERROR - usb_device_get_fw_register() failed - invalid register address: %d\n", address);
489 | }
490 | return this->fw_registers[address];
491 | }
492 |
493 |
494 | int usb_device_set_fw_register(usb_device_t *this, uint16_t address,
495 | uint16_t value) {
496 | if (address >= MAX_FW_REGISTERS) {
497 | fprintf(stderr, "ERROR - usb_device_set_fw_register() failed - invalid register address: %d\n", address);
498 | }
499 | int ret = usb_device_control(this, SETARGFX3, address, value, 0, 0);
500 | if (ret < 0) {
501 | fprintf(stderr, "ERROR - usb_device_control(SETARGFX3) failed\n");
502 | return -1;
503 | }
504 | this->fw_registers[address] = value;
505 | return 0;
506 | }
507 |
508 |
509 |
510 |
511 |
512 | /* internal functions */
513 | static libusb_device_handle *find_usb_device(int index, libusb_context *ctx,
514 | libusb_device **device, int *needs_firmware)
515 | {
516 | libusb_device_handle *ret_val = 0;
517 |
518 | *device = 0;
519 | *needs_firmware = 0;
520 |
521 | libusb_device **list = 0;
522 | ssize_t nusbdevices = libusb_get_device_list(ctx, &list);
523 | if (nusbdevices < 0) {
524 | log_usb_error(nusbdevices, __func__, __FILE__, __LINE__);
525 | goto FAIL0;
526 | }
527 |
528 | int count = 0;
529 | for (ssize_t j = 0; j < nusbdevices; ++j) {
530 | libusb_device *dev = list[j];
531 | struct libusb_device_descriptor desc;
532 | libusb_get_device_descriptor(dev, &desc);
533 | for (int i = 0; i < n_usb_device_ids; ++i) {
534 | if (desc.idVendor == usb_device_ids[i].vid &&
535 | desc.idProduct == usb_device_ids[i].pid) {
536 | if (count == index) {
537 | *device = dev;
538 | *needs_firmware = usb_device_ids[i].needs_firmware;
539 | }
540 | count++;
541 | }
542 | }
543 | }
544 |
545 | if (*device == 0) {
546 | fprintf(stderr, "ERROR - usb_device@%d not found\n", index);
547 | goto FAIL1;
548 | }
549 |
550 | libusb_device_handle *dev_handle = 0;
551 | int ret = libusb_open(*device, &dev_handle);
552 | if (ret < 0) {
553 | log_usb_error(ret, __func__, __FILE__, __LINE__);
554 | goto FAIL1;
555 | }
556 | libusb_free_device_list(list, 1);
557 |
558 | ret = libusb_kernel_driver_active(dev_handle, 0);
559 | if (ret < 0) {
560 | log_usb_error(ret, __func__, __FILE__, __LINE__);
561 | goto FAILA;
562 | }
563 | if (ret == 1) {
564 | fprintf(stderr, "ERROR - device busy\n");
565 | goto FAILA;
566 | }
567 |
568 | ret = libusb_claim_interface(dev_handle, 0);
569 | if (ret < 0) {
570 | log_usb_error(ret, __func__, __FILE__, __LINE__);
571 | goto FAILA;
572 | }
573 |
574 | ret_val = dev_handle;
575 | return ret_val;
576 |
577 | FAILA:
578 | libusb_close(dev_handle);
579 | return ret_val;
580 |
581 | FAIL1:
582 | libusb_free_device_list(list, 1);
583 | FAIL0:
584 | return ret_val;
585 | }
586 |
587 |
588 | int load_image(libusb_device_handle *dev_handle, const char *imagefile)
589 | {
590 | int ret_val = -1;
591 |
592 | const int fx_type = FX_TYPE_FX3;
593 | const int img_type = IMG_TYPE_IMG;
594 | const int stage = 0;
595 | verbose = 1;
596 | ret_val = ezusb_load_ram(dev_handle, imagefile, fx_type, img_type, stage);
597 | return ret_val;
598 |
599 | int fd = open(imagefile, O_RDONLY);
600 | if (fd < 0) {
601 | fprintf(stderr, "ERROR - open(%s) failed: %s\n", imagefile, strerror(errno));
602 | goto FAIL0;
603 | }
604 |
605 | /* slurp the whole fle into memory */
606 | struct stat statbuf;
607 | int ret = fstat(fd, &statbuf);
608 | if (ret < 0) {
609 | fprintf(stderr, "ERROR - fstat(%s) failed: %s\n", imagefile, strerror(errno));
610 | goto FAIL1;
611 | }
612 | size_t image_size = statbuf.st_size;
613 | uint8_t *image = (uint8_t *) malloc(image_size);
614 | if (image == 0) {
615 | fprintf(stderr, "ERROR - malloc() failed: %s\n", strerror(errno));
616 | goto FAIL1;
617 | }
618 | for (size_t nleft = image_size; nleft != 0; ) {
619 | ssize_t nr = read(fd, image, nleft);
620 | if (nr < 0) {
621 | fprintf(stderr, "ERROR - read(%s) failed: %s\n", imagefile, strerror(errno));
622 | goto FAIL1;
623 | }
624 | nleft -= nr;
625 | }
626 |
627 | close(fd);
628 |
629 | if (validate_image(image, image_size) < 0) {
630 | fprintf(stderr, "ERROR - validate_image() failed\n");
631 | goto FAILA;
632 | }
633 |
634 | if (transfer_image(image, dev_handle) < 0) {
635 | fprintf(stderr, "ERROR - transfer_image() failed\n");
636 | goto FAILA;
637 | }
638 |
639 | ret_val = 0;
640 |
641 | FAILA:
642 | free(image);
643 | return ret_val;
644 |
645 | FAIL1:
646 | close(fd);
647 | FAIL0:
648 | return ret_val;
649 | }
650 |
651 |
652 | static int validate_image(const uint8_t *image, const size_t size)
653 | {
654 | if (size < 10240) {
655 | fprintf(stderr, "ERROR - image file is too small\n");
656 | return -1;
657 | }
658 | if (!(image[0] == 'C' && image[1] == 'Y')) {
659 | fprintf(stderr, "ERROR - image header does not start with 'CY'\n");
660 | return -1;
661 | }
662 | if (!(image[2] == 0x1c)) {
663 | fprintf(stderr, "ERROR - I2C config is not set to 0x1C\n");
664 | return -1;
665 | }
666 | if (!(image[3] == 0xb0)) {
667 | fprintf(stderr, "ERROR - image type is not binary (0x01)\n");
668 | return -1;
669 | }
670 |
671 | uint32_t checksum = 0;
672 | uint32_t *current = (uint32_t *) image + 1;
673 | uint32_t *end = (uint32_t *) (image + size);
674 |
675 | while (1) {
676 | uint32_t loadSz = *current++;
677 | //printf("\tloadSz: %u\n", loadSz);
678 | if (loadSz == 0) {
679 | break;
680 | }
681 | uint32_t secStart __attribute__((unused)) = *current++;
682 | //printf("\tsecStart: 0x%08x\n", secStart);
683 | if (current + loadSz >= end - 2) {
684 | fprintf(stderr, "ERROR - loadSz is too big - loadSz=%u\n", loadSz);
685 | return -1;
686 | }
687 | while (loadSz--) {
688 | checksum += *current++;
689 | }
690 | }
691 | uint32_t entryAddr __attribute__((unused)) = *current++;
692 | //printf("entryAddr: 0x%08x\n", entryAddr);
693 | uint32_t expected_checksum = *current++;
694 | if (!(current == end)) {
695 | fprintf(stderr, "WARNING - image file longer than expected\n");
696 | }
697 | if (!(checksum == expected_checksum)) {
698 | fprintf(stderr, "ERROR - checksum does not match - actual=0x%08x expected=0x%08x\n",
699 | checksum, expected_checksum);
700 | return -1;
701 | }
702 | return 0;
703 | }
704 |
705 |
706 | static int transfer_image(const uint8_t *image,
707 | libusb_device_handle *dev_handle)
708 | {
709 | const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE;
710 | const uint8_t bRequest = 0xa0; // vendor command
711 | const unsigned int timeout = 5000; // timeout (in ms) for each command
712 | const size_t max_write_size = 2 * 1024; // max write size in bytes
713 |
714 | // skip first word with 'CY' magic
715 | uint32_t *current = (uint32_t *) image + 1;
716 |
717 | while (1) {
718 | uint32_t loadSz = *current++;
719 | if (loadSz == 0) {
720 | break;
721 | }
722 | uint32_t address = *current++;
723 |
724 | unsigned char *data = (unsigned char *) current;
725 | for (size_t nleft = loadSz * 4; nleft > 0; ) {
726 | uint16_t wLength = nleft > max_write_size ? max_write_size : nleft;
727 | int ret = libusb_control_transfer(dev_handle, bmRequestType, bRequest,
728 | address & 0xffff, address >> 16,
729 | data, wLength, timeout);
730 | if (ret < 0) {
731 | log_usb_error(ret, __func__, __FILE__, __LINE__);
732 | return -1;
733 | }
734 | if (!(ret == wLength)) {
735 | fprintf(stderr, "ERROR - libusb_control_transfer() returned less bytes than expected - actual=%d expected=%hu\n", ret, wLength);
736 | return -1;
737 | }
738 | data += wLength;
739 | nleft -= wLength;
740 | }
741 | current += loadSz;
742 | }
743 |
744 | uint32_t entryAddr = *current++;
745 | uint32_t checksum __attribute__((unused)) = *current++;
746 |
747 | sleep(1);
748 |
749 | int ret = libusb_control_transfer(dev_handle, bmRequestType, bRequest,
750 | entryAddr & 0xffff, entryAddr >> 16,
751 | 0, 0, timeout);
752 | if (ret < 0) {
753 | log_usb_warning(ret, __func__, __FILE__, __LINE__);
754 | }
755 |
756 | return 0;
757 | }
758 |
759 |
760 | static int list_endpoints(struct libusb_endpoint_descriptor endpoints[],
761 | struct libusb_ss_endpoint_companion_descriptor ss_endpoints[],
762 | libusb_device *device)
763 | {
764 | struct libusb_config_descriptor *config;
765 | int ret = libusb_get_active_config_descriptor(device, &config);
766 | if (ret < 0) {
767 | log_usb_error(ret, __func__, __FILE__, __LINE__);
768 | return -1;
769 | }
770 |
771 | int count = 0;
772 |
773 | /* loop through the interfaces */
774 | for (int intf = 0; intf < config->bNumInterfaces; ++intf) {
775 | const struct libusb_interface *interface = &config->interface[intf];
776 | for (int setng = 0; setng < interface->num_altsetting; ++setng) {
777 | const struct libusb_interface_descriptor *setting = &interface->altsetting[setng];
778 | for (int endp = 0; endp < setting->bNumEndpoints; ++endp) {
779 | const struct libusb_endpoint_descriptor *endpoint = &setting->endpoint[endp];
780 | if (count == MAX_ENDPOINTS) {
781 | fprintf(stderr, "WARNING - found too many USB endpoints; returning only the first %d\n", MAX_ENDPOINTS);
782 | return count;
783 | }
784 | endpoints[count] = *endpoint;
785 | struct libusb_ss_endpoint_companion_descriptor *endpoint_ss_companion;
786 | ret = libusb_get_ss_endpoint_companion_descriptor(0, endpoint,
787 | &endpoint_ss_companion);
788 | if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND) {
789 | log_usb_error(ret, __func__, __FILE__, __LINE__);
790 | return -1;
791 | }
792 | if (ret == 0) {
793 | ss_endpoints[count] = *endpoint_ss_companion;
794 | } else {
795 | ss_endpoints[count].bLength = 0;
796 | }
797 | libusb_free_ss_endpoint_companion_descriptor(endpoint_ss_companion);
798 | count++;
799 | }
800 | }
801 | }
802 |
803 | return count;
804 | }
805 |
--------------------------------------------------------------------------------
/src/usb_device.h:
--------------------------------------------------------------------------------
1 | /*
2 | * usb_device.h - Basic USB and USB control functions
3 | *
4 | * Copyright (C) 2020 by Franco Venturi
5 | *
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 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | *
19 | * SPDX-License-Identifier: GPL-3.0-or-later
20 | */
21 |
22 | #ifndef __USB_DEVICE_H
23 | #define __USB_DEVICE_H
24 |
25 | #include
26 |
27 |
28 | #ifdef __cplusplus
29 | extern "C" {
30 | #endif
31 |
32 | typedef struct usb_device usb_device_t;
33 |
34 | struct usb_device_info {
35 | unsigned char *manufacturer;
36 | unsigned char *product;
37 | unsigned char *serial_number;
38 | };
39 |
40 | enum USBCommands {
41 | STARTFX3 = 0xaa,
42 | STOPFX3 = 0xab,
43 | TESTFX3 = 0xac,
44 | GPIOFX3 = 0xad,
45 | I2CWFX3 = 0xae,
46 | I2CRFX3 = 0xaf,
47 | RESETFX3 = 0xb1,
48 | SETARGFX3 = 0xb6,
49 | STARTADC = 0xb2,
50 | R82XXINIT = 0xb4,
51 | R82XXTUNE = 0xb5,
52 | R82XXSTDBY = 0xb8,
53 | };
54 |
55 | int usb_device_count_devices();
56 |
57 | int usb_device_get_device_list(struct usb_device_info **usb_device_infos);
58 |
59 | int usb_device_free_device_list(struct usb_device_info *usb_device_infos);
60 |
61 | usb_device_t *usb_device_open(int index, const char* imagefile,
62 | uint16_t gpio_register);
63 |
64 | int usb_device_handle_events(usb_device_t *this);
65 |
66 | void usb_device_close(usb_device_t *this);
67 |
68 | int usb_device_control(usb_device_t *this, uint8_t request, uint16_t value,
69 | uint16_t index, uint8_t *data, uint16_t length);
70 |
71 | uint16_t usb_device_gpio_get(usb_device_t *this);
72 |
73 | int usb_device_gpio_set(usb_device_t *this, uint16_t bit_pattern,
74 | uint16_t bit_mask);
75 |
76 | int usb_device_gpio_on(usb_device_t *this, uint16_t bit_pattern);
77 |
78 | int usb_device_gpio_off(usb_device_t *this, uint16_t bit_pattern);
79 |
80 | int usb_device_gpio_toggle(usb_device_t *this, uint16_t bit_pattern);
81 |
82 | int usb_device_i2c_write(usb_device_t *this, uint8_t i2c_address,
83 | uint8_t register_address, uint8_t *data,
84 | uint8_t length);
85 |
86 | int usb_device_i2c_write_byte(usb_device_t *this, uint8_t i2c_address,
87 | uint8_t register_address, uint8_t value);
88 |
89 | int usb_device_i2c_read(usb_device_t *this, uint8_t i2c_address,
90 | uint8_t register_address, uint8_t *data,
91 | uint8_t length);
92 |
93 | uint16_t usb_device_get_fw_register(usb_device_t *this, uint16_t address);
94 |
95 | int usb_device_set_fw_register(usb_device_t *this, uint16_t address,
96 | uint16_t value);
97 |
98 | #ifdef __cplusplus
99 | }
100 | #endif
101 |
102 | #endif /* __USB_DEVICE_H */
103 |
--------------------------------------------------------------------------------
/src/usb_device_internals.h:
--------------------------------------------------------------------------------
1 | /*
2 | * usb_device_internals.h - internal USB structures to be shared between
3 | * usb_device and usb_streaming
4 | *
5 | * Copyright (C) 2020 by Franco Venturi
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | *
20 | * SPDX-License-Identifier: GPL-3.0-or-later
21 | */
22 |
23 | #ifndef __USB_DEVICE_INTERNALS_H
24 | #define __USB_DEVICE_INTERNALS_H
25 |
26 | #include "usb_device.h"
27 |
28 |
29 | #ifdef __cplusplus
30 | extern "C" {
31 | #endif
32 |
33 | typedef struct usb_device {
34 | libusb_device *dev;
35 | libusb_device_handle *dev_handle;
36 | libusb_context *context;
37 | int completed;
38 | int nendpoints;
39 | #define MAX_ENDPOINTS (16)
40 | struct libusb_endpoint_descriptor endpoints[MAX_ENDPOINTS];
41 | struct libusb_ss_endpoint_companion_descriptor ss_endpoints[MAX_ENDPOINTS];
42 | uint8_t bulk_in_endpoint_address;
43 | uint16_t bulk_in_max_packet_size;
44 | uint8_t bulk_in_max_burst;
45 | uint16_t gpio_register;
46 | #define MAX_FW_REGISTERS (16)
47 | uint16_t fw_registers[MAX_FW_REGISTERS];
48 | } usb_device_t;
49 | typedef struct usb_device usb_device_t;
50 |
51 | #ifdef __cplusplus
52 | }
53 | #endif
54 |
55 | #endif /* __USB_DEVICE_INTERNALS_H */
56 |
--------------------------------------------------------------------------------
/src/wavehdr.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2019 by Hayati Ayguen
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 2 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | #ifndef __WAVEHDR_H
19 | #define __WAVEHDR_H
20 |
21 | #include
22 | #include
23 | #include
24 |
25 | #pragma pack(push)
26 | #pragma pack(1)
27 |
28 | typedef struct
29 | {
30 | char ID[4];
31 | uint32_t size;
32 | } chunk_hdr;
33 |
34 | typedef struct
35 | {
36 | uint16_t wYear; /* 1601 through 30827 */
37 | uint16_t wMonth; /* 1..12 */
38 | uint16_t wDayOfWeek; /* 0 .. 6: 0 == Sunday, .., 6 == Saturday */
39 | uint16_t wDay; /* 1 .. 31 */
40 | uint16_t wHour; /* 0 .. 23 */
41 | uint16_t wMinute; /* 0 .. 59 */
42 | uint16_t wSecond; /* 0 .. 59 */
43 | uint16_t wMilliseconds; /* 0 .. 999 */
44 | } Wind_SystemTime;
45 |
46 |
47 | typedef struct
48 | {
49 | /* RIFF header */
50 | chunk_hdr hdr; /* ID == "RIFF" string, size == full filesize - 8 bytes (maybe with some byte missing...) */
51 | char waveID[4]; /* "WAVE" string */
52 | } riff_chunk;
53 |
54 | typedef struct
55 | {
56 | /* FMT header */
57 | chunk_hdr hdr; /* ID == "fmt " */
58 | int16_t wFormatTag;
59 | int16_t nChannels;
60 | int32_t nSamplesPerSec;
61 | int32_t nAvgBytesPerSec;
62 | int16_t nBlockAlign;
63 | int16_t nBitsPerSample;
64 | } fmt_chunk;
65 |
66 | typedef struct
67 | {
68 | /* auxi header - used by SpectraVue / rfspace / HDSDR / ELAD FDM .. */
69 | chunk_hdr hdr; /* ="auxi" (chunk rfspace) */
70 | Wind_SystemTime StartTime;
71 | Wind_SystemTime StopTime;
72 | uint32_t centerFreq; /* receiver center frequency */
73 | uint32_t ADsamplerate; /* A/D sample frequency before downsampling */
74 | uint32_t IFFrequency; /* IF freq if an external down converter is used */
75 | uint32_t Bandwidth; /* displayable BW if you want to limit the display to less than Nyquist band */
76 | int32_t IQOffset; /* DC offset of the I and Q channels in 1/1000's of a count */
77 | int32_t Unused2;
78 | int32_t Unused3;
79 | int32_t Unused4;
80 | int32_t Unused5;
81 | } auxi_chunk;
82 |
83 | typedef struct
84 | {
85 | /* DATA header */
86 | chunk_hdr hdr; /* ="data" */
87 | } data_chunk;
88 |
89 | typedef struct
90 | {
91 | riff_chunk r;
92 | fmt_chunk f;
93 | auxi_chunk a;
94 | data_chunk d;
95 | } waveFileHeader;
96 |
97 | #pragma pack(pop)
98 |
99 | #endif /* __WAVEHDR_H */
100 |
101 | // vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab
102 |
103 |
--------------------------------------------------------------------------------
/src/wavewrite.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2019 by Hayati Ayguen
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 2 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | #include "wavewrite.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 |
26 | #ifndef _WIN32
27 | #include
28 | #include
29 | #else
30 | #include
31 | #include
32 | #include
33 | #include
34 | #define _USE_MATH_DEFINES
35 | #endif
36 |
37 | #include
38 |
39 | #include "wavehdr.h"
40 |
41 | static waveFileHeader waveHdr;
42 |
43 | static uint32_t waveDataSize = 0;
44 | int waveHdrStarted = 0;
45 |
46 |
47 | static void waveSetCurrTime(Wind_SystemTime *p)
48 | {
49 | struct timeval tv;
50 | struct tm t;
51 |
52 | gettimeofday(&tv, NULL);
53 | p->wMilliseconds = tv.tv_usec / 1000;
54 |
55 | #ifdef _WIN32
56 | t = *gmtime(&tv.tv_sec);
57 | #else
58 | gmtime_r(&tv.tv_sec, &t);
59 | #endif
60 |
61 | p->wYear = t.tm_year + 1900; /* 1601 through 30827 */
62 | p->wMonth = t.tm_mon + 1; /* 1..12 */
63 | p->wDayOfWeek = t.tm_wday; /* 0 .. 6: 0 == Sunday, .., 6 == Saturday */
64 | p->wDay = t.tm_mday; /* 1 .. 31 */
65 | p->wHour = t.tm_hour; /* 0 .. 23 */
66 | p->wMinute = t.tm_min; /* 0 .. 59 */
67 | p->wSecond = t.tm_sec; /* 0 .. 59 */
68 | }
69 |
70 | static void waveSetStartTimeInt(time_t tim, double fraction, Wind_SystemTime *p)
71 | {
72 | struct tm t = *gmtime( &tim );
73 | p->wYear = t.tm_year + 1900; /* 1601 through 30827 */
74 | p->wMonth = t.tm_mon + 1; /* 1..12 */
75 | p->wDayOfWeek = t.tm_wday; /* 0 .. 6: 0 == Sunday, .., 6 == Saturday */
76 | p->wDay = t.tm_mday; /* 1 .. 31 */
77 | p->wHour = t.tm_hour; /* 0 .. 23 */
78 | p->wMinute = t.tm_min; /* 0 .. 59 */
79 | p->wSecond = t.tm_sec; /* 0 .. 59 */
80 | p->wMilliseconds = (int)( fraction * 1000.0 );
81 | if (p->wMilliseconds >= 1000)
82 | p->wMilliseconds = 999;
83 | }
84 |
85 | void waveSetStartTime(time_t tim, double fraction)
86 | {
87 | waveSetStartTimeInt(tim, fraction, &waveHdr.a.StartTime );
88 | waveHdr.a.StopTime = waveHdr.a.StartTime; /* to fix */
89 | }
90 |
91 |
92 | void wavePrepareHeader(unsigned samplerate, unsigned freq, int bitsPerSample, int numChannels)
93 | {
94 | int bytesPerSample = bitsPerSample / 8;
95 | int bytesPerFrame = bytesPerSample * numChannels;
96 |
97 | memcpy( waveHdr.r.hdr.ID, "RIFF", 4 );
98 | waveHdr.r.hdr.size = sizeof(waveFileHeader) - 8; /* to fix */
99 | memcpy( waveHdr.r.waveID, "WAVE", 4 );
100 |
101 | memcpy( waveHdr.f.hdr.ID, "fmt ", 4 );
102 | waveHdr.f.hdr.size = 16;
103 | waveHdr.f.wFormatTag = 1; /* PCM */
104 | waveHdr.f.nChannels = numChannels; /* I and Q channels */
105 | waveHdr.f.nSamplesPerSec = samplerate;
106 | waveHdr.f.nAvgBytesPerSec = samplerate * bytesPerFrame;
107 | waveHdr.f.nBlockAlign = waveHdr.f.nChannels;
108 | waveHdr.f.nBitsPerSample = bitsPerSample;
109 |
110 | memcpy( waveHdr.a.hdr.ID, "auxi", 4 );
111 | waveHdr.a.hdr.size = 2 * sizeof(Wind_SystemTime) + 9 * sizeof(int32_t); /* = 2 * 16 + 9 * 4 = 68 */
112 | waveSetCurrTime( &waveHdr.a.StartTime );
113 | waveHdr.a.StopTime = waveHdr.a.StartTime; /* to fix */
114 | waveHdr.a.centerFreq = freq;
115 | waveHdr.a.ADsamplerate = samplerate;
116 | waveHdr.a.IFFrequency = 0;
117 | waveHdr.a.Bandwidth = 0;
118 | waveHdr.a.IQOffset = 0;
119 | waveHdr.a.Unused2 = 0;
120 | waveHdr.a.Unused3 = 0;
121 | waveHdr.a.Unused4 = 0;
122 | waveHdr.a.Unused5 = 0;
123 |
124 | memcpy( waveHdr.d.hdr.ID, "data", 4 );
125 | waveHdr.d.hdr.size = 0; /* to fix later */
126 | waveDataSize = 0;
127 | }
128 |
129 | void waveWriteHeader(unsigned samplerate, unsigned freq, int bitsPerSample, int numChannels, FILE * f)
130 | {
131 | if (f != stdout) {
132 | assert( !waveHdrStarted );
133 | wavePrepareHeader(samplerate, freq, bitsPerSample, numChannels);
134 | fwrite(&waveHdr, sizeof(waveFileHeader), 1, f);
135 | waveHdrStarted = 1;
136 | }
137 | }
138 |
139 | int waveWriteSamples(FILE* f, void * vpData, size_t numSamples, int needCleanData)
140 | {
141 | size_t nw;
142 | switch (waveHdr.f.nBitsPerSample)
143 | {
144 | case 0:
145 | default:
146 | return 1;
147 | case 8:
148 | /* no endian conversion needed for single bytes */
149 | nw = fwrite(vpData, sizeof(uint8_t), numSamples, f);
150 | waveDataSize += sizeof(uint8_t) * numSamples;
151 | return (nw == numSamples) ? 0 : 1;
152 | case 16:
153 | /* TODO: endian conversion needed */
154 | nw = fwrite(vpData, sizeof(int16_t), numSamples, f);
155 | waveDataSize += sizeof(int16_t) * numSamples;
156 | if ( needCleanData )
157 | {
158 | /* TODO: convert back endianness */
159 | }
160 | return (nw == numSamples) ? 0 : 1;
161 | }
162 | }
163 |
164 | int waveWriteFrames(FILE* f, void * vpData, size_t numFrames, int needCleanData)
165 | {
166 | size_t nw;
167 | switch (waveHdr.f.nBitsPerSample)
168 | {
169 | case 0:
170 | default:
171 | return 1;
172 | case 8:
173 | /* no endian conversion needed for single bytes */
174 | nw = fwrite(vpData, waveHdr.f.nChannels * sizeof(uint8_t), numFrames, f);
175 | waveDataSize += waveHdr.f.nChannels * sizeof(uint8_t) * numFrames;
176 | return (nw == numFrames) ? 0 : 1;
177 | case 16:
178 | /* TODO: endian conversion needed */
179 | nw = fwrite(vpData, waveHdr.f.nChannels * sizeof(int16_t), numFrames, f);
180 | waveDataSize += waveHdr.f.nChannels * sizeof(int16_t) * numFrames;
181 | if ( needCleanData )
182 | {
183 | /* TODO: convert back endianness */
184 | }
185 | return (nw == numFrames) ? 0 : 1;
186 | }
187 | }
188 |
189 |
190 | int waveFinalizeHeader(FILE * f)
191 | {
192 | if (f != stdout) {
193 | assert( waveHdrStarted );
194 | waveSetCurrTime( &waveHdr.a.StopTime );
195 | waveHdr.d.hdr.size = waveDataSize;
196 | waveHdr.r.hdr.size += waveDataSize;
197 | /* fprintf(stderr, "waveFinalizeHeader(): datasize = %d\n", waveHdr.dataSize); */
198 | waveHdrStarted = 0;
199 | if ( fseek(f, 0, SEEK_SET) )
200 | return 1;
201 | if ( 1 != fwrite(&waveHdr, sizeof(waveFileHeader), 1, f) )
202 | return 1;
203 | /* fprintf(stderr, "waveFinalizeHeader(): success writing header\n"); */
204 | return 0;
205 | }
206 | return 1;
207 | }
208 |
209 | // vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab
210 |
--------------------------------------------------------------------------------
/src/wavewrite.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2019 by Hayati Ayguen
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 2 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 | #ifndef __WAVEWRITE_H
18 | #define __WAVEWRITE_H
19 |
20 | #include
21 | #include
22 | #include
23 |
24 | #ifdef __cplusplus
25 | extern "C" {
26 | #endif
27 |
28 | extern int waveHdrStarted;
29 |
30 | /*!
31 | * helper functions to write and finalize wave headers
32 | * with compatibility to some SDR programs - showing frequency:
33 | * raw sample data still have to be written by caller to FILE*.
34 | * call waveWriteHeader() before writing anything to to file
35 | * and call waveFinalizeHeader() afterwards,
36 | * stdout/stderr can't be used, because seek to begin isn't possible.
37 | *
38 | */
39 |
40 | void waveWriteHeader(unsigned samplerate, unsigned freq, int bitsPerSample, int numChannels, FILE * f);
41 |
42 | /* waveWriteFrames() writes (numFrames * numChannels) samples
43 | * waveWriteSamples()
44 | * both return 0, when no errors occured
45 | */
46 | int waveWriteFrames(FILE* f, void * vpData, size_t numFrames, int needCleanData);
47 | int waveWriteSamples(FILE* f, void * vpData, size_t numSamples, int needCleanData); /* returns 0, when no errors occured */
48 | void waveSetStartTime(time_t t, double fraction);
49 | int waveFinalizeHeader(FILE * f); /* returns 0, when no errors occured */
50 |
51 | #ifdef __cplusplus
52 | }
53 | #endif
54 |
55 | #endif /*__WAVEWRITE_H*/
56 |
--------------------------------------------------------------------------------