├── .gitignore
├── .pre-commit-config.yaml
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── README.md
├── img
├── noa-35c3.png
├── noambition.png
└── spectral.png
├── no-midi
├── Cargo.toml
├── README.md
├── src
│ └── main.rs
└── visualizer.toml
├── noa-35c3
├── Cargo.toml
├── src
│ ├── logo.png
│ ├── main.rs
│ └── shaders
│ │ ├── background.frag
│ │ ├── bokeh.frag
│ │ ├── color.frag
│ │ ├── fxaa.frag
│ │ ├── pp.vert
│ │ ├── prepass.frag
│ │ └── prepass.vert
└── visualizer.toml
├── noambition
├── Cargo.toml
├── src
│ ├── main.rs
│ └── shaders
│ │ ├── background.frag
│ │ ├── bokeh.frag
│ │ ├── color.frag
│ │ ├── fxaa.frag
│ │ ├── pp.vert
│ │ ├── prepass.frag
│ │ └── prepass.vert
└── visualizer.toml
├── spectral
├── Cargo.toml
├── src
│ └── main.rs
└── visualizer.toml
└── vis-core
├── Cargo.toml
├── README.md
├── examples
└── analyze.rs
└── src
├── analyzer
├── beat.rs
├── fourier.rs
├── mod.rs
├── samples.rs
└── spectrum.rs
├── frames.rs
├── helpers.rs
├── lib.rs
├── recorder
├── cpal.rs
├── mod.rs
└── pulse.rs
└── visualizer.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | **/*.rs.bk
3 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | # See https://pre-commit.com for more information
2 | # See https://pre-commit.com/hooks.html for more hooks
3 | repos:
4 | - repo: https://github.com/pre-commit/pre-commit-hooks
5 | rev: v2.0.0
6 | hooks:
7 | - id: trailing-whitespace
8 | - id: end-of-file-fixer
9 | - id: check-added-large-files
10 | - repo: https://github.com/doublify/pre-commit-rust
11 | rev: master
12 | hooks:
13 | - id: fmt
14 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | resolver = "2"
3 | members = [
4 | "vis-core",
5 | "spectral",
6 | "noambition",
7 | "noa-35c3",
8 | "no-midi",
9 | ]
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | GNU GENERAL PUBLIC LICENSE
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The GNU General Public License is a free, copyleft license for
12 | software and other kinds of works.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | the GNU General Public License is intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users. We, the Free Software Foundation, use the
19 | GNU General Public License for most of our software; it applies also to
20 | any other work released this way by its authors. You can apply it to
21 | your programs, too.
22 |
23 | When we speak of free software, we are referring to freedom, not
24 | price. Our General Public Licenses are designed to make sure that you
25 | have the freedom to distribute copies of free software (and charge for
26 | them if you wish), that you receive source code or can get it if you
27 | want it, that you can change the software or use pieces of it in new
28 | free programs, and that you know you can do these things.
29 |
30 | To protect your rights, we need to prevent others from denying you
31 | these rights or asking you to surrender the rights. Therefore, you have
32 | certain responsibilities if you distribute copies of the software, or if
33 | you modify it: responsibilities to respect the freedom of others.
34 |
35 | For example, if you distribute copies of such a program, whether
36 | gratis or for a fee, you must pass on to the recipients the same
37 | freedoms that you received. You must make sure that they, too, receive
38 | or can get the source code. And you must show them these terms so they
39 | know their rights.
40 |
41 | Developers that use the GNU GPL protect your rights with two steps:
42 | (1) assert copyright on the software, and (2) offer you this License
43 | giving you legal permission to copy, distribute and/or modify it.
44 |
45 | For the developers' and authors' protection, the GPL clearly explains
46 | that there is no warranty for this free software. For both users' and
47 | authors' sake, the GPL requires that modified versions be marked as
48 | changed, so that their problems will not be attributed erroneously to
49 | authors of previous versions.
50 |
51 | Some devices are designed to deny users access to install or run
52 | modified versions of the software inside them, although the manufacturer
53 | can do so. This is fundamentally incompatible with the aim of
54 | protecting users' freedom to change the software. The systematic
55 | pattern of such abuse occurs in the area of products for individuals to
56 | use, which is precisely where it is most unacceptable. Therefore, we
57 | have designed this version of the GPL to prohibit the practice for those
58 | products. If such problems arise substantially in other domains, we
59 | stand ready to extend this provision to those domains in future versions
60 | of the GPL, as needed to protect the freedom of users.
61 |
62 | Finally, every program is threatened constantly by software patents.
63 | States should not allow patents to restrict development and use of
64 | software on general-purpose computers, but in those that do, we wish to
65 | avoid the special danger that patents applied to a free program could
66 | make it effectively proprietary. To prevent this, the GPL assures that
67 | patents cannot be used to render the program non-free.
68 |
69 | The precise terms and conditions for copying, distribution and
70 | modification follow.
71 |
72 | TERMS AND CONDITIONS
73 |
74 | 0. Definitions.
75 |
76 | "This License" refers to version 3 of the GNU General Public License.
77 |
78 | "Copyright" also means copyright-like laws that apply to other kinds of
79 | works, such as semiconductor masks.
80 |
81 | "The Program" refers to any copyrightable work licensed under this
82 | License. Each licensee is addressed as "you". "Licensees" and
83 | "recipients" may be individuals or organizations.
84 |
85 | To "modify" a work means to copy from or adapt all or part of the work
86 | in a fashion requiring copyright permission, other than the making of an
87 | exact copy. The resulting work is called a "modified version" of the
88 | earlier work or a work "based on" the earlier work.
89 |
90 | A "covered work" means either the unmodified Program or a work based
91 | on the Program.
92 |
93 | To "propagate" a work means to do anything with it that, without
94 | permission, would make you directly or secondarily liable for
95 | infringement under applicable copyright law, except executing it on a
96 | computer or modifying a private copy. Propagation includes copying,
97 | distribution (with or without modification), making available to the
98 | public, and in some countries other activities as well.
99 |
100 | To "convey" a work means any kind of propagation that enables other
101 | parties to make or receive copies. Mere interaction with a user through
102 | a computer network, with no transfer of a copy, is not conveying.
103 |
104 | An interactive user interface displays "Appropriate Legal Notices"
105 | to the extent that it includes a convenient and prominently visible
106 | feature that (1) displays an appropriate copyright notice, and (2)
107 | tells the user that there is no warranty for the work (except to the
108 | extent that warranties are provided), that licensees may convey the
109 | work under this License, and how to view a copy of this License. If
110 | the interface presents a list of user commands or options, such as a
111 | menu, a prominent item in the list meets this criterion.
112 |
113 | 1. Source Code.
114 |
115 | The "source code" for a work means the preferred form of the work
116 | for making modifications to it. "Object code" means any non-source
117 | form of a work.
118 |
119 | A "Standard Interface" means an interface that either is an official
120 | standard defined by a recognized standards body, or, in the case of
121 | interfaces specified for a particular programming language, one that
122 | is widely used among developers working in that language.
123 |
124 | The "System Libraries" of an executable work include anything, other
125 | than the work as a whole, that (a) is included in the normal form of
126 | packaging a Major Component, but which is not part of that Major
127 | Component, and (b) serves only to enable use of the work with that
128 | Major Component, or to implement a Standard Interface for which an
129 | implementation is available to the public in source code form. A
130 | "Major Component", in this context, means a major essential component
131 | (kernel, window system, and so on) of the specific operating system
132 | (if any) on which the executable work runs, or a compiler used to
133 | produce the work, or an object code interpreter used to run it.
134 |
135 | The "Corresponding Source" for a work in object code form means all
136 | the source code needed to generate, install, and (for an executable
137 | work) run the object code and to modify the work, including scripts to
138 | control those activities. However, it does not include the work's
139 | System Libraries, or general-purpose tools or generally available free
140 | programs which are used unmodified in performing those activities but
141 | which are not part of the work. For example, Corresponding Source
142 | includes interface definition files associated with source files for
143 | the work, and the source code for shared libraries and dynamically
144 | linked subprograms that the work is specifically designed to require,
145 | such as by intimate data communication or control flow between those
146 | subprograms and other parts of the work.
147 |
148 | The Corresponding Source need not include anything that users
149 | can regenerate automatically from other parts of the Corresponding
150 | Source.
151 |
152 | The Corresponding Source for a work in source code form is that
153 | same work.
154 |
155 | 2. Basic Permissions.
156 |
157 | All rights granted under this License are granted for the term of
158 | copyright on the Program, and are irrevocable provided the stated
159 | conditions are met. This License explicitly affirms your unlimited
160 | permission to run the unmodified Program. The output from running a
161 | covered work is covered by this License only if the output, given its
162 | content, constitutes a covered work. This License acknowledges your
163 | rights of fair use or other equivalent, as provided by copyright law.
164 |
165 | You may make, run and propagate covered works that you do not
166 | convey, without conditions so long as your license otherwise remains
167 | in force. You may convey covered works to others for the sole purpose
168 | of having them make modifications exclusively for you, or provide you
169 | with facilities for running those works, provided that you comply with
170 | the terms of this License in conveying all material for which you do
171 | not control copyright. Those thus making or running the covered works
172 | for you must do so exclusively on your behalf, under your direction
173 | and control, on terms that prohibit them from making any copies of
174 | your copyrighted material outside their relationship with you.
175 |
176 | Conveying under any other circumstances is permitted solely under
177 | the conditions stated below. Sublicensing is not allowed; section 10
178 | makes it unnecessary.
179 |
180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
181 |
182 | No covered work shall be deemed part of an effective technological
183 | measure under any applicable law fulfilling obligations under article
184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
185 | similar laws prohibiting or restricting circumvention of such
186 | measures.
187 |
188 | When you convey a covered work, you waive any legal power to forbid
189 | circumvention of technological measures to the extent such circumvention
190 | is effected by exercising rights under this License with respect to
191 | the covered work, and you disclaim any intention to limit operation or
192 | modification of the work as a means of enforcing, against the work's
193 | users, your or third parties' legal rights to forbid circumvention of
194 | technological measures.
195 |
196 | 4. Conveying Verbatim Copies.
197 |
198 | You may convey verbatim copies of the Program's source code as you
199 | receive it, in any medium, provided that you conspicuously and
200 | appropriately publish on each copy an appropriate copyright notice;
201 | keep intact all notices stating that this License and any
202 | non-permissive terms added in accord with section 7 apply to the code;
203 | keep intact all notices of the absence of any warranty; and give all
204 | recipients a copy of this License along with the Program.
205 |
206 | You may charge any price or no price for each copy that you convey,
207 | and you may offer support or warranty protection for a fee.
208 |
209 | 5. Conveying Modified Source Versions.
210 |
211 | You may convey a work based on the Program, or the modifications to
212 | produce it from the Program, in the form of source code under the
213 | terms of section 4, provided that you also meet all of these conditions:
214 |
215 | a) The work must carry prominent notices stating that you modified
216 | it, and giving a relevant date.
217 |
218 | b) The work must carry prominent notices stating that it is
219 | released under this License and any conditions added under section
220 | 7. This requirement modifies the requirement in section 4 to
221 | "keep intact all notices".
222 |
223 | c) You must license the entire work, as a whole, under this
224 | License to anyone who comes into possession of a copy. This
225 | License will therefore apply, along with any applicable section 7
226 | additional terms, to the whole of the work, and all its parts,
227 | regardless of how they are packaged. This License gives no
228 | permission to license the work in any other way, but it does not
229 | invalidate such permission if you have separately received it.
230 |
231 | d) If the work has interactive user interfaces, each must display
232 | Appropriate Legal Notices; however, if the Program has interactive
233 | interfaces that do not display Appropriate Legal Notices, your
234 | work need not make them do so.
235 |
236 | A compilation of a covered work with other separate and independent
237 | works, which are not by their nature extensions of the covered work,
238 | and which are not combined with it such as to form a larger program,
239 | in or on a volume of a storage or distribution medium, is called an
240 | "aggregate" if the compilation and its resulting copyright are not
241 | used to limit the access or legal rights of the compilation's users
242 | beyond what the individual works permit. Inclusion of a covered work
243 | in an aggregate does not cause this License to apply to the other
244 | parts of the aggregate.
245 |
246 | 6. Conveying Non-Source Forms.
247 |
248 | You may convey a covered work in object code form under the terms
249 | of sections 4 and 5, provided that you also convey the
250 | machine-readable Corresponding Source under the terms of this License,
251 | in one of these ways:
252 |
253 | a) Convey the object code in, or embodied in, a physical product
254 | (including a physical distribution medium), accompanied by the
255 | Corresponding Source fixed on a durable physical medium
256 | customarily used for software interchange.
257 |
258 | b) Convey the object code in, or embodied in, a physical product
259 | (including a physical distribution medium), accompanied by a
260 | written offer, valid for at least three years and valid for as
261 | long as you offer spare parts or customer support for that product
262 | model, to give anyone who possesses the object code either (1) a
263 | copy of the Corresponding Source for all the software in the
264 | product that is covered by this License, on a durable physical
265 | medium customarily used for software interchange, for a price no
266 | more than your reasonable cost of physically performing this
267 | conveying of source, or (2) access to copy the
268 | Corresponding Source from a network server at no charge.
269 |
270 | c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
275 |
276 | d) Convey the object code by offering access from a designated
277 | place (gratis or for a charge), and offer equivalent access to the
278 | Corresponding Source in the same way through the same place at no
279 | further charge. You need not require recipients to copy the
280 | Corresponding Source along with the object code. If the place to
281 | copy the object code is a network server, the Corresponding Source
282 | may be on a different server (operated by you or a third party)
283 | that supports equivalent copying facilities, provided you maintain
284 | clear directions next to the object code saying where to find the
285 | Corresponding Source. Regardless of what server hosts the
286 | Corresponding Source, you remain obligated to ensure that it is
287 | available for as long as needed to satisfy these requirements.
288 |
289 | e) Convey the object code using peer-to-peer transmission, provided
290 | you inform other peers where the object code and Corresponding
291 | Source of the work are being offered to the general public at no
292 | charge under subsection 6d.
293 |
294 | A separable portion of the object code, whose source code is excluded
295 | from the Corresponding Source as a System Library, need not be
296 | included in conveying the object code work.
297 |
298 | A "User Product" is either (1) a "consumer product", which means any
299 | tangible personal property which is normally used for personal, family,
300 | or household purposes, or (2) anything designed or sold for incorporation
301 | into a dwelling. In determining whether a product is a consumer product,
302 | doubtful cases shall be resolved in favor of coverage. For a particular
303 | product received by a particular user, "normally used" refers to a
304 | typical or common use of that class of product, regardless of the status
305 | of the particular user or of the way in which the particular user
306 | actually uses, or expects or is expected to use, the product. A product
307 | is a consumer product regardless of whether the product has substantial
308 | commercial, industrial or non-consumer uses, unless such uses represent
309 | the only significant mode of use of the product.
310 |
311 | "Installation Information" for a User Product means any methods,
312 | procedures, authorization keys, or other information required to install
313 | and execute modified versions of a covered work in that User Product from
314 | a modified version of its Corresponding Source. The information must
315 | suffice to ensure that the continued functioning of the modified object
316 | code is in no case prevented or interfered with solely because
317 | modification has been made.
318 |
319 | If you convey an object code work under this section in, or with, or
320 | specifically for use in, a User Product, and the conveying occurs as
321 | part of a transaction in which the right of possession and use of the
322 | User Product is transferred to the recipient in perpetuity or for a
323 | fixed term (regardless of how the transaction is characterized), the
324 | Corresponding Source conveyed under this section must be accompanied
325 | by the Installation Information. But this requirement does not apply
326 | if neither you nor any third party retains the ability to install
327 | modified object code on the User Product (for example, the work has
328 | been installed in ROM).
329 |
330 | The requirement to provide Installation Information does not include a
331 | requirement to continue to provide support service, warranty, or updates
332 | for a work that has been modified or installed by the recipient, or for
333 | the User Product in which it has been modified or installed. Access to a
334 | network may be denied when the modification itself materially and
335 | adversely affects the operation of the network or violates the rules and
336 | protocols for communication across the network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders of
364 | that material) supplement the terms of this License with terms:
365 |
366 | a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
368 |
369 | b) Requiring preservation of specified reasonable legal notices or
370 | author attributions in that material or in the Appropriate Legal
371 | Notices displayed by works containing it; or
372 |
373 | c) Prohibiting misrepresentation of the origin of that material, or
374 | requiring that modified versions of such material be marked in
375 | reasonable ways as different from the original version; or
376 |
377 | d) Limiting the use for publicity purposes of names of licensors or
378 | authors of the material; or
379 |
380 | e) Declining to grant rights under trademark law for use of some
381 | trade names, trademarks, or service marks; or
382 |
383 | f) Requiring indemnification of licensors and authors of that
384 | material by anyone who conveys the material (or modified versions of
385 | it) with contractual assumptions of liability to the recipient, for
386 | any liability that these contractual assumptions directly impose on
387 | those licensors and authors.
388 |
389 | All other non-permissive additional terms are considered "further
390 | restrictions" within the meaning of section 10. If the Program as you
391 | received it, or any part of it, contains a notice stating that it is
392 | governed by this License along with a term that is a further
393 | restriction, you may remove that term. If a license document contains
394 | a further restriction but permits relicensing or conveying under this
395 | License, you may add to a covered work material governed by the terms
396 | of that license document, provided that the further restriction does
397 | not survive such relicensing or conveying.
398 |
399 | If you add terms to a covered work in accord with this section, you
400 | must place, in the relevant source files, a statement of the
401 | additional terms that apply to those files, or a notice indicating
402 | where to find the applicable terms.
403 |
404 | Additional terms, permissive or non-permissive, may be stated in the
405 | form of a separately written license, or stated as exceptions;
406 | the above requirements apply either way.
407 |
408 | 8. Termination.
409 |
410 | You may not propagate or modify a covered work except as expressly
411 | provided under this License. Any attempt otherwise to propagate or
412 | modify it is void, and will automatically terminate your rights under
413 | this License (including any patent licenses granted under the third
414 | paragraph of section 11).
415 |
416 | However, if you cease all violation of this License, then your
417 | license from a particular copyright holder is reinstated (a)
418 | provisionally, unless and until the copyright holder explicitly and
419 | finally terminates your license, and (b) permanently, if the copyright
420 | holder fails to notify you of the violation by some reasonable means
421 | prior to 60 days after the cessation.
422 |
423 | Moreover, your license from a particular copyright holder is
424 | reinstated permanently if the copyright holder notifies you of the
425 | violation by some reasonable means, this is the first time you have
426 | received notice of violation of this License (for any work) from that
427 | copyright holder, and you cure the violation prior to 30 days after
428 | your receipt of the notice.
429 |
430 | Termination of your rights under this section does not terminate the
431 | licenses of parties who have received copies or rights from you under
432 | this License. If your rights have been terminated and not permanently
433 | reinstated, you do not qualify to receive new licenses for the same
434 | material under section 10.
435 |
436 | 9. Acceptance Not Required for Having Copies.
437 |
438 | You are not required to accept this License in order to receive or
439 | run a copy of the Program. Ancillary propagation of a covered work
440 | occurring solely as a consequence of using peer-to-peer transmission
441 | to receive a copy likewise does not require acceptance. However,
442 | nothing other than this License grants you permission to propagate or
443 | modify any covered work. These actions infringe copyright if you do
444 | not accept this License. Therefore, by modifying or propagating a
445 | covered work, you indicate your acceptance of this License to do so.
446 |
447 | 10. Automatic Licensing of Downstream Recipients.
448 |
449 | Each time you convey a covered work, the recipient automatically
450 | receives a license from the original licensors, to run, modify and
451 | propagate that work, subject to this License. You are not responsible
452 | for enforcing compliance by third parties with this License.
453 |
454 | An "entity transaction" is a transaction transferring control of an
455 | organization, or substantially all assets of one, or subdividing an
456 | organization, or merging organizations. If propagation of a covered
457 | work results from an entity transaction, each party to that
458 | transaction who receives a copy of the work also receives whatever
459 | licenses to the work the party's predecessor in interest had or could
460 | give under the previous paragraph, plus a right to possession of the
461 | Corresponding Source of the work from the predecessor in interest, if
462 | the predecessor has it or can get it with reasonable efforts.
463 |
464 | You may not impose any further restrictions on the exercise of the
465 | rights granted or affirmed under this License. For example, you may
466 | not impose a license fee, royalty, or other charge for exercise of
467 | rights granted under this License, and you may not initiate litigation
468 | (including a cross-claim or counterclaim in a lawsuit) alleging that
469 | any patent claim is infringed by making, using, selling, offering for
470 | sale, or importing the Program or any portion of it.
471 |
472 | 11. Patents.
473 |
474 | A "contributor" is a copyright holder who authorizes use under this
475 | License of the Program or a work on which the Program is based. The
476 | work thus licensed is called the contributor's "contributor version".
477 |
478 | A contributor's "essential patent claims" are all patent claims
479 | owned or controlled by the contributor, whether already acquired or
480 | hereafter acquired, that would be infringed by some manner, permitted
481 | by this License, of making, using, or selling its contributor version,
482 | but do not include claims that would be infringed only as a
483 | consequence of further modification of the contributor version. For
484 | purposes of this definition, "control" includes the right to grant
485 | patent sublicenses in a manner consistent with the requirements of
486 | this License.
487 |
488 | Each contributor grants you a non-exclusive, worldwide, royalty-free
489 | patent license under the contributor's essential patent claims, to
490 | make, use, sell, offer for sale, import and otherwise run, modify and
491 | propagate the contents of its contributor version.
492 |
493 | In the following three paragraphs, a "patent license" is any express
494 | agreement or commitment, however denominated, not to enforce a patent
495 | (such as an express permission to practice a patent or covenant not to
496 | sue for patent infringement). To "grant" such a patent license to a
497 | party means to make such an agreement or commitment not to enforce a
498 | patent against the party.
499 |
500 | If you convey a covered work, knowingly relying on a patent license,
501 | and the Corresponding Source of the work is not available for anyone
502 | to copy, free of charge and under the terms of this License, through a
503 | publicly available network server or other readily accessible means,
504 | then you must either (1) cause the Corresponding Source to be so
505 | available, or (2) arrange to deprive yourself of the benefit of the
506 | patent license for this particular work, or (3) arrange, in a manner
507 | consistent with the requirements of this License, to extend the patent
508 | license to downstream recipients. "Knowingly relying" means you have
509 | actual knowledge that, but for the patent license, your conveying the
510 | covered work in a country, or your recipient's use of the covered work
511 | in a country, would infringe one or more identifiable patents in that
512 | country that you have reason to believe are valid.
513 |
514 | If, pursuant to or in connection with a single transaction or
515 | arrangement, you convey, or propagate by procuring conveyance of, a
516 | covered work, and grant a patent license to some of the parties
517 | receiving the covered work authorizing them to use, propagate, modify
518 | or convey a specific copy of the covered work, then the patent license
519 | you grant is automatically extended to all recipients of the covered
520 | work and works based on it.
521 |
522 | A patent license is "discriminatory" if it does not include within
523 | the scope of its coverage, prohibits the exercise of, or is
524 | conditioned on the non-exercise of one or more of the rights that are
525 | specifically granted under this License. You may not convey a covered
526 | work if you are a party to an arrangement with a third party that is
527 | in the business of distributing software, under which you make payment
528 | to the third party based on the extent of your activity of conveying
529 | the work, and under which the third party grants, to any of the
530 | parties who would receive the covered work from you, a discriminatory
531 | patent license (a) in connection with copies of the covered work
532 | conveyed by you (or copies made from those copies), or (b) primarily
533 | for and in connection with specific products or compilations that
534 | contain the covered work, unless you entered into that arrangement,
535 | or that patent license was granted, prior to 28 March 2007.
536 |
537 | Nothing in this License shall be construed as excluding or limiting
538 | any implied license or other defenses to infringement that may
539 | otherwise be available to you under applicable patent law.
540 |
541 | 12. No Surrender of Others' Freedom.
542 |
543 | If conditions are imposed on you (whether by court order, agreement or
544 | otherwise) that contradict the conditions of this License, they do not
545 | excuse you from the conditions of this License. If you cannot convey a
546 | covered work so as to satisfy simultaneously your obligations under this
547 | License and any other pertinent obligations, then as a consequence you may
548 | not convey it at all. For example, if you agree to terms that obligate you
549 | to collect a royalty for further conveying from those to whom you convey
550 | the Program, the only way you could satisfy both those terms and this
551 | License would be to refrain entirely from conveying the Program.
552 |
553 | 13. Use with the GNU Affero General Public License.
554 |
555 | Notwithstanding any other provision of this License, you have
556 | permission to link or combine any covered work with a work licensed
557 | under version 3 of the GNU Affero General Public License into a single
558 | combined work, and to convey the resulting work. The terms of this
559 | License will continue to apply to the part which is the covered work,
560 | but the special requirements of the GNU Affero General Public License,
561 | section 13, concerning interaction through a network will apply to the
562 | combination as such.
563 |
564 | 14. Revised Versions of this License.
565 |
566 | The Free Software Foundation may publish revised and/or new versions of
567 | the GNU General Public License from time to time. Such new versions will
568 | be similar in spirit to the present version, but may differ in detail to
569 | address new problems or concerns.
570 |
571 | Each version is given a distinguishing version number. If the
572 | Program specifies that a certain numbered version of the GNU General
573 | Public License "or any later version" applies to it, you have the
574 | option of following the terms and conditions either of that numbered
575 | version or of any later version published by the Free Software
576 | Foundation. If the Program does not specify a version number of the
577 | GNU General Public License, you may choose any version ever published
578 | by the Free Software Foundation.
579 |
580 | If the Program specifies that a proxy can decide which future
581 | versions of the GNU General Public License can be used, that proxy's
582 | public statement of acceptance of a version permanently authorizes you
583 | to choose that version for the Program.
584 |
585 | Later license versions may give you additional or different
586 | permissions. However, no additional obligations are imposed on any
587 | author or copyright holder as a result of your choosing to follow a
588 | later version.
589 |
590 | 15. Disclaimer of Warranty.
591 |
592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
600 |
601 | 16. Limitation of Liability.
602 |
603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
611 | SUCH DAMAGES.
612 |
613 | 17. Interpretation of Sections 15 and 16.
614 |
615 | If the disclaimer of warranty and limitation of liability provided
616 | above cannot be given local legal effect according to their terms,
617 | reviewing courts shall apply local law that most closely approximates
618 | an absolute waiver of all civil liability in connection with the
619 | Program, unless a warranty or assumption of liability accompanies a
620 | copy of the Program in return for a fee.
621 |
622 | END OF TERMS AND CONDITIONS
623 |
624 | How to Apply These Terms to Your New Programs
625 |
626 | If you develop a new program, and you want it to be of the greatest
627 | possible use to the public, the best way to achieve this is to make it
628 | free software which everyone can redistribute and change under these terms.
629 |
630 | To do so, attach the following notices to the program. It is safest
631 | to attach them to the start of each source file to most effectively
632 | state the exclusion of warranty; and each file should have at least
633 | the "copyright" line and a pointer to where the full notice is found.
634 |
635 |
636 | Copyright (C)
637 |
638 | This program is free software: you can redistribute it and/or modify
639 | it under the terms of the GNU General Public License as published by
640 | the Free Software Foundation, either version 3 of the License, or
641 | (at your option) any later version.
642 |
643 | This program is distributed in the hope that it will be useful,
644 | but WITHOUT ANY WARRANTY; without even the implied warranty of
645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
646 | GNU General Public License for more details.
647 |
648 | You should have received a copy of the GNU General Public License
649 | along with this program. If not, see .
650 |
651 | Also add information on how to contact you by electronic and paper mail.
652 |
653 | If the program does terminal interaction, make it output a short
654 | notice like this when it starts in an interactive mode:
655 |
656 | Copyright (C)
657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
658 | This is free software, and you are welcome to redistribute it
659 | under certain conditions; type `show c' for details.
660 |
661 | The hypothetical commands `show w' and `show c' should show the appropriate
662 | parts of the General Public License. Of course, your program's commands
663 | might be different; for a GUI interface, you would use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or school,
666 | if any, to sign a "copyright disclaimer" for the program, if necessary.
667 | For more information on this, and how to apply and follow the GNU GPL, see
668 | .
669 |
670 | The GNU General Public License does not permit incorporating your program
671 | into proprietary programs. If your program is a subroutine library, you
672 | may consider it more useful to permit linking proprietary applications with
673 | the library. If this is what you want to do, use the GNU Lesser General
674 | Public License instead of this License. But first, please read
675 | .
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | visualizer2
2 | ===========
3 |
4 | Audio-Visualization in Rust. *visualizer2* is my second (actually third) attempt at creating pretty visuals that somehow behave in sync with a live audio signal. The first attempt can be found [here](https://github.com/Rahix/pa-visualizer).
5 |
6 | ## Visualizers
7 | There are a few ready to use visualizers in this repository:
8 |
9 | ### noambition
10 | Based on the *noambition* visualizer from [pa-visualizer](https://github.com/Rahix/pa-visualizer), which in turn is based on the demo [No Ambition](http://www.pouet.net/prod.php?which=69730) by Quite & T-Rex. That said, this version no longer has a lot of similarities ...
11 |
12 | 
13 |
14 | ### noa-35c3
15 | Version of *noambition* that was adapted for 35c3.
16 |
17 | 
18 |
19 | ### no-midi
20 | A visualizer which sends MIDI commands. These MIDI commands can be fed into a lighting controller to then control fancy event lighting equipment.
21 |
22 | Check the [no-midi README](./no-midi/README.md) for more info.
23 |
24 | ### spectral
25 | A debug spectral display.
26 |
27 | 
28 |
29 | ## Project Structure
30 | The core concept of *visualizer2* is the following: The [`vis-core`](./vis-core) crate contains all the glue logic and building blocks for analyzing the audio signal. The goal is that creating a new visualizer needs as little boilerplate as possible. In practice, the following code is all you need to get started:
31 |
32 | ```rust
33 | // The data-type for storing analyzer results
34 | #[derive(Debug, Clone)]
35 | pub struct AnalyzerResult {
36 | spectrum: vis_core::analyzer::Spectrum>,
37 | volume: f32,
38 | beat: f32,
39 | }
40 |
41 | fn main() {
42 | // Initialize the logger. Take a look at the sources if you want to customize
43 | // the logger.
44 | vis_core::default_log();
45 |
46 | // Load the default config source. More about config later on. You can also
47 | // do this manually if you have special requirements.
48 | vis_core::default_config();
49 |
50 | // Initialize some analyzer-tools. These will be moved into the analyzer closure
51 | // later on.
52 | let mut analyzer = vis_core::analyzer::FourierBuilder::new()
53 | .length(512)
54 | .window(vis_core::analyzer::window::nuttall)
55 | .plan();
56 |
57 | let spectrum = vis_core::analyzer::Spectrum::new(vec![0.0; analyzer.buckets], 0.0, 1.0);
58 |
59 | let mut frames = vis_core::Visualizer::new(
60 | AnalyzerResult {
61 | spectrum,
62 | volume: 0.0,
63 | beat: 0.0,
64 | },
65 | // This closure is the "analyzer". It will be executed in a loop to always
66 | // have the latest data available.
67 | move |info, samples| {
68 | analyzer.analyze(samples);
69 |
70 | info.spectrum.fill_from(&analyzer.average());
71 | info.volume = samples.volume(0.3) * 400.0;
72 | info.beat = info.spectrum.slice(50.0, 100.0).max() * 0.01;
73 | info
74 | },
75 | )
76 | // Build the frame iterator which is the base of your loop later on
77 | .frames();
78 |
79 | for frame in frames.iter() {
80 | // This is just a primitive example, your vis core belongs here
81 |
82 | frame.lock_info(|info| {
83 | for _ in 0..info.volume as usize {
84 | print!("#");
85 | }
86 | println!("");
87 | });
88 | std::thread::sleep_ms(30);
89 | }
90 | }
91 | ```
92 |
93 | ## Architecture
94 | In live mode, *visualizer2* runs three loops:
95 |
96 | 1. The **recorder**, which acquires samples from somewhere (pulseaudio by default) and pushes them into the sample-buffer.
97 | 2. The **analyzer**, which calculates some information from the sample-buffer. Common are spectral analysis or beat-detection. The *analyzer* is actually written by **you**, so you have maximum freedom with what you need.
98 | 3. The **renderer**, which is the applications main thread. Here you consume the latest info from the *analyzer* and create visuals with it.
99 |
100 | ### Recorder
101 | By default, *visualizer2* uses *pulseaudio*, but it is really easy to use another audio source. You just have to implement an alternative recorder. For an example take a look at the `pulse` recorder.
102 |
103 | ### Analyzer
104 | The *analyzer* consists of a closure and a data-type that contains all info shared with the *renderer*. There are a few things to note:
105 |
106 | * To enable lock-free sharing of the info, the info-type needs to be `Clone`.
107 | * While the analyzer gets an `&mut info`, you can **not** make any assumptions about its contents apart from it being filled with either the initial value or the result of *some* (most likely **not** the last!) analyzer run.
108 | * If you need data from the last analyzer run, you have to keep track of that locally, easiest by capturing a variable in the analyzer closure.
109 |
110 | ### Renderer
111 | This part is completely up to you. `vis-core` gives you an iterator that you should trigger once a frame and that allows access to the info from the analyzer. In most cases you will be using a loop like this:
112 |
113 | ```rust
114 | for frame in frames.iter() {
115 | println!("Frame: {}", frame.frame);
116 | println!("Time since start: {}", frame.time);
117 | }
118 | ```
119 |
120 | ## Configuration
121 | During the process of writing multiple different versions of this system I also wrote [`ezconf`](https://github.com/Rahix/ezconf). This is now the configuration system used in all parts of `vis-core`. The design philosophy is the following:
122 |
123 | * Components (like a `FourierAnalyzer` or a `BeatDetector`) are created using a builder pattern.
124 | * All fields not explicitly set with the builder will be read from the configuration source. This allows easily changing parameters without recompiling each time.
125 |
126 | Additionally, the final configuration will be logged in debug builds.
127 |
128 | I encourage using the same system for your graphics code because it allows quickly iterating on certain settings which is more fun than waiting for the compiler each time. To use the config:
129 |
130 | ```rust
131 | let some_configurable_setting = vis_core::CONFIG.get_or(
132 | // Toml path to the value
133 | "myvis.foo.bar",
134 | // Default value, type will be inferred from this
135 | 123.456
136 | )
137 | ```
138 |
139 | ### Config Source
140 | By default, when calling `vis_core::default_config()`, `vis-core` searches for a file named `visualizer.toml` in the current working directory. If you want a different file to be used, you can instead initialize the config yourself manually.
141 |
142 |
143 | ## Analyzer Tools
144 | `vis-core` includes a few tools for analyzing the audio signal. Look at each ones docs for more info:
145 |
146 | * [`FourierAnalyzer`](./vis-core/src/analyzer/fourier.rs) - Does a fourier transform on the latest samples and returns a spectrum
147 | * [`Spectrum`](./vis-core/src/analyzer/spectrum.rs) - A flexible representation of a spectrum. Has methods for taking a subspectrum (`slice`), filling into a smaller number of buckets (`fill_buckets`), and finding maxima (`find_maxima`). There is also `average_spectrum` to average multiple spectra.
148 | * [`BeatDetector`](./vis-core/src/analyzer/beat.rs) - A beat detector that allows triggering certain effects as soon as a beat happens. Tries to introduce as little delay as possible!
149 |
150 | ## License
151 |
152 | *visualizer2* is licensed under the `GNU General Public License v3.0 or later`. See [LICENSE](LICENSE) for more info.
153 |
--------------------------------------------------------------------------------
/img/noa-35c3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/img/noa-35c3.png
--------------------------------------------------------------------------------
/img/noambition.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/img/noambition.png
--------------------------------------------------------------------------------
/img/spectral.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/img/spectral.png
--------------------------------------------------------------------------------
/no-midi/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Rahix "]
3 | edition = "2021"
4 | name = "no-midi"
5 | version = "0.1.0"
6 |
7 | [dependencies]
8 | log = "0.4.6"
9 | midir = "0.9.1"
10 | rand = "0.8.5"
11 |
12 | [dependencies.vis-core]
13 | path = "../vis-core"
14 |
--------------------------------------------------------------------------------
/no-midi/README.md:
--------------------------------------------------------------------------------
1 | no-midi
2 | =======
3 | A visualizer which sends MIDI commands. These MIDI commands can be fed into a lighting controller to then control fancy event lighting equipment.
4 |
5 | Events are sent as NOTE_ON/NOTE_OFF messages. The following notes are mapped:
6 |
7 | | MIDI Note | Meaning |
8 | | --- | --- |
9 | | 50 <= n < 60 | ON/OFF for the 10 frequency channels. The 4 highest channels are ON, rest OFF. I map this to 10 non-overlapping light scenes. |
10 | | 66 | ON when a beat hits, OFF 100ms later unless a further beat immediately follows. I like to trigger strobe lights on this. |
11 | | 70 | Volume as note velocity. |
12 |
--------------------------------------------------------------------------------
/no-midi/src/main.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate log;
3 | use midir::{MidiOutput, MidiOutputPort};
4 |
5 |
6 | use vis_core::analyzer;
7 |
8 | #[derive(Debug, Clone)]
9 | pub struct VisInfo {
10 | beat: u64,
11 | beat_volume: f32,
12 | volume: f32,
13 | analyzer: analyzer::FourierAnalyzer,
14 | spectrum: analyzer::Spectrum>,
15 | }
16 |
17 | fn main() {
18 | vis_core::default_config();
19 | vis_core::default_log();
20 |
21 | let mut frames = {
22 | // Analyzer {{{
23 | let mut beat = analyzer::BeatBuilder::new().build();
24 | let mut beat_num = 0;
25 |
26 | let analyzer = analyzer::FourierBuilder::new().plan();
27 |
28 | vis_core::Visualizer::new(
29 | VisInfo {
30 | beat: 0,
31 | beat_volume: 0.0,
32 | volume: 0.0,
33 | spectrum: analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1000.0),
34 | analyzer,
35 | },
36 | move |info, samples| {
37 | if beat.detect(&samples) {
38 | beat_num += 1;
39 | }
40 | info.beat = beat_num;
41 | info.beat_volume = beat.last_volume();
42 | info.volume = samples.volume(0.3);
43 |
44 | info.analyzer.analyze(&samples);
45 | info.spectrum.fill_from(&info.analyzer.average());
46 |
47 | info
48 | },
49 | )
50 | .async_analyzer(300)
51 | .frames()
52 | // }}}
53 | };
54 |
55 | // Config {{{
56 |
57 | // Columns
58 | let notes_num = 10;
59 | let slowdown = vis_core::CONFIG.get_or("noa.cols.slowdown", 0.95);
60 |
61 | let frame_time =
62 | std::time::Duration::from_micros(1000000 / vis_core::CONFIG.get_or("noa.fps", 30));
63 |
64 | let note_roll_size = vis_core::CONFIG.get_or("noa.cols.note_roll", 20) as f32;
65 |
66 | // }}}
67 |
68 | let midi_out = MidiOutput::new("no-midi Music Visualizer").unwrap();
69 |
70 | // Get an output port (read from console if multiple are available)
71 | let out_ports = midi_out.ports();
72 | let out_port: &MidiOutputPort = match out_ports.len() {
73 | 0 => panic!("no MIDI output port found"),
74 | _ => {
75 | log::debug!("Available output ports:");
76 | for p in out_ports.iter() {
77 | log::debug!(" - {}", midi_out.port_name(p).unwrap());
78 | }
79 |
80 | if let Some(want_port) = vis_core::CONFIG.get::("midi.output_port") {
81 | let mut out_port = None;
82 | for p in out_ports.iter() {
83 | if want_port == midi_out.port_name(p).unwrap() {
84 | log::debug!("Chose wanted MIDI output port {:?}", want_port);
85 | out_port = Some(p);
86 | }
87 | }
88 | out_port.unwrap_or_else(|| {
89 | panic!("Wanted MIDI output port {:?} not found!", want_port)
90 | })
91 | } else {
92 | log::debug!("Choosing MIDI port {:?}", midi_out.port_name(&out_ports[0]));
93 | &out_ports[0]
94 | }
95 | }
96 | };
97 | let mut conn_out = midi_out.connect(out_port, "midir-test").unwrap();
98 |
99 | let mut previous_time = 0.0;
100 | let mut rolling_volume = 0.0;
101 | let mut last_beat = -100.0;
102 |
103 | let mut notes_spectrum = analyzer::Spectrum::new(vec![0.0; notes_num], 220.0, 660.0);
104 | let mut notes_rolling_buf = vec![0.0; notes_num];
105 |
106 | let mut last_beat_num = 0;
107 |
108 | let mut maxima_buf = [(0.0, 0.0); 8];
109 |
110 | let mut previous_columns = vec![false; notes_num];
111 | let mut beat_ended = true;
112 |
113 | for frame in frames.iter() {
114 |
115 | let start = std::time::Instant::now();
116 | let delta = frame.time - previous_time;
117 | trace!("Delta: {}s", delta);
118 |
119 | // Audio Info Retrieval {{{
120 | let (_volume, maxima, notes_rolling_spectrum, _base_volume) = frame.info(|info| {
121 | rolling_volume = info.volume.max(rolling_volume * slowdown);
122 |
123 | if info.beat != last_beat_num {
124 | last_beat = frame.time;
125 | last_beat_num = info.beat;
126 | beat_ended = false;
127 | }
128 |
129 | let notes_spectrum = info.spectrum.fill_spectrum(&mut notes_spectrum);
130 |
131 | for (n, s) in notes_rolling_buf.iter_mut().zip(notes_spectrum.iter()) {
132 | *n = (*n * (note_roll_size - 1.0) + s) / note_roll_size;
133 | }
134 | let notes_rolling_spectrum = vis_core::analyzer::Spectrum::new(
135 | &mut *notes_rolling_buf,
136 | notes_spectrum.lowest(),
137 | notes_spectrum.highest(),
138 | );
139 |
140 | let maxima = notes_rolling_spectrum.find_maxima(&mut maxima_buf);
141 |
142 | (
143 | info.volume,
144 | maxima,
145 | notes_rolling_spectrum,
146 | info.beat_volume,
147 | )
148 | });
149 | // }}}
150 |
151 | const NOTE_ON_MSG: u8 = 0x90;
152 | const NOTE_OFF_MSG: u8 = 0x80;
153 | const VELOCITY: u8 = 0x7f;
154 |
155 | // let vol_float = (rolling_volume.powf(0.5) / 0.50).min(1.0).powi(2).max(0.15);
156 | let vol_float = (((rolling_volume / 0.18).powf(0.6) - 0.2) / 0.8).min(1.0).max(0.15);
157 | let vol = (vol_float * 127.0) as u8;
158 | conn_out.send(&[NOTE_ON_MSG, 70 as u8, vol]).unwrap();
159 |
160 | let beat_dur = 0.1;
161 | if frame.time == last_beat && vol_float != 0.15 {
162 | conn_out.send(&[NOTE_ON_MSG, 66 as u8, VELOCITY]).unwrap();
163 | } else if frame.time - last_beat > beat_dur && !beat_ended {
164 | conn_out.send(&[NOTE_OFF_MSG, 66 as u8, VELOCITY]).unwrap();
165 | beat_ended = true;
166 | }
167 |
168 | let chars = if frame.time - last_beat <= beat_dur && vol_float != 0.15 {
169 | "XX"
170 | } else {
171 | " "
172 | };
173 |
174 | let mut columns = vec![false; notes_num];
175 | for (f, _) in maxima.iter().take(3) {
176 | let note = notes_rolling_spectrum.freq_to_id(*f);
177 | columns[note] = true;
178 | }
179 |
180 | for (i, (prev, now)) in previous_columns.iter().copied().zip(columns.iter().copied()).enumerate() {
181 | if !prev && now {
182 | conn_out.send(&[NOTE_ON_MSG, 50 + i as u8, VELOCITY]).unwrap();
183 | } else if prev && !now {
184 | conn_out.send(&[NOTE_OFF_MSG, 50 + i as u8, VELOCITY]).unwrap();
185 | }
186 | }
187 |
188 | if columns[0] {
189 | print!("\x1B[48;2;92;38;134m{}", chars);
190 | } else {
191 | print!("\x1B[0m{}", chars);
192 | }
193 | if columns[1] {
194 | print!("\x1B[48;2;255;22;144m{}", chars);
195 | } else {
196 | print!("\x1B[0m{}", chars);
197 | }
198 | if columns[2] {
199 | print!("\x1B[48;2;244;214;118m{}", chars);
200 | } else {
201 | print!("\x1B[0m{}", chars);
202 | }
203 | if columns[3] {
204 | print!("\x1B[48;2;54;205;196m{}", chars);
205 | } else {
206 | print!("\x1B[0m{}", chars);
207 | }
208 | if columns[4] {
209 | print!("\x1B[48;2;92;38;134m{}", chars);
210 | } else {
211 | print!("\x1B[0m{}", chars);
212 | }
213 | if columns[5] {
214 | print!("\x1B[48;2;255;22;144m{}", chars);
215 | } else {
216 | print!("\x1B[0m{}", chars);
217 | }
218 | if columns[6] {
219 | print!("\x1B[48;2;244;214;118m{}", chars);
220 | } else {
221 | print!("\x1B[0m{}", chars);
222 | }
223 | if columns[7] {
224 | print!("\x1B[48;2;54;205;196m{}", chars);
225 | } else {
226 | print!("\x1B[0m{}", chars);
227 | }
228 | if columns[8] {
229 | print!("\x1B[48;2;92;38;134m{}", chars);
230 | } else {
231 | print!("\x1B[0m{}", chars);
232 | }
233 | if columns[9] {
234 | print!("\x1B[48;2;255;22;144m{}", chars);
235 | } else {
236 | print!("\x1B[0m{}", chars);
237 | }
238 | print!("\x1B[0m| ");
239 |
240 | for i in 0..64 {
241 | if i < vol /2 {
242 | print!("=");
243 | } else {
244 | print!(" ");
245 | }
246 | }
247 |
248 | print!(" {vol_float:5.3}");
249 |
250 | println!("");
251 |
252 |
253 |
254 | previous_time = frame.time;
255 | previous_columns = columns;
256 |
257 | let end = std::time::Instant::now();
258 | let dur = end - start;
259 | if dur < frame_time {
260 | let sleep = frame_time - dur;
261 | std::thread::sleep(sleep);
262 | }
263 | }
264 | }
265 |
--------------------------------------------------------------------------------
/no-midi/visualizer.toml:
--------------------------------------------------------------------------------
1 | [audio]
2 | window = "nuttall"
3 | conversions = 300
4 | rate = 8000
5 | read_size = 256
6 | recorder = "cpal"
7 |
8 | [midi]
9 | # If you want to select a specific port:
10 | #
11 | # output_port = "Midi Through:Midi Through Port-0 14:0"
12 |
13 | [noa]
14 | fps = 40
15 |
16 | [noa.cols]
17 | rows = 50
18 | num = 30
19 | depth = 30.0
20 | mid_dist = 0.1
21 | speed = 0.1
22 | slowdown = 0.95
23 | speed_deviation = 50.0
24 | width = 10.0
25 | note_width = 6
26 | colors = [
27 | [1.000000, 0.007443, 0.318893, 1.0],
28 | [0.915586, 0.704283, 0.214133, 1.0],
29 | [0.044844, 0.646290, 0.590788, 1.0],
30 | [0.130165, 0.022207, 0.276140, 1.0],
31 | [1.000000, 0.007443, 0.318893, 1.0],
32 | [0.915586, 0.704283, 0.214133, 1.0],
33 | [0.044844, 0.646290, 0.590788, 1.0],
34 | [0.130165, 0.022207, 0.276140, 1.0],
35 | [1.000000, 0.007443, 0.318893, 1.0],
36 | [0.915586, 0.704283, 0.214133, 1.0],
37 | [0.044844, 0.646290, 0.590788, 1.0],
38 | [0.130165, 0.022207, 0.276140, 1.0],
39 | ]
40 |
41 | amp_top = 0.7
42 | amp_bottom = 0.2
43 |
44 | [noa.camera]
45 | height = 1.0
46 | look_height = 0.8
47 |
--------------------------------------------------------------------------------
/noa-35c3/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Rahix "]
3 | edition = "2018"
4 | name = "noa-35c3"
5 | version = "0.1.0"
6 |
7 | [dependencies]
8 | glium = "0.32.1"
9 | image = "0.24.5"
10 | log = "0.4.17"
11 | nalgebra = "0.32.1"
12 | rand = "0.8.5"
13 |
14 | [dependencies.vis-core]
15 | optional = false
16 | path = "../vis-core"
17 |
--------------------------------------------------------------------------------
/noa-35c3/src/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noa-35c3/src/logo.png
--------------------------------------------------------------------------------
/noa-35c3/src/main.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate log;
3 | #[macro_use]
4 | extern crate glium;
5 | extern crate nalgebra as na;
6 |
7 | use glium::glutin;
8 | use vis_core::analyzer;
9 |
10 | use glutin::platform::run_return::EventLoopExtRunReturn;
11 |
12 | macro_rules! shader_program {
13 | // {{{
14 | ($display:expr, $vert_file:expr, $frag_file:expr) => {{
15 | // Use this for debug
16 | #[cfg(debug_assertions)]
17 | {
18 | let vert_src = {
19 | use std::io::Read;
20 | let mut buf = String::new();
21 | let mut f = std::fs::File::open(format!("src/{}", $vert_file)).unwrap();
22 | f.read_to_string(&mut buf).unwrap();
23 |
24 | buf
25 | };
26 |
27 | let frag_src = {
28 | use std::io::Read;
29 | let mut buf = String::new();
30 | let mut f = std::fs::File::open(format!("src/{}", $frag_file)).unwrap();
31 | f.read_to_string(&mut buf).unwrap();
32 |
33 | buf
34 | };
35 |
36 | glium::Program::from_source($display, &vert_src, &frag_src, None).unwrap()
37 | }
38 |
39 | // Use this for release
40 | #[cfg(not(debug_assertions))]
41 | glium::Program::from_source(
42 | $display,
43 | include_str!($vert_file),
44 | include_str!($frag_file),
45 | None,
46 | )
47 | .unwrap()
48 | }};
49 | } // }}}
50 |
51 | #[derive(Copy, Clone)]
52 | struct Vertex {
53 | position: [f32; 4],
54 | color_id: u16,
55 | }
56 |
57 | glium::implement_vertex!(Vertex, position, color_id);
58 |
59 | #[derive(Debug, Clone)]
60 | pub struct VisInfo {
61 | beat: u64,
62 | beat_volume: f32,
63 | volume: f32,
64 | analyzer: analyzer::FourierAnalyzer,
65 | spectrum: analyzer::Spectrum>,
66 | }
67 |
68 | fn main() {
69 | vis_core::default_config();
70 | vis_core::default_log();
71 |
72 | let mut frames = {
73 | // Analyzer {{{
74 | let mut beat = analyzer::BeatBuilder::new().build();
75 | let mut beat_num = 0;
76 |
77 | let analyzer = analyzer::FourierBuilder::new().plan();
78 |
79 | vis_core::Visualizer::new(
80 | VisInfo {
81 | beat: 0,
82 | beat_volume: 0.0,
83 | volume: 0.0,
84 | spectrum: analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1.0),
85 | analyzer,
86 | },
87 | move |info, samples| {
88 | if beat.detect(&samples) {
89 | beat_num += 1;
90 | }
91 | info.beat = beat_num;
92 | info.beat_volume = beat.last_volume();
93 | info.volume = samples.volume(0.3);
94 |
95 | info.analyzer.analyze(&samples);
96 | info.spectrum.fill_from(&info.analyzer.average());
97 |
98 | info
99 | },
100 | )
101 | .async_analyzer(300)
102 | .frames()
103 | // }}}
104 | };
105 |
106 | // Config {{{
107 | // Window
108 | let window_width = vis_core::CONFIG.get_or("window.width", 1280);
109 | let window_height = vis_core::CONFIG.get_or("window.height", 720);
110 | let aspect = window_width as f32 / window_height as f32;
111 |
112 | // Columns
113 | let rows = vis_core::CONFIG.get_or("noa.cols.rows", 50);
114 | let cols = vis_core::CONFIG.get_or("noa.cols.num", 30);
115 | let nrow = cols * 4;
116 | let cols_per_note = vis_core::CONFIG.get_or("noa.cols.note_width", 6);
117 | let notes_num = cols * 2 / cols_per_note;
118 | let width = vis_core::CONFIG.get_or("noa.cols.width", 10.0);
119 | let depth = vis_core::CONFIG.get_or("noa.cols.depth", 30.0);
120 | let rowsize = depth / rows as f32;
121 | let mid_dist = vis_core::CONFIG.get_or("noa.cols.mid_dist", 0.1);
122 | let base_height = vis_core::CONFIG.get_or("noa.cols.base_height", 0.2);
123 | let base_speed = vis_core::CONFIG.get_or("noa.cols.speed", 0.1);
124 | let slowdown = vis_core::CONFIG.get_or("noa.cols.slowdown", 0.995);
125 | let speed_deviation = vis_core::CONFIG.get_or("noa.cols.speed_deviation", 50.0);
126 | let ampli_top = vis_core::CONFIG.get_or("noa.cols.amp_top", 0.7);
127 | let ampli_bottom = vis_core::CONFIG.get_or("noa.cols.amp_bottom", 0.2);
128 |
129 | let frame_time =
130 | std::time::Duration::from_micros(1000000 / vis_core::CONFIG.get_or("noa.fps", 30));
131 |
132 | // Colors
133 | let colors: Vec<[f32; 4]> = vis_core::CONFIG.get_or(
134 | "noa.cols.colors",
135 | vec![
136 | [0.000000, 0.267958, 0.476371, 1.0],
137 | [0.000000, 0.408597, 0.113741, 1.0],
138 | [0.000000, 0.267958, 0.476371, 1.0],
139 | [0.000000, 0.408597, 0.113741, 1.0],
140 | [0.000000, 0.267958, 0.476371, 1.0],
141 | [0.000000, 0.408597, 0.113741, 1.0],
142 | [0.000000, 0.267958, 0.476371, 1.0],
143 | [0.000000, 0.408597, 0.113741, 1.0],
144 | [0.000000, 0.267958, 0.476371, 1.0],
145 | [0.000000, 0.408597, 0.113741, 1.0],
146 | ],
147 | );
148 | let note_roll_size = vis_core::CONFIG.get_or("noa.cols.note_roll", 20) as f32;
149 |
150 | // Camera
151 | let cam_height = vis_core::CONFIG.get_or("noa.camera.height", 1.0);
152 | let cam_look = vis_core::CONFIG.get_or("noa.camera.look_height", 0.8);
153 |
154 | // }}}
155 |
156 | // Window Initialization {{{
157 | let mut events_loop = glutin::event_loop::EventLoop::new();
158 | let window = glutin::window::WindowBuilder::new()
159 | .with_inner_size(glutin::dpi::LogicalSize::new(
160 | window_width as f64,
161 | window_height as f64,
162 | ))
163 | .with_maximized(true)
164 | .with_decorations(false)
165 | .with_fullscreen(Some(glutin::window::Fullscreen::Borderless(Some(
166 | events_loop
167 | .primary_monitor()
168 | .unwrap_or_else(|| events_loop.available_monitors().next().unwrap()),
169 | ))))
170 | .with_title("Visualizer2 - NoAmbition");
171 |
172 | let context = glutin::ContextBuilder::new()
173 | .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (4, 1)))
174 | .with_gl_profile(glutin::GlProfile::Core)
175 | .with_multisampling(0);
176 |
177 | let display = glium::Display::new(window, context, &events_loop).unwrap();
178 | // }}}
179 |
180 | // Framebuffer Initialization {{{
181 | let tex1 = glium::texture::Texture2d::empty_with_format(
182 | &display,
183 | glium::texture::UncompressedFloatFormat::F32F32F32F32,
184 | glium::texture::MipmapsOption::NoMipmap,
185 | window_width,
186 | window_height,
187 | )
188 | .unwrap();
189 | let depth1 = glium::texture::DepthTexture2d::empty_with_format(
190 | &display,
191 | glium::texture::DepthFormat::F32,
192 | glium::texture::MipmapsOption::NoMipmap,
193 | window_width,
194 | window_height,
195 | )
196 | .unwrap();
197 | let mut framebuffer1 =
198 | glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(&display, &tex1, &depth1).unwrap();
199 |
200 | let tex2 = glium::texture::Texture2d::empty_with_format(
201 | &display,
202 | glium::texture::UncompressedFloatFormat::F32F32F32F32,
203 | glium::texture::MipmapsOption::NoMipmap,
204 | window_width,
205 | window_height,
206 | )
207 | .unwrap();
208 | let depth2 = glium::texture::DepthTexture2d::empty_with_format(
209 | &display,
210 | glium::texture::DepthFormat::F32,
211 | glium::texture::MipmapsOption::NoMipmap,
212 | window_width,
213 | window_height,
214 | )
215 | .unwrap();
216 | let mut framebuffer2 =
217 | glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(&display, &tex2, &depth2).unwrap();
218 | // }}}
219 |
220 | // Shader Initialization {{{
221 | let prepass_program = shader_program!(&display, "shaders/prepass.vert", "shaders/prepass.frag");
222 | let background_program =
223 | shader_program!(&display, "shaders/pp.vert", "shaders/background.frag");
224 | // let fxaa_program = shader_program!(&display, "shaders/pp.vert", "shaders/fxaa.frag");
225 | // let bokeh_program = shader_program!(&display, "shaders/pp.vert", "shaders/bokeh.frag");
226 | let color_program = shader_program!(&display, "shaders/pp.vert", "shaders/color.frag");
227 | // }}}
228 |
229 | // Buffers {{{
230 |
231 | // Quad {{{
232 | let quad_verts = {
233 | #[derive(Copy, Clone)]
234 | struct Vertex {
235 | position: [f32; 4],
236 | texcoord: [f32; 2],
237 | }
238 |
239 | glium::implement_vertex!(Vertex, position, texcoord);
240 |
241 | glium::VertexBuffer::new(
242 | &display,
243 | &[
244 | Vertex {
245 | position: [-1.0, -1.0, 0.0, 1.0],
246 | texcoord: [0.0, 0.0],
247 | },
248 | Vertex {
249 | position: [1.0, -1.0, 0.0, 1.0],
250 | texcoord: [1.0, 0.0],
251 | },
252 | Vertex {
253 | position: [1.0, 1.0, 0.0, 1.0],
254 | texcoord: [1.0, 1.0],
255 | },
256 | Vertex {
257 | position: [-1.0, 1.0, 0.0, 1.0],
258 | texcoord: [0.0, 1.0],
259 | },
260 | ],
261 | )
262 | .unwrap()
263 | };
264 | let quad_inds = glium::IndexBuffer::new(
265 | &display,
266 | glium::index::PrimitiveType::TrianglesList,
267 | &[0u16, 1, 2, 0, 2, 3],
268 | )
269 | .unwrap();
270 | // }}}
271 |
272 | // Lines {{{
273 | let (mut lines_verts, mut lines_colors) = {
274 | let colsmax = (cols - 1) as f32 / width * 2.0;
275 | let rowsmax = (rows - 1) as f32 / depth;
276 | let h = base_height / 2.0;
277 | let mut v_buf = Vec::with_capacity(rows * cols * 4);
278 |
279 | for row in 0..rows {
280 | let y = row as f32 / rowsmax;
281 | // Left
282 | for col in 0..cols {
283 | let x = -(col as f32 / colsmax) - mid_dist;
284 | let cid = (cols - col - 1) / cols_per_note;
285 | v_buf.push(Vertex {
286 | position: [x, y, -h, 1.0],
287 | color_id: cid as u16,
288 | });
289 | v_buf.push(Vertex {
290 | position: [x, y, h, 1.0],
291 | color_id: cid as u16,
292 | });
293 | }
294 |
295 | // Right
296 | for col in 0..cols {
297 | let x = (col as f32 / colsmax) + mid_dist;
298 | let cid = col / cols_per_note + notes_num / 2;
299 | v_buf.push(Vertex {
300 | position: [x, y, -h, 1.0],
301 | color_id: cid as u16,
302 | });
303 | v_buf.push(Vertex {
304 | position: [x, y, h, 1.0],
305 | color_id: cid as u16,
306 | });
307 | }
308 | }
309 |
310 | let mut colors_buf = [[1.0, 0.0, 0.0, 1.0]; 32];
311 | for (buf, color) in colors_buf.iter_mut().zip(colors.iter()) {
312 | *buf = *color;
313 | }
314 | let lines_colors =
315 | glium::uniforms::UniformBuffer::persistent(&display, colors_buf).unwrap();
316 |
317 | (
318 | glium::VertexBuffer::persistent(&display, &v_buf).unwrap(),
319 | lines_colors,
320 | )
321 | };
322 | // }}}
323 |
324 | // Points {{{
325 | let points_colors = {
326 | let mut colors_buf = [[1.0, 0.0, 0.0, 1.0]; 32];
327 | for (buf, color) in colors_buf.iter_mut().zip(colors.iter()) {
328 | *buf = *color;
329 | }
330 | glium::uniforms::UniformBuffer::persistent(&display, colors_buf).unwrap()
331 | };
332 | // }}}
333 |
334 | // Lightning {{{
335 | // }}}
336 |
337 | // }}}
338 |
339 | // Image {{{
340 | let image = image::load(
341 | std::io::Cursor::new(&include_bytes!("logo.png")[..]),
342 | image::ImageFormat::Png,
343 | )
344 | .unwrap()
345 | .to_rgba8();
346 | let image_dims = image.dimensions();
347 | let image = glium::texture::RawImage2d::from_raw_rgba_reversed(&image.into_raw(), image_dims);
348 | let c3_texture = glium::texture::CompressedSrgbTexture2d::new(&display, image).unwrap();
349 | // }}}
350 |
351 | let mut previous_time = 0.0;
352 | let mut previous_offset = 0.0;
353 | let mut rolling_volume = 0.0;
354 | let mut write_row = rows * 3 / 4;
355 | let mut last_beat = -100.0;
356 |
357 | let mut notes_spectrum = analyzer::Spectrum::new(vec![0.0; notes_num], 220.0, 660.0);
358 | let mut notes_rolling_buf = vec![0.0; notes_num];
359 | let mut row_buf = Vec::with_capacity(nrow);
360 | let mut row_spectrum = vec![0.0; cols];
361 |
362 | let mut beat_rolling = 0.0;
363 | let mut last_beat_num = 0;
364 |
365 | let mut maxima_buf = [(0.0, 0.0); 8];
366 |
367 | 'main: for frame in frames.iter() {
368 | use glium::Surface;
369 |
370 | let start = std::time::Instant::now();
371 | let delta = frame.time - previous_time;
372 | trace!("Delta: {}s", delta);
373 |
374 | // Audio Info Retrieval {{{
375 | let (volume, maxima, notes_rolling_spectrum, base_volume) = frame.info(|info| {
376 | rolling_volume = info.volume.max(rolling_volume * slowdown);
377 |
378 | if info.beat != last_beat_num {
379 | last_beat = frame.time;
380 | last_beat_num = info.beat;
381 | }
382 |
383 | let notes_spectrum = info.spectrum.fill_spectrum(&mut notes_spectrum);
384 |
385 | for (n, s) in notes_rolling_buf.iter_mut().zip(notes_spectrum.iter()) {
386 | *n = (*n * (note_roll_size - 1.0) + s) / note_roll_size;
387 | }
388 | let notes_rolling_spectrum = vis_core::analyzer::Spectrum::new(
389 | &mut *notes_rolling_buf,
390 | notes_spectrum.lowest(),
391 | notes_spectrum.highest(),
392 | );
393 |
394 | let maxima = notes_rolling_spectrum.find_maxima(&mut maxima_buf);
395 |
396 | (
397 | info.volume,
398 | maxima,
399 | notes_rolling_spectrum,
400 | info.beat_volume,
401 | )
402 | });
403 | // }}}
404 |
405 | // GL Matrices {{{
406 | let view = na::Matrix4::look_at_rh(
407 | &na::Point3::new(0.0, -1.0, cam_height),
408 | &na::Point3::new(0.0, 10.0, cam_look),
409 | &na::Vector3::new(0.0, 0.0, 1.0),
410 | );
411 |
412 | let perspective =
413 | na::Matrix4::new_perspective(aspect, std::f32::consts::FRAC_PI_4, 0.001, 100.0);
414 | // }}}
415 |
416 | // Grid {{{
417 | let speed = base_speed + rolling_volume * speed_deviation;
418 | let offset = (previous_offset + delta * speed) % rowsize;
419 | let model_grid =
420 | na::Translation3::from(na::Vector3::new(0.0, -offset, 0.0)).to_homogeneous();
421 |
422 | // Color Notes {{{
423 | {
424 | let mut color_buf = lines_colors.map();
425 | for color in color_buf.iter_mut() {
426 | color[3] = 0.05;
427 | }
428 | for (f, _) in maxima.iter().take(4) {
429 | let note = notes_rolling_spectrum.freq_to_id(*f);
430 | color_buf[note][3] = 1.0;
431 | }
432 | }
433 | // }}}
434 |
435 | // Spectral Grid {{{
436 | if previous_offset > offset {
437 | let mut lines_buf = lines_verts.map();
438 | // We jumped right here
439 | // Save last rows y coordinate
440 | row_buf.clear();
441 | let last_row_offset = lines_buf.len() - nrow;
442 | for i in 0..nrow {
443 | row_buf.push(lines_buf[last_row_offset + i].position[1]);
444 | }
445 | // Copy y coordinate of each line to the next
446 | for i in (nrow..(lines_buf.len())).rev() {
447 | lines_buf[i].position[1] = lines_buf[i - nrow].position[1];
448 | }
449 | // Write saved info to first row (cycle rows)
450 | for i in 0..nrow {
451 | lines_buf[i].position[1] = row_buf[i];
452 | }
453 |
454 | // Write spectral information
455 | frame.info(|info| {
456 | let left = info
457 | .analyzer
458 | .left()
459 | .slice(100.0, 800.0)
460 | .fill_buckets(&mut row_spectrum[..]);
461 | let row_offset = nrow * write_row;
462 | let max = left.max() + 0.0001;
463 | for (i, v) in left.iter().enumerate() {
464 | lines_buf[row_offset + i * 2 + 1].position[2] =
465 | base_height / 2.0 + v / max * ampli_top;
466 | lines_buf[row_offset + i * 2].position[2] =
467 | -base_height / 2.0 - v / max * ampli_bottom;
468 | }
469 |
470 | let right = info
471 | .analyzer
472 | .right()
473 | .slice(100.0, 800.0)
474 | .fill_buckets(&mut row_spectrum[..]);
475 | let row_offset = nrow * write_row + cols * 2;
476 | let max = right.max() + 0.0001;
477 | for (i, v) in right.iter().enumerate() {
478 | lines_buf[row_offset + i * 2 + 1].position[2] =
479 | base_height / 2.0 + v / max * ampli_top;
480 | lines_buf[row_offset + i * 2].position[2] =
481 | -base_height / 2.0 - v / max * ampli_bottom;
482 | }
483 | });
484 |
485 | write_row = (write_row + 1) % rows;
486 | }
487 | // }}}
488 | // }}}
489 |
490 | // Drawing {{{
491 | let draw_params = glium::DrawParameters {
492 | line_width: Some(1.0),
493 | point_size: Some(2.0),
494 | blend: glium::Blend {
495 | color: glium::BlendingFunction::Addition {
496 | source: glium::LinearBlendingFactor::SourceAlpha,
497 | destination: glium::LinearBlendingFactor::OneMinusSourceAlpha,
498 | },
499 | alpha: glium::BlendingFunction::Addition {
500 | source: glium::LinearBlendingFactor::One,
501 | destination: glium::LinearBlendingFactor::One,
502 | },
503 | constant_value: (1.0, 1.0, 1.0, 1.0),
504 | },
505 | ..Default::default()
506 | };
507 |
508 | framebuffer1.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);
509 | framebuffer2.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);
510 |
511 | let (ref mut fa, ref mut fb) = (&mut framebuffer1, &mut framebuffer2);
512 |
513 | // Lines {{{
514 | let uniforms = uniform! {
515 | perspective_matrix: Into::<[[f32; 4]; 4]>::into(perspective),
516 | view_matrix: Into::<[[f32; 4]; 4]>::into(view),
517 | model_matrix: Into::<[[f32; 4]; 4]>::into(model_grid),
518 | Colors: &lines_colors,
519 | volume: rolling_volume,
520 | };
521 | fa.draw(
522 | &lines_verts,
523 | &glium::index::NoIndices(glium::index::PrimitiveType::LinesList),
524 | &prepass_program,
525 | &uniforms,
526 | &draw_params,
527 | )
528 | .unwrap();
529 | // }}}
530 |
531 | // Points {{{
532 | let uniforms = uniform! {
533 | perspective_matrix: Into::<[[f32; 4]; 4]>::into(perspective),
534 | view_matrix: Into::<[[f32; 4]; 4]>::into(view),
535 | model_matrix: Into::<[[f32; 4]; 4]>::into(model_grid),
536 | Colors: &points_colors,
537 | volume: rolling_volume,
538 | };
539 | fa.draw(
540 | &lines_verts,
541 | &glium::index::NoIndices(glium::index::PrimitiveType::Points),
542 | &prepass_program,
543 | &uniforms,
544 | &draw_params,
545 | )
546 | .unwrap();
547 | // }}}
548 |
549 | // Post-Processing {{{
550 | beat_rolling = (beat_rolling * 0.95f32).max(base_volume);
551 |
552 | let (fa, fb) = (fb, fa);
553 | let ua = uniform! {
554 | previous: tex1.sampled().wrap_function(glium::uniforms::SamplerWrapFunction::Mirror),
555 | c3: c3_texture.sampled(),
556 | aspect: aspect,
557 | time: frame.time,
558 | volume: volume,
559 | last_beat: frame.time - last_beat,
560 | beat: beat_rolling,
561 | };
562 | let ub = uniform! {
563 | previous: tex2.sampled().wrap_function(glium::uniforms::SamplerWrapFunction::Mirror),
564 | c3: c3_texture.sampled(),
565 | aspect: aspect,
566 | time: frame.time,
567 | volume: volume,
568 | last_beat: frame.time - last_beat,
569 | beat: beat_rolling,
570 | };
571 |
572 | fa.draw(
573 | &quad_verts,
574 | &quad_inds,
575 | &background_program,
576 | &ua,
577 | &draw_params,
578 | )
579 | .unwrap();
580 | let (fa, ua, fb, ub) = (fb, ub, fa, ua);
581 | fa.draw(&quad_verts, &quad_inds, &color_program, &ua, &draw_params)
582 | .unwrap();
583 | #[allow(unused_variables)]
584 | let (fa, ua, fb, ub) = (fb, ub, fa, ua);
585 | // }}}
586 |
587 | // Finalizing / Draw to screen {{{
588 | let target = display.draw();
589 | let dims = target.get_dimensions();
590 | target.blit_from_simple_framebuffer(
591 | &fb,
592 | &glium::Rect {
593 | left: 0,
594 | bottom: 0,
595 | width: window_width,
596 | height: window_height,
597 | },
598 | &glium::BlitTarget {
599 | left: 0,
600 | bottom: 0,
601 | width: dims.0 as i32,
602 | height: dims.1 as i32,
603 | },
604 | glium::uniforms::MagnifySamplerFilter::Linear,
605 | );
606 | target.finish().unwrap();
607 | // }}}
608 | // }}}
609 |
610 | // Events {{{
611 | let mut closed = false;
612 | events_loop.run_return(|ev, _, control_flow| {
613 | match ev {
614 | glutin::event::Event::WindowEvent { event, .. } => match event {
615 | glutin::event::WindowEvent::CloseRequested => closed = true,
616 | glutin::event::WindowEvent::KeyboardInput {
617 | input:
618 | glutin::event::KeyboardInput {
619 | virtual_keycode: Some(glutin::event::VirtualKeyCode::Escape),
620 | ..
621 | },
622 | ..
623 | } => closed = true,
624 | _ => (),
625 | },
626 | _ => (),
627 | }
628 | *control_flow = glutin::event_loop::ControlFlow::Exit;
629 | });
630 | if closed {
631 | break 'main;
632 | }
633 | // }}}
634 |
635 | previous_time = frame.time;
636 | previous_offset = offset;
637 |
638 | let end = std::time::Instant::now();
639 | let dur = end - start;
640 | if dur < frame_time {
641 | let sleep = frame_time - dur;
642 | std::thread::sleep(sleep);
643 | }
644 | }
645 | }
646 |
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/background.frag:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | uniform sampler2D previous;
4 | uniform sampler2D c3;
5 | uniform float last_beat;
6 | uniform float beat;
7 | uniform float volume;
8 | uniform float aspect;
9 |
10 | smooth in vec2 frag_position;
11 | smooth in vec2 frag_texcoord;
12 |
13 | vec3 background() {
14 | vec2 p = frag_position;
15 |
16 | float t = last_beat + 1.0;
17 |
18 | p.x = p.x * aspect + 0.5;
19 |
20 | p -= vec2(0.5);
21 | p = p * t;
22 | p += vec2(0.5);
23 |
24 | if(p.x > 1.0 || p.x < 0.0 || p.y > 1.0 || p.y < 0.0){
25 | return vec3(0.0);
26 | }
27 |
28 | return texture(c3, p).rgb;
29 | }
30 |
31 | void main() {
32 | vec4 prev_color = texture(previous, frag_texcoord);
33 | vec3 bg_color = background();
34 | gl_FragColor = vec4(prev_color.rgb + (1.0 - prev_color.a) * bg_color, 1.0);
35 | }
36 |
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/bokeh.frag:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noa-35c3/src/shaders/bokeh.frag
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/color.frag:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | uniform sampler2D previous;
4 | uniform sampler2D c3;
5 | uniform float last_beat;
6 | uniform float beat;
7 | uniform float volume;
8 | uniform float aspect;
9 |
10 | smooth in vec2 frag_position;
11 | smooth in vec2 frag_texcoord;
12 |
13 | // RGB/HSV Conversion
14 | // Taken from http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
15 |
16 | vec3 rgb2hsv(vec3 c)
17 | {
18 | vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
19 | vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
20 | vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
21 |
22 | float d = q.x - min(q.w, q.y);
23 | float e = 1.0e-10;
24 | return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
25 | }
26 |
27 | vec3 hsv2rgb(vec3 c)
28 | {
29 | vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
30 | vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
31 | return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
32 | }
33 |
34 |
35 | void main() {
36 | vec4 prev_color = texture(previous, frag_texcoord);
37 |
38 | // if (frag_texcoord.x < 0.5) {
39 | // gl_FragColor = prev_color;
40 | // return;
41 | // }
42 |
43 | gl_FragColor = mat4(
44 | 1.0, 0.0, 0.0, 0.0,
45 | 0.0, 1.0, -0.1, 0.0,
46 | 0.0, -0.3, 1.0, 0.0,
47 | 0.0, 0.0, 0.0, 1.0
48 | ) * prev_color;
49 | }
50 |
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/fxaa.frag:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noa-35c3/src/shaders/fxaa.frag
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/pp.vert:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | in vec4 position;
4 | in vec2 texcoord;
5 |
6 | smooth out vec2 frag_position;
7 | smooth out vec2 frag_texcoord;
8 |
9 | void main() {
10 | frag_texcoord = texcoord;
11 | frag_position = position.xy;
12 | gl_Position = position;
13 | }
14 |
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/prepass.frag:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | smooth in vec4 frag_position;
4 | smooth in vec4 frag_color;
5 |
6 | void main() {
7 | gl_FragColor = frag_color;
8 | }
9 |
--------------------------------------------------------------------------------
/noa-35c3/src/shaders/prepass.vert:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | uniform mat4 perspective_matrix;
4 | uniform mat4 view_matrix;
5 | uniform mat4 model_matrix;
6 | layout(std140) uniform Colors {
7 | vec4 colors[32];
8 | };
9 | uniform float volume;
10 |
11 | in vec4 position;
12 | in uint color_id;
13 |
14 | smooth out vec4 frag_position;
15 | smooth out vec4 frag_color;
16 |
17 | void main() {
18 | frag_position = model_matrix * position;
19 | frag_position.z += exp(-pow(frag_position.y / 5.0 - 4.0, 2.0)) * (pow(frag_position.x / 8.0, 2.0) * 2.0 + 0.1) * (volume * 30.0 + 0.1);
20 | frag_color = colors[color_id];
21 | frag_color.a = frag_color.a * (1.0 - smoothstep(15.0, 25.0, frag_position.y));
22 | gl_Position = perspective_matrix * view_matrix * frag_position;
23 | }
24 |
--------------------------------------------------------------------------------
/noa-35c3/visualizer.toml:
--------------------------------------------------------------------------------
1 | [audio]
2 | window = "nuttall"
3 | conversions = 300
4 | rate = 8000
5 | read_size = 256
6 | recorder = "cpal"
7 |
8 | [noa]
9 | fps = 40
10 |
11 | [noa.cols]
12 | rows = 50
13 | num = 30
14 | depth = 30.0
15 | mid_dist = 0.1
16 | speed = 0.1
17 | slowdown = 0.995
18 | speed_deviation = 50.0
19 | width = 10.0
20 | note_width = 6
21 | colors = [
22 | [0.000000, 0.267958, 0.476371, 1.0],
23 | [0.000000, 0.408597, 0.113741, 1.0],
24 | [0.000000, 0.267958, 0.476371, 1.0],
25 | [0.000000, 0.408597, 0.113741, 1.0],
26 | [0.000000, 0.267958, 0.476371, 1.0],
27 | [0.000000, 0.408597, 0.113741, 1.0],
28 | [0.000000, 0.267958, 0.476371, 1.0],
29 | [0.000000, 0.408597, 0.113741, 1.0],
30 | [0.000000, 0.267958, 0.476371, 1.0],
31 | [0.000000, 0.408597, 0.113741, 1.0],
32 | ]
33 |
34 | amp_top = 0.7
35 | amp_bottom = 0.2
36 |
37 | [noa.camera]
38 | height = 1.0
39 | look_height = 0.8
40 |
--------------------------------------------------------------------------------
/noambition/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Rahix "]
3 | edition = "2018"
4 | name = "noambition"
5 | version = "0.1.0"
6 |
7 | [dependencies]
8 | glium = "0.32.1"
9 | image = "0.24.5"
10 | log = "0.4.17"
11 | nalgebra = "0.32.1"
12 | rand = "0.8.5"
13 |
14 | [dependencies.vis-core]
15 | optional = false
16 | path = "../vis-core"
17 |
--------------------------------------------------------------------------------
/noambition/src/main.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate log;
3 | #[macro_use]
4 | extern crate glium;
5 | extern crate nalgebra as na;
6 |
7 | use glium::glutin;
8 | use vis_core::analyzer;
9 |
10 | use glutin::platform::run_return::EventLoopExtRunReturn;
11 |
12 | macro_rules! shader_program {
13 | // {{{
14 | ($display:expr, $vert_file:expr, $frag_file:expr) => {{
15 | // Use this for debug
16 | #[cfg(debug_assertions)]
17 | {
18 | let vert_src = {
19 | use std::io::Read;
20 | let mut buf = String::new();
21 | let mut f = std::fs::File::open(format!("src/{}", $vert_file)).unwrap();
22 | f.read_to_string(&mut buf).unwrap();
23 |
24 | buf
25 | };
26 |
27 | let frag_src = {
28 | use std::io::Read;
29 | let mut buf = String::new();
30 | let mut f = std::fs::File::open(format!("src/{}", $frag_file)).unwrap();
31 | f.read_to_string(&mut buf).unwrap();
32 |
33 | buf
34 | };
35 |
36 | glium::Program::from_source($display, &vert_src, &frag_src, None).unwrap()
37 | }
38 |
39 | // Use this for release
40 | #[cfg(not(debug_assertions))]
41 | glium::Program::from_source(
42 | $display,
43 | include_str!($vert_file),
44 | include_str!($frag_file),
45 | None,
46 | )
47 | .unwrap()
48 | }};
49 | } // }}}
50 |
51 | #[derive(Copy, Clone)]
52 | struct Vertex {
53 | position: [f32; 4],
54 | color_id: u16,
55 | }
56 |
57 | #[allow(deprecated)]
58 | pub mod _vertex_impl {
59 | use super::Vertex;
60 |
61 | glium::implement_vertex!(Vertex, position, color_id);
62 | }
63 |
64 | #[derive(Debug, Clone)]
65 | pub struct VisInfo {
66 | beat: u64,
67 | beat_volume: f32,
68 | volume: f32,
69 | analyzer: analyzer::FourierAnalyzer,
70 | spectrum: analyzer::Spectrum>,
71 | }
72 |
73 | fn main() {
74 | vis_core::default_config();
75 | vis_core::default_log();
76 |
77 | let mut frames = {
78 | // Analyzer {{{
79 | let mut beat = analyzer::BeatBuilder::new().build();
80 | let mut beat_num = 0;
81 |
82 | let analyzer = analyzer::FourierBuilder::new().plan();
83 |
84 | vis_core::Visualizer::new(
85 | VisInfo {
86 | beat: 0,
87 | beat_volume: 0.0,
88 | volume: 0.0,
89 | spectrum: analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1.0),
90 | analyzer,
91 | },
92 | move |info, samples| {
93 | if beat.detect(&samples) {
94 | beat_num += 1;
95 | }
96 | info.beat = beat_num;
97 | info.beat_volume = beat.last_volume();
98 | info.volume = samples.volume(0.3);
99 |
100 | info.analyzer.analyze(&samples);
101 | info.spectrum.fill_from(&info.analyzer.average());
102 |
103 | info
104 | },
105 | )
106 | .async_analyzer(300)
107 | .frames()
108 | // }}}
109 | };
110 |
111 | // Config {{{
112 | // Window
113 | let window_width = vis_core::CONFIG.get_or("window.width", 1280);
114 | let window_height = vis_core::CONFIG.get_or("window.height", 720);
115 | let aspect = window_width as f32 / window_height as f32;
116 |
117 | // Columns
118 | let rows = vis_core::CONFIG.get_or("noa.cols.rows", 50);
119 | let cols = vis_core::CONFIG.get_or("noa.cols.num", 30);
120 | let nrow = cols * 4;
121 | let cols_per_note = vis_core::CONFIG.get_or("noa.cols.note_width", 6);
122 | let notes_num = cols * 2 / cols_per_note;
123 | let width = vis_core::CONFIG.get_or("noa.cols.width", 10.0);
124 | let depth = vis_core::CONFIG.get_or("noa.cols.depth", 30.0);
125 | let rowsize = depth / rows as f32;
126 | let mid_dist = vis_core::CONFIG.get_or("noa.cols.mid_dist", 0.1);
127 | let base_height = vis_core::CONFIG.get_or("noa.cols.base_height", 0.2);
128 | let base_speed = vis_core::CONFIG.get_or("noa.cols.speed", 0.1);
129 | let slowdown = vis_core::CONFIG.get_or("noa.cols.slowdown", 0.995);
130 | let speed_deviation = vis_core::CONFIG.get_or("noa.cols.speed_deviation", 50.0);
131 | let ampli_top = vis_core::CONFIG.get_or("noa.cols.amp_top", 0.7);
132 | let ampli_bottom = vis_core::CONFIG.get_or("noa.cols.amp_bottom", 0.2);
133 |
134 | let frame_time =
135 | std::time::Duration::from_micros(1000000 / vis_core::CONFIG.get_or("noa.fps", 30));
136 |
137 | // Colors
138 | let colors: Vec<[f32; 4]> = vis_core::CONFIG.get_or(
139 | "noa.cols.colors",
140 | vec![
141 | [1.0, 0.007443, 0.318893, 1.0],
142 | [0.915586, 0.704283, 0.214133, 1.0],
143 | [0.044844, 0.64629, 0.590788, 1.0],
144 | [0.130165, 0.022207, 0.27614, 1.0],
145 | [1.0, 0.007443, 0.318893, 1.0],
146 | [0.915586, 0.704283, 0.214133, 1.0],
147 | [0.044844, 0.64629, 0.590788, 1.0],
148 | [0.130165, 0.022207, 0.27614, 1.0],
149 | [1.0, 0.007443, 0.318893, 1.0],
150 | [0.915586, 0.704283, 0.214133, 1.0],
151 | [0.044844, 0.64629, 0.590788, 1.0],
152 | [0.130165, 0.022207, 0.27614, 1.0],
153 | ],
154 | );
155 | let note_roll_size = vis_core::CONFIG.get_or("noa.cols.note_roll", 20) as f32;
156 |
157 | // Camera
158 | let cam_height = vis_core::CONFIG.get_or("noa.camera.height", 1.0);
159 | let cam_look = vis_core::CONFIG.get_or("noa.camera.look_height", 0.8);
160 |
161 | // }}}
162 |
163 | // Window Initialization {{{
164 | let mut events_loop = glutin::event_loop::EventLoop::new();
165 | let window = glutin::window::WindowBuilder::new()
166 | .with_inner_size(glutin::dpi::LogicalSize::new(
167 | window_width as f64,
168 | window_height as f64,
169 | ))
170 | .with_maximized(true)
171 | .with_decorations(false)
172 | .with_fullscreen(Some(glutin::window::Fullscreen::Borderless(Some(
173 | events_loop
174 | .primary_monitor()
175 | .unwrap_or_else(|| events_loop.available_monitors().next().unwrap()),
176 | ))))
177 | .with_title("Visualizer2 - NoAmbition");
178 |
179 | let context = glutin::ContextBuilder::new()
180 | .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (4, 1)))
181 | .with_gl_profile(glutin::GlProfile::Core)
182 | .with_multisampling(0);
183 |
184 | let display = glium::Display::new(window, context, &events_loop).unwrap();
185 | // }}}
186 |
187 | // Framebuffer Initialization {{{
188 | let tex1 = glium::texture::Texture2d::empty_with_format(
189 | &display,
190 | glium::texture::UncompressedFloatFormat::F32F32F32F32,
191 | glium::texture::MipmapsOption::NoMipmap,
192 | window_width,
193 | window_height,
194 | )
195 | .unwrap();
196 | let depth1 = glium::texture::DepthTexture2d::empty_with_format(
197 | &display,
198 | glium::texture::DepthFormat::F32,
199 | glium::texture::MipmapsOption::NoMipmap,
200 | window_width,
201 | window_height,
202 | )
203 | .unwrap();
204 | let mut framebuffer1 =
205 | glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(&display, &tex1, &depth1).unwrap();
206 |
207 | let tex2 = glium::texture::Texture2d::empty_with_format(
208 | &display,
209 | glium::texture::UncompressedFloatFormat::F32F32F32F32,
210 | glium::texture::MipmapsOption::NoMipmap,
211 | window_width,
212 | window_height,
213 | )
214 | .unwrap();
215 | let depth2 = glium::texture::DepthTexture2d::empty_with_format(
216 | &display,
217 | glium::texture::DepthFormat::F32,
218 | glium::texture::MipmapsOption::NoMipmap,
219 | window_width,
220 | window_height,
221 | )
222 | .unwrap();
223 | let mut framebuffer2 =
224 | glium::framebuffer::SimpleFrameBuffer::with_depth_buffer(&display, &tex2, &depth2).unwrap();
225 | // }}}
226 |
227 | // Shader Initialization {{{
228 | let prepass_program = shader_program!(&display, "shaders/prepass.vert", "shaders/prepass.frag");
229 | let background_program =
230 | shader_program!(&display, "shaders/pp.vert", "shaders/background.frag");
231 | // let fxaa_program = shader_program!(&display, "shaders/pp.vert", "shaders/fxaa.frag");
232 | // let bokeh_program = shader_program!(&display, "shaders/pp.vert", "shaders/bokeh.frag");
233 | // let color_program = shader_program!(&display, "shaders/pp.vert", "shaders/color.frag");
234 | // }}}
235 |
236 | // Buffers {{{
237 |
238 | // Quad {{{
239 | #[allow(deprecated)]
240 | let quad_verts = {
241 | #[derive(Copy, Clone)]
242 | struct Vertex {
243 | position: [f32; 4],
244 | texcoord: [f32; 2],
245 | }
246 |
247 | glium::implement_vertex!(Vertex, position, texcoord);
248 |
249 | glium::VertexBuffer::new(
250 | &display,
251 | &[
252 | Vertex {
253 | position: [-1.0, -1.0, 0.0, 1.0],
254 | texcoord: [0.0, 0.0],
255 | },
256 | Vertex {
257 | position: [1.0, -1.0, 0.0, 1.0],
258 | texcoord: [1.0, 0.0],
259 | },
260 | Vertex {
261 | position: [1.0, 1.0, 0.0, 1.0],
262 | texcoord: [1.0, 1.0],
263 | },
264 | Vertex {
265 | position: [-1.0, 1.0, 0.0, 1.0],
266 | texcoord: [0.0, 1.0],
267 | },
268 | ],
269 | )
270 | .unwrap()
271 | };
272 | let quad_inds = glium::IndexBuffer::new(
273 | &display,
274 | glium::index::PrimitiveType::TrianglesList,
275 | &[0u16, 1, 2, 0, 2, 3],
276 | )
277 | .unwrap();
278 | // }}}
279 |
280 | // Lines {{{
281 | let (mut lines_verts, mut lines_colors) = {
282 | let colsmax = (cols - 1) as f32 / width * 2.0;
283 | let rowsmax = (rows - 1) as f32 / depth;
284 | let h = base_height / 2.0;
285 | let mut v_buf = Vec::with_capacity(rows * cols * 4);
286 |
287 | for row in 0..rows {
288 | let y = row as f32 / rowsmax;
289 | // Left
290 | for col in 0..cols {
291 | let x = -(col as f32 / colsmax) - mid_dist;
292 | let cid = (cols - col - 1) / cols_per_note;
293 | v_buf.push(Vertex {
294 | position: [x, y, -h, 1.0],
295 | color_id: cid as u16,
296 | });
297 | v_buf.push(Vertex {
298 | position: [x, y, h, 1.0],
299 | color_id: cid as u16,
300 | });
301 | }
302 |
303 | // Right
304 | for col in 0..cols {
305 | let x = (col as f32 / colsmax) + mid_dist;
306 | let cid = col / cols_per_note + notes_num / 2;
307 | v_buf.push(Vertex {
308 | position: [x, y, -h, 1.0],
309 | color_id: cid as u16,
310 | });
311 | v_buf.push(Vertex {
312 | position: [x, y, h, 1.0],
313 | color_id: cid as u16,
314 | });
315 | }
316 | }
317 |
318 | let mut colors_buf = [[1.0, 0.0, 0.0, 1.0]; 32];
319 | for (buf, color) in colors_buf.iter_mut().zip(colors.iter()) {
320 | *buf = *color;
321 | }
322 | let lines_colors =
323 | glium::uniforms::UniformBuffer::persistent(&display, colors_buf).unwrap();
324 |
325 | (
326 | glium::VertexBuffer::persistent(&display, &v_buf).unwrap(),
327 | lines_colors,
328 | )
329 | };
330 | // }}}
331 |
332 | // Points {{{
333 | let points_colors = {
334 | let mut colors_buf = [[1.0, 0.0, 0.0, 1.0]; 32];
335 | for (buf, color) in colors_buf.iter_mut().zip(colors.iter()) {
336 | *buf = *color;
337 | }
338 | glium::uniforms::UniformBuffer::persistent(&display, colors_buf).unwrap()
339 | };
340 | // }}}
341 |
342 | // Lightning {{{
343 | // }}}
344 |
345 | // }}}
346 |
347 | let mut previous_time = 0.0;
348 | let mut previous_offset = 0.0;
349 | let mut rolling_volume = 0.0;
350 | let mut write_row = rows * 3 / 4;
351 | let mut last_beat = -100.0;
352 |
353 | let mut notes_spectrum = analyzer::Spectrum::new(vec![0.0; notes_num], 220.0, 660.0);
354 | let mut notes_rolling_buf = vec![0.0; notes_num];
355 | let mut row_buf = Vec::with_capacity(nrow);
356 | let mut row_spectrum = vec![0.0; cols];
357 |
358 | let mut beat_rolling = 0.0;
359 | let mut last_beat_num = 0;
360 |
361 | let mut maxima_buf = [(0.0, 0.0); 8];
362 |
363 | 'main: for frame in frames.iter() {
364 | use glium::Surface;
365 |
366 | let start = std::time::Instant::now();
367 | let delta = frame.time - previous_time;
368 | trace!("Delta: {}s", delta);
369 |
370 | // Audio Info Retrieval {{{
371 | let (volume, maxima, notes_rolling_spectrum, base_volume) = frame.info(|info| {
372 | rolling_volume = info.volume.max(rolling_volume * slowdown);
373 |
374 | if info.beat != last_beat_num {
375 | last_beat = frame.time;
376 | last_beat_num = info.beat;
377 | }
378 |
379 | let notes_spectrum = info.spectrum.fill_spectrum(&mut notes_spectrum);
380 |
381 | for (n, s) in notes_rolling_buf.iter_mut().zip(notes_spectrum.iter()) {
382 | *n = (*n * (note_roll_size - 1.0) + s) / note_roll_size;
383 | }
384 | let notes_rolling_spectrum = vis_core::analyzer::Spectrum::new(
385 | &mut *notes_rolling_buf,
386 | notes_spectrum.lowest(),
387 | notes_spectrum.highest(),
388 | );
389 |
390 | let maxima = notes_rolling_spectrum.find_maxima(&mut maxima_buf);
391 |
392 | (
393 | info.volume,
394 | maxima,
395 | notes_rolling_spectrum,
396 | info.beat_volume,
397 | )
398 | });
399 | // }}}
400 |
401 | // GL Matrices {{{
402 | let view = na::Matrix4::look_at_rh(
403 | &na::Point3::new(0.0, -1.0, cam_height),
404 | &na::Point3::new(0.0, 10.0, cam_look),
405 | &na::Vector3::new(0.0, 0.0, 1.0),
406 | );
407 |
408 | let perspective =
409 | na::Matrix4::new_perspective(aspect, std::f32::consts::FRAC_PI_4, 0.001, 100.0);
410 | // }}}
411 |
412 | // Grid {{{
413 | let speed = base_speed + rolling_volume * speed_deviation;
414 | let offset = (previous_offset + delta * speed) % rowsize;
415 | let model_grid =
416 | na::Translation3::from(na::Vector3::new(0.0, -offset, 0.0)).to_homogeneous();
417 |
418 | // Color Notes {{{
419 | {
420 | let mut color_buf = lines_colors.map();
421 | for color in color_buf.iter_mut() {
422 | color[3] = 0.05;
423 | }
424 | for (f, _) in maxima.iter().take(4) {
425 | let note = notes_rolling_spectrum.freq_to_id(*f);
426 | color_buf[note][3] = 1.0;
427 | }
428 | }
429 | // }}}
430 |
431 | // Spectral Grid {{{
432 | if previous_offset > offset {
433 | let mut lines_buf = lines_verts.map();
434 | // We jumped right here
435 | // Save last rows y coordinate
436 | row_buf.clear();
437 | let last_row_offset = lines_buf.len() - nrow;
438 | for i in 0..nrow {
439 | row_buf.push(lines_buf[last_row_offset + i].position[1]);
440 | }
441 | // Copy y coordinate of each line to the next
442 | for i in (nrow..(lines_buf.len())).rev() {
443 | lines_buf[i].position[1] = lines_buf[i - nrow].position[1];
444 | }
445 | // Write saved info to first row (cycle rows)
446 | for i in 0..nrow {
447 | lines_buf[i].position[1] = row_buf[i];
448 | }
449 |
450 | // Write spectral information
451 | frame.info(|info| {
452 | let left = info
453 | .analyzer
454 | .left()
455 | .slice(100.0, 800.0)
456 | .fill_buckets(&mut row_spectrum[..]);
457 | let row_offset = nrow * write_row;
458 | let max = left.max() + 0.0001;
459 | for (i, v) in left.iter().enumerate() {
460 | lines_buf[row_offset + i * 2 + 1].position[2] =
461 | base_height / 2.0 + v / max * ampli_top;
462 | lines_buf[row_offset + i * 2].position[2] =
463 | -base_height / 2.0 - v / max * ampli_bottom;
464 | }
465 |
466 | let right = info
467 | .analyzer
468 | .right()
469 | .slice(100.0, 800.0)
470 | .fill_buckets(&mut row_spectrum[..]);
471 | let row_offset = nrow * write_row + cols * 2;
472 | let max = right.max() + 0.0001;
473 | for (i, v) in right.iter().enumerate() {
474 | lines_buf[row_offset + i * 2 + 1].position[2] =
475 | base_height / 2.0 + v / max * ampli_top;
476 | lines_buf[row_offset + i * 2].position[2] =
477 | -base_height / 2.0 - v / max * ampli_bottom;
478 | }
479 | });
480 |
481 | write_row = (write_row + 1) % rows;
482 | }
483 | // }}}
484 | // }}}
485 |
486 | // Drawing {{{
487 | let draw_params = glium::DrawParameters {
488 | line_width: Some(1.0),
489 | point_size: Some(2.0),
490 | blend: glium::Blend {
491 | color: glium::BlendingFunction::Addition {
492 | source: glium::LinearBlendingFactor::SourceAlpha,
493 | destination: glium::LinearBlendingFactor::OneMinusSourceAlpha,
494 | },
495 | alpha: glium::BlendingFunction::Addition {
496 | source: glium::LinearBlendingFactor::One,
497 | destination: glium::LinearBlendingFactor::One,
498 | },
499 | constant_value: (1.0, 1.0, 1.0, 1.0),
500 | },
501 | ..Default::default()
502 | };
503 |
504 | framebuffer1.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);
505 | framebuffer2.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);
506 |
507 | let (ref mut fa, ref mut fb) = (&mut framebuffer1, &mut framebuffer2);
508 |
509 | // Lines {{{
510 | let uniforms = uniform! {
511 | perspective_matrix: Into::<[[f32; 4]; 4]>::into(perspective),
512 | view_matrix: Into::<[[f32; 4]; 4]>::into(view),
513 | model_matrix: Into::<[[f32; 4]; 4]>::into(model_grid),
514 | Colors: &lines_colors,
515 | volume: rolling_volume,
516 | };
517 | fa.draw(
518 | &lines_verts,
519 | &glium::index::NoIndices(glium::index::PrimitiveType::LinesList),
520 | &prepass_program,
521 | &uniforms,
522 | &draw_params,
523 | )
524 | .unwrap();
525 | // }}}
526 |
527 | // Points {{{
528 | let uniforms = uniform! {
529 | perspective_matrix: Into::<[[f32; 4]; 4]>::into(perspective),
530 | view_matrix: Into::<[[f32; 4]; 4]>::into(view),
531 | model_matrix: Into::<[[f32; 4]; 4]>::into(model_grid),
532 | Colors: &points_colors,
533 | volume: rolling_volume,
534 | };
535 | fa.draw(
536 | &lines_verts,
537 | &glium::index::NoIndices(glium::index::PrimitiveType::Points),
538 | &prepass_program,
539 | &uniforms,
540 | &draw_params,
541 | )
542 | .unwrap();
543 | // }}}
544 |
545 | // Post-Processing {{{
546 | beat_rolling = (beat_rolling * 0.95f32).max(base_volume);
547 |
548 | let (fa, fb) = (fb, fa);
549 | let ua = uniform! {
550 | previous: tex1.sampled().wrap_function(glium::uniforms::SamplerWrapFunction::Mirror),
551 | aspect: aspect,
552 | time: frame.time,
553 | volume: volume,
554 | last_beat: frame.time - last_beat,
555 | beat: beat_rolling,
556 | };
557 | let ub = uniform! {
558 | previous: tex2.sampled().wrap_function(glium::uniforms::SamplerWrapFunction::Mirror),
559 | aspect: aspect,
560 | time: frame.time,
561 | volume: volume,
562 | last_beat: frame.time - last_beat,
563 | beat: beat_rolling,
564 | };
565 |
566 | fa.draw(
567 | &quad_verts,
568 | &quad_inds,
569 | &background_program,
570 | &ua,
571 | &draw_params,
572 | )
573 | .unwrap();
574 | #[allow(unused_variables)]
575 | let (fa, ua, fb, ub) = (fb, ub, fa, ua);
576 | // }}}
577 |
578 | // Finalizing / Draw to screen {{{
579 | let target = display.draw();
580 | let dims = target.get_dimensions();
581 | target.blit_from_simple_framebuffer(
582 | &fb,
583 | &glium::Rect {
584 | left: 0,
585 | bottom: 0,
586 | width: window_width,
587 | height: window_height,
588 | },
589 | &glium::BlitTarget {
590 | left: 0,
591 | bottom: 0,
592 | width: dims.0 as i32,
593 | height: dims.1 as i32,
594 | },
595 | glium::uniforms::MagnifySamplerFilter::Linear,
596 | );
597 | target.finish().unwrap();
598 | // }}}
599 | // }}}
600 |
601 | // Events {{{
602 | let mut closed = false;
603 | events_loop.run_return(|ev, _, control_flow| {
604 | match ev {
605 | glutin::event::Event::WindowEvent { event, .. } => match event {
606 | glutin::event::WindowEvent::CloseRequested => closed = true,
607 | glutin::event::WindowEvent::KeyboardInput {
608 | input:
609 | glutin::event::KeyboardInput {
610 | virtual_keycode: Some(glutin::event::VirtualKeyCode::Escape),
611 | ..
612 | },
613 | ..
614 | } => closed = true,
615 | _ => (),
616 | },
617 | _ => (),
618 | }
619 | *control_flow = glutin::event_loop::ControlFlow::Exit;
620 | });
621 | if closed {
622 | break 'main;
623 | }
624 | // }}}
625 |
626 | previous_time = frame.time;
627 | previous_offset = offset;
628 |
629 | let end = std::time::Instant::now();
630 | let dur = end - start;
631 | if dur < frame_time {
632 | let sleep = frame_time - dur;
633 | std::thread::sleep(sleep);
634 | }
635 | }
636 | }
637 |
--------------------------------------------------------------------------------
/noambition/src/shaders/background.frag:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | uniform sampler2D previous;
4 | uniform float last_beat;
5 | uniform float beat;
6 | uniform float volume;
7 | uniform float aspect;
8 |
9 | smooth in vec2 frag_position;
10 | smooth in vec2 frag_texcoord;
11 |
12 | vec3 background() {
13 | vec2 p = frag_position;
14 | p.x = p.x * aspect;
15 | p.y -= 0.5;
16 | float radius = sqrt(p.x * p.x + p.y * p.y);
17 | float t = smoothstep(0.4, 0.38, radius * (last_beat + 1.0));
18 | // float t = smoothstep(0.1 + beat, 0.08 + beat, radius);
19 | return vec3(0.915586, 0.704283, 0.214133) * ((radius * 2.0 + 0.5)) * t + vec3(0.012057, 0.000554, 0.119093) * (1.0 - t) * (1.0 / radius);
20 | }
21 |
22 | void main() {
23 | vec4 prev_color = texture(previous, frag_texcoord);
24 | vec3 bg_color = background();
25 | gl_FragColor = vec4(prev_color.rgb + (1.0 - prev_color.a) * bg_color, 1.0);
26 | }
27 |
--------------------------------------------------------------------------------
/noambition/src/shaders/bokeh.frag:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noambition/src/shaders/bokeh.frag
--------------------------------------------------------------------------------
/noambition/src/shaders/color.frag:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noambition/src/shaders/color.frag
--------------------------------------------------------------------------------
/noambition/src/shaders/fxaa.frag:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rahix/visualizer2/ff44e585361eeee67b806d1223cbba84bc621ba0/noambition/src/shaders/fxaa.frag
--------------------------------------------------------------------------------
/noambition/src/shaders/pp.vert:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | in vec4 position;
4 | in vec2 texcoord;
5 |
6 | smooth out vec2 frag_position;
7 | smooth out vec2 frag_texcoord;
8 |
9 | void main() {
10 | frag_texcoord = texcoord;
11 | frag_position = position.xy;
12 | gl_Position = position;
13 | }
14 |
--------------------------------------------------------------------------------
/noambition/src/shaders/prepass.frag:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | smooth in vec4 frag_position;
4 | smooth in vec4 frag_color;
5 |
6 | void main() {
7 | gl_FragColor = frag_color;
8 | }
9 |
--------------------------------------------------------------------------------
/noambition/src/shaders/prepass.vert:
--------------------------------------------------------------------------------
1 | #version 410
2 |
3 | uniform mat4 perspective_matrix;
4 | uniform mat4 view_matrix;
5 | uniform mat4 model_matrix;
6 | layout(std140) uniform Colors {
7 | vec4 colors[32];
8 | };
9 | uniform float volume;
10 |
11 | in vec4 position;
12 | in uint color_id;
13 |
14 | smooth out vec4 frag_position;
15 | smooth out vec4 frag_color;
16 |
17 | void main() {
18 | frag_position = model_matrix * position;
19 | frag_position.z += exp(-pow(frag_position.y / 5.0 - 4.0, 2.0)) * (pow(frag_position.x / 8.0, 2.0) * 2.0 + 0.1) * (volume * 30.0 + 0.1);
20 | frag_color = colors[color_id];
21 | frag_color.a = frag_color.a * (1.0 - smoothstep(15.0, 25.0, frag_position.y));
22 | gl_Position = perspective_matrix * view_matrix * frag_position;
23 | }
24 |
--------------------------------------------------------------------------------
/noambition/visualizer.toml:
--------------------------------------------------------------------------------
1 | [audio]
2 | window = "nuttall"
3 | conversions = 300
4 | rate = 8000
5 | read_size = 256
6 | recorder = "cpal"
7 |
8 | [noa]
9 | fps = 40
10 |
11 | [noa.cols]
12 | rows = 50
13 | num = 30
14 | depth = 30.0
15 | mid_dist = 0.1
16 | speed = 0.1
17 | slowdown = 0.995
18 | speed_deviation = 50.0
19 | width = 10.0
20 | note_width = 6
21 | colors = [
22 | [1.000000, 0.007443, 0.318893, 1.0],
23 | [0.915586, 0.704283, 0.214133, 1.0],
24 | [0.044844, 0.646290, 0.590788, 1.0],
25 | [0.130165, 0.022207, 0.276140, 1.0],
26 | [1.000000, 0.007443, 0.318893, 1.0],
27 | [0.915586, 0.704283, 0.214133, 1.0],
28 | [0.044844, 0.646290, 0.590788, 1.0],
29 | [0.130165, 0.022207, 0.276140, 1.0],
30 | [1.000000, 0.007443, 0.318893, 1.0],
31 | [0.915586, 0.704283, 0.214133, 1.0],
32 | [0.044844, 0.646290, 0.590788, 1.0],
33 | [0.130165, 0.022207, 0.276140, 1.0],
34 | ]
35 |
36 | amp_top = 0.7
37 | amp_bottom = 0.2
38 |
39 | [noa.camera]
40 | height = 1.0
41 | look_height = 0.8
42 |
--------------------------------------------------------------------------------
/spectral/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Rahix "]
3 | edition = "2018"
4 | name = "spectral"
5 | version = "0.1.0"
6 |
7 | [dependencies]
8 | log = "0.4.17"
9 | sfml = "0.20.0"
10 |
11 | [dependencies.vis-core]
12 | optional = false
13 | path = "../vis-core"
14 |
--------------------------------------------------------------------------------
/spectral/src/main.rs:
--------------------------------------------------------------------------------
1 | use sfml::{graphics, system};
2 | use vis_core::analyzer;
3 |
4 | const BUCKETS: usize = 200;
5 | const LINES: usize = 200;
6 |
7 | #[derive(Debug, Clone)]
8 | struct AnalyzerResult {
9 | analyzer: analyzer::FourierAnalyzer,
10 | average: analyzer::Spectrum>,
11 | beat: usize,
12 | }
13 |
14 | fn main() {
15 | use sfml::graphics::RenderTarget;
16 |
17 | vis_core::default_config();
18 | vis_core::default_log();
19 |
20 | let context_settings = sfml::window::ContextSettings {
21 | antialiasing_level: 4,
22 | ..Default::default()
23 | };
24 |
25 | let mut window = sfml::graphics::RenderWindow::new(
26 | (1600, 800),
27 | "Visualizer2 Spectrum Display",
28 | sfml::window::Style::CLOSE,
29 | &context_settings,
30 | );
31 | window.set_vertical_sync_enabled(true);
32 | window.clear(graphics::Color::BLACK);
33 | window.display();
34 |
35 | let view = graphics::View::from_rect(graphics::Rect::new(0.0, 0.0, 1.0, LINES as f32));
36 | window.set_view(&view);
37 |
38 | let mut texture = graphics::Texture::new().unwrap();
39 | assert!(texture.create(1600, 800));
40 |
41 | let mut rectangle = graphics::RectangleShape::new();
42 | rectangle.set_size(system::Vector2f::new(1.0 / BUCKETS as f32, 1.0));
43 |
44 | // Analyzer {{{
45 | let mut frames = {
46 | let analyzer = analyzer::FourierBuilder::new().plan();
47 | let average = analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1.0);
48 |
49 | // Beat
50 | let mut beat = analyzer::BeatBuilder::new().build();
51 | let mut beat_num = 0;
52 |
53 | vis_core::Visualizer::new(
54 | AnalyzerResult {
55 | analyzer,
56 | average,
57 | beat: 0,
58 | },
59 | move |info, samples| {
60 | info.analyzer.analyze(&samples);
61 |
62 | info.average.fill_from(&info.analyzer.average());
63 |
64 | if beat.detect(&samples) {
65 | beat_num += 1;
66 | }
67 | info.beat = beat_num;
68 |
69 | info
70 | },
71 | )
72 | .frames()
73 | };
74 | // }}}
75 |
76 | let mut last_beat = 0;
77 | 'main: for frame in frames.iter() {
78 | log::trace!("Frame: {:7}@{:.3}", frame.frame, frame.time);
79 |
80 | while let Some(event) = window.poll_event() {
81 | use sfml::window::Event;
82 |
83 | match event {
84 | Event::Closed => break 'main,
85 | Event::KeyPressed {
86 | code: sfml::window::Key::Escape,
87 | ..
88 | } => break 'main,
89 | _ => (),
90 | }
91 | }
92 |
93 | // Move window content up
94 | {
95 | use sfml::graphics::Transformable;
96 |
97 | // SAFETY: Pray for the best.
98 | unsafe {
99 | texture.update_from_render_window(&window, 0, 0);
100 | }
101 | window.clear(graphics::Color::BLACK);
102 | let mut rect_img = graphics::RectangleShape::with_texture(&texture);
103 | rect_img.set_size(system::Vector2f::new(1.0, LINES as f32));
104 | rect_img.set_position(system::Vector2f::new(0.0, -1.0));
105 | window.draw(&rect_img);
106 | }
107 |
108 | frame.info(|info| {
109 | use sfml::graphics::Shape;
110 |
111 | let max = info.average.max();
112 | let n50 = info.average.freq_to_id(50.0);
113 | let n100 = info.average.freq_to_id(100.0);
114 |
115 | let beat = if info.beat > last_beat {
116 | last_beat = info.beat;
117 | rectangle.set_fill_color(graphics::Color::rgb(255, 255, 255));
118 | true
119 | } else {
120 | false
121 | };
122 |
123 | for (i, b) in info.average.iter().enumerate() {
124 | use sfml::graphics::Transformable;
125 |
126 | let int = ((b / max).sqrt() * 255.0) as u8;
127 | if !beat {
128 | rectangle.set_fill_color(graphics::Color::rgb(int, int, int));
129 | if i == n50 || i == n100 {
130 | rectangle.set_fill_color(graphics::Color::rgb(255, 0, 0));
131 | }
132 | }
133 | rectangle.set_position(system::Vector2f::new(
134 | i as f32 / BUCKETS as f32,
135 | LINES as f32 - 1.0,
136 | ));
137 | window.draw(&rectangle);
138 | }
139 | });
140 |
141 | window.display();
142 | std::thread::sleep(std::time::Duration::from_millis(10));
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/spectral/visualizer.toml:
--------------------------------------------------------------------------------
1 | [audio.fourier]
2 | window = "nuttall"
3 |
4 | [audio.beat]
5 | decay = 2000.0
6 | trigger = 0.6
7 | low = 40.0
8 | high = 100.0
9 | downsample = 13
10 |
11 | [pulse]
12 | read_size = 256
13 |
--------------------------------------------------------------------------------
/vis-core/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Rahix "]
3 | edition = "2021"
4 | name = "vis-core"
5 | version = "0.1.0"
6 |
7 | [dependencies]
8 | apodize = "1.0.0"
9 | env_logger = "0.10.0"
10 | ezconf = "0.3.0"
11 | log = "0.4.17"
12 | parking_lot = "0.12.1"
13 | rustfft = "6.1.0"
14 | color-backtrace = "0.5.1"
15 | triple_buffer = "6.2.0"
16 |
17 | [dependencies.cpal]
18 | optional = true
19 | version = "0.15.0"
20 |
21 | [dependencies.pulse-simple]
22 | optional = true
23 | version = "1.0.1"
24 |
25 | [features]
26 | default = ["cpalrecord"]
27 | pulseaudio = ["pulse-simple"]
28 | cpalrecord = ["cpal"]
29 |
--------------------------------------------------------------------------------
/vis-core/README.md:
--------------------------------------------------------------------------------
1 | # vis-core
2 |
3 | **vis-core** is the core of *visualizer2*. It contains the thread orchestration
4 | and a few analyzation tools. These include:
5 |
6 | * [Fourier Spectralizer](src/analyzer/fourier.rs)
7 | * [Beat Detector](src/analyzer/beat.rs)
8 |
9 | ## Audio Input
10 | In *vis-core* audio input happens using the [recorder](src/recorder/mod.rs). You
11 | can implement recorders yourself if the one you need does not exist yet. The interface
12 | is dead simple:
13 |
14 | ```rust
15 | pub trait Recorder: std::fmt::Debug {
16 | /// Return the sample buffer where this recorder pushes data into
17 | fn sample_buffer<'a>(&'a self) -> &'a analyzer::SampleBuffer;
18 |
19 | /// Synchronize sample buffer for this time stamp
20 | ///
21 | /// Returns true as long as new samples are available
22 | ///
23 | /// Async recorders (eg. pulse) will always return true
24 | /// and ignore this call otherwise
25 | fn sync(&mut self, time: f32) -> bool;
26 | }
27 | ```
28 |
29 | As an example, take a look at the [pulseaudio recorder](src/recorder/pulse.rs).
30 |
--------------------------------------------------------------------------------
/vis-core/examples/analyze.rs:
--------------------------------------------------------------------------------
1 | extern crate log;
2 | extern crate vis_core;
3 |
4 | #[derive(Debug, Clone, Default)]
5 | pub struct AnalyzerResult {
6 | spectrum: vis_core::analyzer::Spectrum>,
7 | volume: f32,
8 | beat: f32,
9 | }
10 |
11 | fn main() {
12 | vis_core::default_log();
13 | vis_core::default_config();
14 |
15 | let mut analyzer = vis_core::analyzer::FourierBuilder::new()
16 | .length(512)
17 | .window(vis_core::analyzer::window::nuttall)
18 | .plan();
19 |
20 | let spectrum = vis_core::analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1.0);
21 |
22 | let mut frames = vis_core::Visualizer::new(
23 | AnalyzerResult {
24 | spectrum,
25 | ..Default::default()
26 | },
27 | move |info, samples| {
28 | analyzer.analyze(samples);
29 |
30 | info.spectrum.fill_from(&analyzer.average());
31 | info.volume = samples.volume(0.3) * 400.0;
32 | info.beat = info.spectrum.slice(50.0, 100.0).max() * 0.01;
33 | info
34 | },
35 | )
36 | .async_analyzer(300)
37 | .frames();
38 |
39 | for frame in frames.iter() {
40 | frame.info(|info| {
41 | for _ in 0..info.volume as usize {
42 | print!("#");
43 | }
44 | println!("");
45 | });
46 | std::thread::sleep_ms(30);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/vis-core/src/analyzer/beat.rs:
--------------------------------------------------------------------------------
1 | //! Beat Detection
2 | use crate::analyzer;
3 |
4 | /// Builder for BeatDetector
5 | ///
6 | /// Your configuration needs to be a tradeoff between quality of beat-detection
7 | /// and latency.
8 | ///
9 | /// The latency is roughly: `(fourier_length * downsample) / rate` seconds
10 | #[derive(Debug, Default)]
11 | pub struct BeatBuilder {
12 | /// Decay of the beat volume
13 | ///
14 | /// The lower this is, the faster a more silent beat will be detected.
15 | /// Defaults to `2000.0`. Can also be set from config as `"audio.beat.decay"`.
16 | pub decay: Option,
17 |
18 | /// The minimum volume a beat must have, relative to the previous one, to be deteced.
19 | ///
20 | /// Defaults to `0.4`. Can also be set from config as `"audio.beat.trigger"`.
21 | pub trigger: Option,
22 |
23 | /// Frequency range to search for beats in.
24 | ///
25 | /// Defaults to `50 Hz - 100 Hz`, can also be set from config as `"audio.beat.low"`
26 | /// and `"audio.beat.high"`
27 | pub range: Option<(analyzer::Frequency, analyzer::Frequency)>,
28 |
29 | /// Length of the fourier transform for beat detection.
30 | ///
31 | /// Keep this as short as possible to minimize delay! Defaults to 16, can also
32 | /// be set from config as `"audio.beat.fourier_length"`.
33 | pub fourier_length: Option,
34 |
35 | /// Downsampling factor
36 | ///
37 | /// Defaults to 10 and can be set from config as `"audio.beat.downsample"`.
38 | pub downsample: Option,
39 |
40 | /// Recording rate
41 | ///
42 | ///
43 | /// Defaults to `8000` or `"audio.rate"`.
44 | pub rate: Option,
45 | }
46 |
47 | impl BeatBuilder {
48 | /// Create new BeatBuilder
49 | pub fn new() -> BeatBuilder {
50 | Default::default()
51 | }
52 |
53 | /// Set decay
54 | pub fn decay(&mut self, decay: analyzer::SignalStrength) -> &mut BeatBuilder {
55 | self.decay = Some(decay);
56 | self
57 | }
58 |
59 | /// Set trigger
60 | pub fn trigger(&mut self, trigger: analyzer::SignalStrength) -> &mut BeatBuilder {
61 | self.trigger = Some(trigger);
62 | self
63 | }
64 |
65 | /// Set frequency range
66 | pub fn range(
67 | &mut self,
68 | low: analyzer::Frequency,
69 | high: analyzer::Frequency,
70 | ) -> &mut BeatBuilder {
71 | self.range = Some((low, high));
72 | self
73 | }
74 |
75 | /// Set fourier length
76 | pub fn fourier_length(&mut self, length: usize) -> &mut BeatBuilder {
77 | self.fourier_length = Some(length);
78 | self
79 | }
80 |
81 | /// Set downsampling factor
82 | pub fn downsample(&mut self, downsample: usize) -> &mut BeatBuilder {
83 | self.downsample = Some(downsample);
84 | self
85 | }
86 |
87 | /// Set recording rate
88 | pub fn rate(&mut self, rate: usize) -> &mut BeatBuilder {
89 | self.rate = Some(rate);
90 | self
91 | }
92 |
93 | /// Build the detector
94 | pub fn build(&mut self) -> BeatDetector {
95 | BeatDetector::from_builder(self)
96 | }
97 | }
98 |
99 | /// A beat detector
100 | ///
101 | /// # Example
102 | /// ```
103 | /// # use vis_core::analyzer;
104 | /// # let samples = analyzer::SampleBuffer::new(32000, 8000);
105 | /// let mut beat = analyzer::BeatBuilder::new()
106 | /// .decay(2000.0)
107 | /// .trigger(0.4)
108 | /// .range(50.0, 100.0)
109 | /// .fourier_length(16)
110 | /// .downsample(10)
111 | /// .rate(8000)
112 | /// .build();
113 | ///
114 | /// let isbeat = beat.detect(&samples);
115 | /// ```
116 | pub struct BeatDetector {
117 | decay: analyzer::SignalStrength,
118 | trigger: analyzer::SignalStrength,
119 | range: (analyzer::Frequency, analyzer::Frequency),
120 |
121 | last_volume: analyzer::SignalStrength,
122 | last_delta: analyzer::SignalStrength,
123 | last_beat_delta: analyzer::SignalStrength,
124 |
125 | last_peak: analyzer::SignalStrength,
126 | last_valley: analyzer::SignalStrength,
127 |
128 | analyzer: analyzer::FourierAnalyzer,
129 | }
130 |
131 | impl BeatDetector {
132 | /// Create a BeatDetector from a builder config
133 | pub fn from_builder(build: &BeatBuilder) -> BeatDetector {
134 | let decay = build
135 | .decay
136 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.beat.decay", 2000.0));
137 | BeatDetector {
138 | decay: 1.0 - 1.0 / decay,
139 | trigger: build
140 | .trigger
141 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.beat.trigger", 0.4)),
142 | range: build.range.unwrap_or_else(|| {
143 | (
144 | crate::CONFIG.get_or("audio.beat.low", 50.0),
145 | crate::CONFIG.get_or("audio.beat.high", 100.0),
146 | )
147 | }),
148 |
149 | last_volume: 0.0,
150 | last_delta: 0.0,
151 | last_beat_delta: 0.0,
152 |
153 | last_peak: 0.0,
154 | last_valley: 0.0,
155 |
156 | analyzer: analyzer::FourierBuilder {
157 | window: Some(analyzer::window::nuttall),
158 | length: Some(
159 | build
160 | .fourier_length
161 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.beat.fourier_length", 16)),
162 | ),
163 | downsample: Some(
164 | build
165 | .downsample
166 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.beat.downsample", 10)),
167 | ),
168 | rate: Some(
169 | build
170 | .rate
171 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.rate", 8000)),
172 | ),
173 | }
174 | .plan(),
175 | }
176 | }
177 |
178 | /// Get the volume measured during the last detection cycle
179 | pub fn last_volume(&self) -> analyzer::SignalStrength {
180 | self.last_volume
181 | }
182 |
183 | /// Detect a beat
184 | ///
185 | /// Returns true if this cycle is a beat and false otherwise.
186 | pub fn detect(&mut self, samples: &analyzer::SampleBuffer) -> bool {
187 | self.analyzer.analyze(samples);
188 | let volume = self
189 | .analyzer
190 | .average()
191 | .slice(self.range.0, self.range.1)
192 | .mean();
193 |
194 | // Decay beat_delta to allow quieter beats to be detected
195 | self.last_beat_delta = self.last_beat_delta * self.decay;
196 | let delta = volume - self.last_volume;
197 |
198 | let isbeat = if delta < 0.0 && self.last_delta > 0.0 {
199 | self.last_peak = self.last_volume;
200 | let beat_delta = self.last_peak - self.last_valley;
201 |
202 | // Check if the peak is big enough
203 | if beat_delta > (self.last_beat_delta * self.trigger) {
204 | self.last_beat_delta = self.last_beat_delta.max(beat_delta);
205 | true
206 | } else {
207 | false
208 | }
209 | } else if delta > 0.0 && self.last_delta < 0.0 {
210 | self.last_valley = self.last_volume;
211 | false
212 | } else {
213 | false
214 | };
215 |
216 | self.last_volume = volume;
217 | // Only write delta if the last two volumes weren't the same
218 | if delta != 0.0 {
219 | self.last_delta = delta;
220 | }
221 |
222 | isbeat
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/vis-core/src/analyzer/fourier.rs:
--------------------------------------------------------------------------------
1 | //! Fourier Analysis
2 | use super::Sample;
3 | use crate::analyzer;
4 |
5 | /// Window functions
6 | ///
7 | /// A window-function in this case takes a size and should return a `Vec` of that length filled
8 | /// with the precomputed window coefficients. The following are available by default:
9 | ///
10 | /// * [None / Rectangle](fn.none.html)
11 | ///
12 | /// 
13 | /// * [Sine](fn.sine.html)
14 | ///
15 | /// 
16 | /// * [Hanning](fn.hanning.html)
17 | ///
18 | /// 
19 | /// * [Hamming](fn.hamming.html)
20 | ///
21 | /// 
22 | /// * [Blackman](fn.blackman.html)
23 | ///
24 | /// 
25 | /// * [Nuttall](fn.nuttall.html)
26 | ///
27 | /// 
28 | pub mod window {
29 | /// Blackman Window
30 | ///
31 | /// 
32 | pub fn blackman(size: usize) -> Vec {
33 | apodize::blackman_iter(size).map(|f| f as f32).collect()
34 | }
35 |
36 | /// Hamming Window
37 | ///
38 | /// 
39 | pub fn hamming(size: usize) -> Vec {
40 | apodize::hamming_iter(size).map(|f| f as f32).collect()
41 | }
42 |
43 | /// Hanning Window
44 | ///
45 | /// 
46 | pub fn hanning(size: usize) -> Vec {
47 | apodize::hanning_iter(size).map(|f| f as f32).collect()
48 | }
49 |
50 | /// No window function / Rectangle window
51 | ///
52 | /// 
53 | pub fn none(size: usize) -> Vec {
54 | vec![1.0; size]
55 | }
56 |
57 | /// Nuttall Window
58 | ///
59 | /// 
60 | pub fn nuttall(size: usize) -> Vec {
61 | apodize::nuttall_iter(size).map(|f| f as f32).collect()
62 | }
63 |
64 | /// Sine Window
65 | ///
66 | /// 
67 | pub fn sine(size: usize) -> Vec {
68 | (0..size)
69 | .map(|i| (i as f32 / (size - 1) as f32 * std::f32::consts::PI).sin())
70 | .collect()
71 | }
72 |
73 | /// Triangular Window
74 | ///
75 | /// 
76 | pub fn triangular(size: usize) -> Vec {
77 | apodize::triangular_iter(size).map(|f| f as f32).collect()
78 | }
79 |
80 | /// Get the window function for the specified name
81 | pub fn from_str(name: &str) -> Option Vec> {
82 | match name {
83 | "blackman" => Some(blackman),
84 | "hamming" => Some(hamming),
85 | "hanning" => Some(hanning),
86 | "none" => Some(none),
87 | "nuttall" => Some(nuttall),
88 | "sine" => Some(sine),
89 | "triangular" => Some(triangular),
90 | _ => None,
91 | }
92 | }
93 | }
94 |
95 | /// Builder for FourierAnalyzer
96 | #[derive(Debug, Default)]
97 | pub struct FourierBuilder {
98 | /// Length of the fourier transform
99 | ///
100 | /// Most efficient if this is a power of two
101 | ///
102 | /// Can also be set from config as `"audio.fourier.length"`.
103 | pub length: Option,
104 |
105 | /// Window Function
106 | ///
107 | /// A few window functions are defined in the [`window`](window/index.html) module.
108 | ///
109 | /// Can also be set from config as `"audio.fourier.window"`.
110 | pub window: Option Vec>,
111 |
112 | /// Downsampling factor
113 | ///
114 | /// Can also be set from config as `"audio.fourier.downsample"`.
115 | pub downsample: Option,
116 |
117 | /// Rate of the captured data
118 | ///
119 | /// `FourierAnalyzer` will panic if the `SampleBuffer`'s rate does not match.
120 | ///
121 | /// Can also be set from config as `"audio.rate"`.
122 | pub rate: Option,
123 | }
124 |
125 | impl FourierBuilder {
126 | /// Create a new FourierBuilder
127 | pub fn new() -> FourierBuilder {
128 | Default::default()
129 | }
130 |
131 | /// Set the length of the transform buffer
132 | pub fn length(&mut self, length: usize) -> &mut FourierBuilder {
133 | self.length = Some(length);
134 | self
135 | }
136 |
137 | /// Set the window function
138 | pub fn window(&mut self, f: fn(usize) -> Vec) -> &mut FourierBuilder {
139 | self.window = Some(f);
140 | self
141 | }
142 |
143 | /// Set the downsampling factor
144 | pub fn downsample(&mut self, factor: usize) -> &mut FourierBuilder {
145 | self.downsample = Some(factor);
146 | self
147 | }
148 |
149 | /// Set the recording rate of the `SampleBuffer`
150 | pub fn rate(&mut self, rate: usize) -> &mut FourierBuilder {
151 | self.rate = Some(rate);
152 | self
153 | }
154 |
155 | /// Plan the fourier transform and prepare buffers
156 | pub fn plan(&mut self) -> FourierAnalyzer {
157 | let length = self
158 | .length
159 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.fourier.length", 512));
160 | let window = (self.window.unwrap_or_else(|| {
161 | window::from_str(&crate::CONFIG.get_or("audio.fourier.window", "none".to_string()))
162 | .expect("Selected window type not found!")
163 | }))(length);
164 | let downsample = self
165 | .downsample
166 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.fourier.downsample", 5));
167 | let rate = self
168 | .rate
169 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.rate", 8000));
170 |
171 | FourierAnalyzer::new(length, window, downsample, rate)
172 | }
173 | }
174 |
175 | /// Fourier Analyzer
176 | ///
177 | /// # Example
178 | /// ```
179 | /// # use vis_core::analyzer::fourier::*;
180 | /// let analyzer = FourierBuilder::new()
181 | /// .length(512)
182 | /// .window(window::nuttall)
183 | /// .downsample(5)
184 | /// .rate(8000)
185 | /// .plan();
186 | /// ```
187 | #[derive(Clone)]
188 | pub struct FourierAnalyzer {
189 | length: usize,
190 | buckets: usize,
191 | window: Vec,
192 | downsample: usize,
193 |
194 | rate: usize,
195 | lowest: analyzer::Frequency,
196 | highest: analyzer::Frequency,
197 |
198 | fft: std::sync::Arc>,
199 |
200 | input: [Vec>; 2],
201 | output: Vec>,
202 |
203 | spectra: [analyzer::Spectrum>; 2],
204 | average: analyzer::Spectrum>,
205 | }
206 |
207 | impl std::fmt::Debug for FourierAnalyzer {
208 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
209 | write!(
210 | f,
211 | "FourierAnalyzer {{ length: {:?}, downsample: {:?}, lowest: {:?}, highest: {:?} }}",
212 | self.length, self.downsample, self.lowest, self.highest,
213 | )
214 | }
215 | }
216 |
217 | impl FourierAnalyzer {
218 | fn new(length: usize, window: Vec, downsample: usize, rate: usize) -> FourierAnalyzer {
219 | use rustfft::num_traits::Zero;
220 |
221 | let fft = rustfft::FftPlanner::new().plan_fft_forward(length);
222 | let buckets = length / 2;
223 |
224 | let downsampled_rate = rate as f32 / downsample as f32;
225 | let lowest = downsampled_rate / length as f32;
226 | let highest = downsampled_rate / 2.0;
227 |
228 | let fa = FourierAnalyzer {
229 | length,
230 | buckets,
231 | window,
232 | downsample,
233 |
234 | rate,
235 | lowest,
236 | highest,
237 |
238 | fft,
239 |
240 | input: [Vec::with_capacity(length), Vec::with_capacity(length)],
241 | output: vec![rustfft::num_complex::Complex::zero(); length],
242 |
243 | spectra: [
244 | analyzer::Spectrum::new(vec![0.0; buckets], lowest, highest),
245 | analyzer::Spectrum::new(vec![0.0; buckets], lowest, highest),
246 | ],
247 | average: analyzer::Spectrum::new(vec![0.0; buckets], lowest, highest),
248 | };
249 |
250 | log::debug!("FourierAnalyzer({:p}):", &fa);
251 | log::debug!(" Fourier Length = {:8}", length);
252 | log::debug!(" Buckets = {:8}", buckets);
253 | log::debug!(
254 | " Downsampled Rate = {:8} ({} / {})",
255 | downsampled_rate,
256 | rate,
257 | downsample,
258 | );
259 | log::debug!(" Lowest Frequency = {:8.3} Hz", lowest);
260 | log::debug!(" Highest Frequency = {:8.3} Hz", highest);
261 |
262 | fa
263 | }
264 |
265 | /// Return the number of buckets
266 | #[inline]
267 | pub fn buckets(&self) -> usize {
268 | self.buckets
269 | }
270 |
271 | /// Return the frequency of the lowest bucket
272 | #[inline]
273 | pub fn lowest(&self) -> analyzer::Frequency {
274 | self.lowest
275 | }
276 |
277 | /// Return the frequency of the highest bucket
278 | #[inline]
279 | pub fn highest(&self) -> analyzer::Frequency {
280 | self.highest
281 | }
282 |
283 | /// Analyze a `SampleBuffer`
284 | ///
285 | /// Returns the left and right channel data as spectra
286 | pub fn analyze(
287 | &mut self,
288 | buf: &analyzer::SampleBuffer,
289 | ) -> [analyzer::Spectrum<&[analyzer::SignalStrength]>; 2] {
290 | log::trace!("FourierAnalyzer({:p}): Analyzing ...", &self);
291 |
292 | assert_eq!(
293 | buf.rate(),
294 | self.rate,
295 | "Samplerate of buffer does not match!"
296 | );
297 |
298 | // Copy samples to left and right buffer
299 | self.input[0].clear();
300 | self.input[1].clear();
301 | for ([l, r], window) in buf
302 | .iter(self.length, self.downsample)
303 | .zip(self.window.iter())
304 | {
305 | self.input[0].push(rustfft::num_complex::Complex::new(l * window, 0.0));
306 | self.input[1].push(rustfft::num_complex::Complex::new(r * window, 0.0));
307 | }
308 |
309 | debug_assert_eq!(self.input[0].len(), self.window.len());
310 | debug_assert_eq!(self.input[1].len(), self.window.len());
311 |
312 | self.output.copy_from_slice(&self.input[0]);
313 | self.fft.process(&mut self.output);
314 | for (s, o) in self.spectra[0].iter_mut().zip(self.output.iter()) {
315 | *s = o.norm_sqr();
316 | }
317 |
318 | self.output.copy_from_slice(&self.input[1]);
319 | self.fft.process(&mut self.output);
320 | for (s, o) in self.spectra[1].iter_mut().zip(self.output.iter()) {
321 | *s = o.norm_sqr();
322 | }
323 |
324 | [self.spectra[0].as_ref(), self.spectra[1].as_ref()]
325 | }
326 |
327 | /// Get the left channels spectral data from the last transform
328 | pub fn left(&self) -> analyzer::Spectrum<&[analyzer::SignalStrength]> {
329 | self.spectra[0].as_ref()
330 | }
331 |
332 | /// Get the left channels spectral data from the last transform
333 | pub fn right(&self) -> analyzer::Spectrum<&[analyzer::SignalStrength]> {
334 | self.spectra[1].as_ref()
335 | }
336 |
337 | /// Calculate the average spectrum
338 | pub fn average(&mut self) -> analyzer::Spectrum<&[analyzer::SignalStrength]> {
339 | analyzer::average_spectrum(&mut self.average, &self.spectra);
340 |
341 | self.average.as_ref()
342 | }
343 | }
344 |
345 | #[cfg(test)]
346 | mod tests {
347 | use super::*;
348 |
349 | #[test]
350 | fn test_init() {
351 | FourierBuilder::new()
352 | .rate(8000)
353 | .length(512)
354 | .window(window::from_str("nuttall").unwrap())
355 | .downsample(8)
356 | .plan();
357 | }
358 |
359 | #[test]
360 | fn test_analyze() {
361 | let mut analyzer = FourierBuilder::new()
362 | .rate(8000)
363 | .length(512)
364 | .window(window::from_str("nuttall").unwrap())
365 | .downsample(2)
366 | .plan();
367 |
368 | let buf = crate::analyzer::SampleBuffer::new(1024, 8000);
369 |
370 | buf.push(&[[1.0; 2]; 1024]);
371 |
372 | analyzer.analyze(&buf);
373 | }
374 | }
375 |
--------------------------------------------------------------------------------
/vis-core/src/analyzer/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod beat;
2 | pub mod fourier;
3 | pub mod samples;
4 | pub mod spectrum;
5 |
6 | #[doc(inline)]
7 | pub use self::beat::{BeatBuilder, BeatDetector};
8 | #[doc(inline)]
9 | pub use self::fourier::{window, FourierAnalyzer, FourierBuilder};
10 | #[doc(inline)]
11 | pub use self::samples::{Sample, SampleBuffer};
12 | #[doc(inline)]
13 | pub use self::spectrum::{average_spectrum, Frequency, SignalStrength, Spectrum};
14 |
--------------------------------------------------------------------------------
/vis-core/src/analyzer/samples.rs:
--------------------------------------------------------------------------------
1 | //! Sample Buffer
2 | use std::collections;
3 | use std::sync;
4 |
5 | /// Type Alias for Samples
6 | pub type Sample = f32;
7 |
8 | type _SampleBuf = sync::Arc>>;
9 |
10 | /// A Sample Buffer
11 | ///
12 | /// The sample buffer is a synchronized ring-buffer. During analyzation, it will
13 | /// be frozen so the view stays constant for that duration. The sample buffer
14 | /// should be created by the recorder.
15 | ///
16 | /// # Example
17 | /// ```
18 | /// # use vis_core::analyzer;
19 | /// # let mut beat = analyzer::BeatBuilder::new()
20 | /// # .decay(2000.0)
21 | /// # .trigger(0.4)
22 | /// # .range(50.0, 100.0)
23 | /// # .fourier_length(16)
24 | /// # .downsample(10)
25 | /// # .rate(8000)
26 | /// # .build();
27 | /// let buffer = analyzer::SampleBuffer::new(32000, 8000);
28 | ///
29 | /// { // In recorder
30 | /// buffer.push(&[[1.0, 1.0]; 10]);
31 | /// }
32 | ///
33 | /// { // In analyzer
34 | /// let volume = buffer.volume(0.01);
35 | /// let isbeat = beat.detect(&buffer);
36 | /// }
37 | /// ```
38 | #[derive(Debug, Clone)]
39 | pub struct SampleBuffer {
40 | buf: _SampleBuf,
41 | rate: usize,
42 | }
43 |
44 | impl SampleBuffer {
45 | /// Create a new sample buffer given a size and a record rate
46 | pub fn new(size: usize, rate: usize) -> SampleBuffer {
47 | let buf = collections::VecDeque::from(vec![[0.0; 2]; size]);
48 |
49 | SampleBuffer {
50 | buf: sync::Arc::new(parking_lot::Mutex::new(buf)),
51 | rate,
52 | }
53 | }
54 |
55 | #[inline]
56 | pub fn rate(&self) -> usize {
57 | self.rate
58 | }
59 |
60 | /// Push a slice of interleaved samples to the buffer
61 | pub fn push(&self, new: &[[Sample; 2]]) {
62 | let mut lock = self.buf.lock();
63 |
64 | #[cfg(debug_assertions)]
65 | let debug_size = lock.len();
66 |
67 | for sample in new.iter() {
68 | lock.pop_front().expect("Failed to pop sample!");
69 | lock.push_back(*sample);
70 | }
71 |
72 | #[cfg(debug_assertions)]
73 | assert_eq!(debug_size, lock.len(), "Sample buffer size differs!");
74 | }
75 |
76 | /// Lock the buffer and iterate over the last `size` samples (with downsampling)
77 | ///
78 | /// Set downsampling to `1` if you do not want to use it.
79 | pub fn iter<'a>(&'a self, size: usize, downsample: usize) -> SampleIterator<'a> {
80 | let lock = self.buf.lock();
81 |
82 | SampleIterator {
83 | index: lock.len() - (size * downsample),
84 | buf: lock,
85 | downsample,
86 | }
87 | }
88 |
89 | /// Calculate the RMS Volume over the last `length` seconds
90 | ///
91 | /// Keep `length` short to avoid performance issues
92 | pub fn volume(&self, length: f32) -> super::SignalStrength {
93 | use super::SignalStrength;
94 |
95 | let lock = self.buf.lock();
96 | let len = lock.len();
97 |
98 | let div = (1.0 / length) as usize;
99 |
100 | (lock
101 | .iter()
102 | // Only look at the last tenth of a second
103 | .skip(len - self.rate / div)
104 | // RMS
105 | .map(|s| ((s[0] + s[1]) / 2.0).powi(2) as SignalStrength)
106 | .sum::()
107 | / len as SignalStrength)
108 | .sqrt()
109 | }
110 | }
111 |
112 | pub struct SampleIterator<'a> {
113 | buf: parking_lot::MutexGuard<'a, collections::VecDeque<[Sample; 2]>>,
114 | index: usize,
115 | downsample: usize,
116 | }
117 |
118 | impl Iterator for SampleIterator<'_> {
119 | type Item = [f32; 2];
120 |
121 | fn next(&mut self) -> Option {
122 | let res = self.buf.get(self.index).cloned();
123 | self.index += self.downsample;
124 | res
125 | }
126 | }
127 |
128 | #[cfg(test)]
129 | mod tests {
130 | use super::*;
131 |
132 | #[test]
133 | fn test_simple() {
134 | let buf = SampleBuffer::new(16, 8000);
135 |
136 | buf.push(&[[1.0; 2]; 8]);
137 |
138 | for s in buf.iter(16, 1) {
139 | println!("{:?}", s);
140 | }
141 | }
142 |
143 | #[test]
144 | fn test_overflow() {
145 | let buf = SampleBuffer::new(16, 8000);
146 |
147 | buf.push(
148 | &(100..120)
149 | .map(|i| [i as Sample, i as Sample])
150 | .collect::>(),
151 | );
152 |
153 | buf.push(
154 | &(0..32)
155 | .map(|i| [i as Sample, i as Sample])
156 | .collect::>(),
157 | );
158 |
159 | assert_eq!(
160 | buf.iter(16, 1).collect::>(),
161 | (16..32)
162 | .map(|i| [i as Sample, i as Sample])
163 | .collect::>(),
164 | );
165 | }
166 |
167 | #[test]
168 | fn test_downsample() {
169 | let buf = SampleBuffer::new(32, 8000);
170 |
171 | buf.push(
172 | &(0..32)
173 | .map(|i| [i as Sample, i as Sample])
174 | .collect::>(),
175 | );
176 |
177 | assert_eq!(
178 | &buf.iter(7, 4).collect::>(),
179 | &[[4.0; 2], [8.0; 2], [12.0; 2], [16.0; 2], [20.0; 2], [24.0; 2], [28.0; 2],]
180 | );
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/vis-core/src/analyzer/spectrum.rs:
--------------------------------------------------------------------------------
1 | //! Spectrum Storage Type
2 |
3 | /// Type Alias for Frequencies
4 | pub type Frequency = f32;
5 |
6 | /// Type Alias for Signal Strengths
7 | pub type SignalStrength = f32;
8 |
9 | /// Trait for types that can be used as storage for a spectrum
10 | pub trait Storage: std::ops::Deref {}
11 |
12 | /// Trait for types that can be used as mutable storage for a spectrum
13 | pub trait StorageMut: std::ops::Deref + std::ops::DerefMut {}
14 |
15 | impl Storage for T where T: std::ops::Deref {}
16 |
17 | impl StorageMut for T where T: Storage + std::ops::DerefMut {}
18 |
19 | #[derive(Debug, Clone)]
20 | pub struct Spectrum {
21 | buckets: S,
22 | width: Frequency,
23 | lowest: Frequency,
24 | highest: Frequency,
25 | }
26 |
27 | impl std::ops::Index for Spectrum {
28 | type Output = SignalStrength;
29 |
30 | fn index(&self, index: usize) -> &Self::Output {
31 | &self.buckets[index]
32 | }
33 | }
34 |
35 | impl std::ops::Index for Spectrum {
36 | type Output = SignalStrength;
37 |
38 | fn index(&self, index: Frequency) -> &Self::Output {
39 | &self.buckets[self.freq_to_id(index)]
40 | }
41 | }
42 |
43 | impl std::ops::IndexMut for Spectrum {
44 | fn index_mut(&mut self, index: usize) -> &mut Self::Output {
45 | &mut self.buckets[index]
46 | }
47 | }
48 |
49 | impl std::ops::IndexMut for Spectrum {
50 | fn index_mut(&mut self, index: Frequency) -> &mut Self::Output {
51 | let idx = self.freq_to_id(index);
52 | &mut self.buckets[idx]
53 | }
54 | }
55 |
56 | impl Default for Spectrum> {
57 | fn default() -> Self {
58 | Spectrum {
59 | buckets: vec![0.0],
60 | width: 1.0,
61 | lowest: 0.0,
62 | highest: 0.0,
63 | }
64 | }
65 | }
66 |
67 | impl Spectrum {
68 | /// Create a new spectrum
69 | ///
70 | /// Takes a storage buffer which is potentially prefilled with spectral data,
71 | /// the frequency associated with the lowest bucket and the frequency associated
72 | /// with the highest bucket.
73 | ///
74 | /// # Example
75 | /// ```
76 | /// # use vis_core::analyzer;
77 | /// const N: usize = 128;
78 | /// let spectrum = analyzer::Spectrum::new(vec![0.0; N], 440.0, 660.0);
79 | /// ```
80 | pub fn new(data: S, low: Frequency, high: Frequency) -> Spectrum {
81 | Spectrum {
82 | width: (high - low) / (data.len() as Frequency - 1.0),
83 | lowest: low,
84 | highest: high,
85 |
86 | buckets: data,
87 | }
88 | }
89 |
90 | /// Return the frequency of the lowest bucket
91 | #[inline]
92 | pub fn lowest(&self) -> Frequency {
93 | self.lowest
94 | }
95 |
96 | /// Return the frequency of the highest bucket
97 | #[inline]
98 | pub fn highest(&self) -> Frequency {
99 | self.highest
100 | }
101 |
102 | /// Respan this spectrum. Use with care!
103 | fn respan(&mut self, low: Frequency, high: Frequency) {
104 | self.width = (high - low) / (self.buckets.len() as Frequency - 1.0);
105 | self.lowest = low;
106 | self.highest = high;
107 | }
108 |
109 | /// Return the index of the bucket associated with a frequency
110 | pub fn freq_to_id(&self, f: Frequency) -> usize {
111 | let x = (f - self.lowest) / self.width;
112 |
113 | assert!(x >= 0.0);
114 | let i = x.round() as usize;
115 | assert!(i < self.buckets.len());
116 | i
117 | }
118 |
119 | /// Return the frequency associated with a bucket
120 | pub fn id_to_freq(&self, i: usize) -> Frequency {
121 | assert!(i < self.buckets.len());
122 |
123 | i as Frequency * self.width + self.lowest
124 | }
125 |
126 | /// Iterate over the buckets of this spectrum
127 | pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, SignalStrength> {
128 | self.buckets.iter()
129 | }
130 |
131 | /// Return the number of buckets in this spectrum
132 | pub fn len(&self) -> usize {
133 | self.buckets.len()
134 | }
135 |
136 | /// Return a borrowed spectrum
137 | pub fn as_ref<'a>(&'a self) -> Spectrum<&'a [SignalStrength]> {
138 | Spectrum {
139 | buckets: &self.buckets,
140 | width: self.width,
141 | lowest: self.lowest,
142 | highest: self.highest,
143 | }
144 | }
145 |
146 | /// Return the highest signal strengh in this spectrum
147 | pub fn max(&self) -> SignalStrength {
148 | *self
149 | .buckets
150 | .iter()
151 | .max_by(|a, b| a.partial_cmp(b).unwrap())
152 | .unwrap()
153 | }
154 |
155 | /// Return the average signal strengh in this spectrum
156 | pub fn mean(&self) -> SignalStrength {
157 | self.buckets.iter().sum::() / self.len() as f32
158 | }
159 |
160 | /// Return a spectrum with the buckets between the specified frequencies
161 | ///
162 | /// Requires **no** allocation! Please note that the returned spectrum might be slightly
163 | /// off if the specified frequencies are not exactly in the middle of two buckets.
164 | ///
165 | /// # Example
166 | /// ```
167 | /// # use vis_core::analyzer;
168 | /// let spectrum = analyzer::Spectrum::new(vec![0.0; 400], 220.0, 660.0);
169 | /// let sliced = spectrum.slice(220.0, 440.0);
170 | /// # assert_eq!(sliced.len(), 201);
171 | /// ```
172 | pub fn slice<'a>(&'a self, low: Frequency, high: Frequency) -> Spectrum<&'a [SignalStrength]> {
173 | let start = self.freq_to_id(low);
174 | let end = self.freq_to_id(high);
175 |
176 | Spectrum {
177 | buckets: &self.buckets[start..end + 1],
178 | width: self.width,
179 | lowest: self.lowest + start as Frequency * self.width,
180 | highest: self.lowest + (end) as Frequency * self.width,
181 | }
182 | }
183 |
184 | /// Allocate a buffer and fill it with data from this spectrum
185 | ///
186 | /// Will merge adjacent buckets to fit data into the new buffer.
187 | pub fn fill_buckets_alloc(&self, n: usize) -> Spectrum> {
188 | self.fill_buckets(vec![0.0; n])
189 | }
190 |
191 | /// Fill a given buffer with data from this spectrum
192 | ///
193 | /// Will merge adjacent buckets to fit data into the new buffer.
194 | ///
195 | /// # Example
196 | /// ```
197 | /// # use vis_core::analyzer;
198 | /// let spectrum = analyzer::Spectrum::new(vec![0.0; 400], 220.0, 660.0);
199 | /// let downscaled = spectrum.fill_buckets(vec![0.0; 20]);
200 | /// # assert_eq!(downscaled.len(), 20);
201 | /// ```
202 | pub fn fill_buckets(&self, mut buf: S2) -> Spectrum {
203 | for i in 0..buf.len() {
204 | buf[i] = 0.0;
205 | }
206 |
207 | for (i, v) in self.buckets.iter().enumerate() {
208 | let bucket = i * buf.len() / self.buckets.len();
209 | buf[bucket] += v;
210 | }
211 |
212 | Spectrum {
213 | width: (self.highest - self.lowest) / (buf.len() as f32 - 1.0),
214 | lowest: self.lowest,
215 | highest: self.highest,
216 |
217 | buckets: buf,
218 | }
219 | }
220 |
221 | /// Fill a spectrum with data from this one.
222 | ///
223 | /// Will slice and merge adjacent buckets to make it fit.
224 | ///
225 | /// *Note*: Data might be slightly off if `lowest` and `highest` of `other` do not exactly
226 | /// match buckets in this spectrum.
227 | ///
228 | /// # Example
229 | /// ```
230 | /// # use vis_core::analyzer;
231 | /// let mut spectrum = analyzer::Spectrum::new(vec![0.0; 400], 220.0, 880.0);
232 | ///
233 | /// // Set some value for demo purposes
234 | /// let id = spectrum.freq_to_id(500.0);
235 | /// spectrum[id] = 100.0;
236 | ///
237 | /// let mut other = analyzer::Spectrum::new(vec![0.0; 20], 440.0, 660.0);
238 | ///
239 | /// spectrum.fill_spectrum(&mut other);
240 | ///
241 | /// assert_eq!(other[other.freq_to_id(500.0)], 100.0);
242 | /// ```
243 | pub fn fill_spectrum<'a, S2: StorageMut>(
244 | &self,
245 | other: &'a mut Spectrum,
246 | ) -> &'a mut Spectrum {
247 | self.slice(other.lowest, other.highest)
248 | .fill_buckets(&mut *other.buckets);
249 |
250 | other
251 | }
252 |
253 | /// Find all maxima in this spectrum and allocate a buffer containing them
254 | pub fn find_maxima_alloc(&self) -> Vec<(f32, f32)> {
255 | let derivative = self
256 | .buckets
257 | .windows(2)
258 | .map(|v| v[1] - v[0])
259 | .collect::>();
260 |
261 | let mut maxima = derivative
262 | .windows(2)
263 | .enumerate()
264 | .filter_map(|(i, d)| {
265 | if d[0] > 0.0 && d[1] < 0.0 {
266 | Some((self.id_to_freq(i + 1), self.buckets[i + 1]))
267 | } else {
268 | None
269 | }
270 | })
271 | .collect::>();
272 |
273 | maxima.sort_by(|(_, a1), (_, a2)| a2.partial_cmp(a1).unwrap());
274 |
275 | maxima
276 | }
277 |
278 | /// Find maxima in this spectrum and fill `buffer` with them
279 | ///
280 | /// Please note that this method will behave incorrectly if more than `buffer.len()` maxima
281 | /// exist. Maxima are sorted, starting with the biggest. Returns a slice of the given buffer
282 | /// filled with the found maxima. Might be smaller than `buffer`.
283 | ///
284 | /// # Example
285 | /// ```
286 | /// # use vis_core::analyzer;
287 | /// let mut spectrum = analyzer::Spectrum::new(vec![0.0; 400], 220.0, 660.0);
288 | ///
289 | /// // Manually create maxima
290 | /// spectrum[100] = 10.0;
291 | /// spectrum[200] = 20.0;
292 | /// spectrum[300] = 15.0;
293 | ///
294 | /// let mut buf = [(0.0, 0.0); 5];
295 | /// let maxima = spectrum.find_maxima(&mut buf);
296 | ///
297 | /// assert_eq!(maxima.len(), 3);
298 | /// assert_eq!(
299 | /// &maxima,
300 | /// &[
301 | /// (spectrum.id_to_freq(200), 20.0),
302 | /// (spectrum.id_to_freq(300), 15.0),
303 | /// (spectrum.id_to_freq(100), 10.0),
304 | /// ],
305 | /// );
306 | /// ```
307 | pub fn find_maxima<'a>(&self, buffer: &'a mut [(f32, f32)]) -> &'a [(f32, f32)] {
308 | let derivative = self
309 | .buckets
310 | .windows(2)
311 | .map(|v| v[1] - v[0])
312 | .collect::>();
313 |
314 | let derive2 = derivative.clone();
315 | let maxima_iter = derive2
316 | .iter()
317 | .zip(derivative.iter().skip(1))
318 | .enumerate()
319 | .filter_map(|(i, (d0, d1))| {
320 | if d0 > &0.0 && d1 < &0.0 {
321 | Some((self.id_to_freq(i + 1), self.buckets[i + 1]))
322 | } else {
323 | None
324 | }
325 | });
326 |
327 | let mut num = 0;
328 | for (b, m) in buffer.iter_mut().zip(maxima_iter) {
329 | *b = m;
330 | num += 1;
331 | }
332 |
333 | buffer[..num].sort_by(|(_, a1), (_, a2)| a2.partial_cmp(a1).unwrap());
334 |
335 | &buffer[..num]
336 | }
337 | }
338 |
339 | impl Spectrum {
340 | /// Iterate over this spectrums buckets mutably
341 | pub fn iter_mut<'a>(&'a mut self) -> std::slice::IterMut<'a, SignalStrength> {
342 | self.buckets.iter_mut()
343 | }
344 |
345 | /// Fill this spectrum with values from another one
346 | ///
347 | /// Will merge adjacent buckets to fit data into our buffer.
348 | pub fn fill_from(&mut self, other: &Spectrum) {
349 | other.fill_buckets(&mut *self.buckets);
350 |
351 | self.respan(other.lowest, other.highest);
352 | }
353 | }
354 |
355 | /// Compute the average of multiple spectra
356 | pub fn average_spectrum<'a, S: Storage, SMut: StorageMut>(
357 | out: &'a mut Spectrum,
358 | spectra: &[Spectrum],
359 | ) -> &'a Spectrum {
360 | let buffer = &mut out.buckets;
361 |
362 | let num = spectra.len() as SignalStrength;
363 | debug_assert!(num > 0.0);
364 |
365 | let buckets = buffer.len();
366 | let lowest = spectra[0].lowest;
367 | let highest = spectra[0].highest;
368 |
369 | // Clear output
370 | for b in buffer.iter_mut() {
371 | *b = 0.0;
372 | }
373 |
374 | for s in spectra.iter() {
375 | debug_assert_eq!(s.len(), buckets);
376 | debug_assert_eq!(s.lowest, lowest);
377 | debug_assert_eq!(s.highest, highest);
378 |
379 | for (b, x) in buffer.iter_mut().zip(s.buckets.iter()) {
380 | *b += x;
381 | }
382 | }
383 |
384 | for b in buffer.iter_mut() {
385 | *b /= num;
386 | }
387 |
388 | out.respan(lowest, highest);
389 |
390 | out
391 | }
392 |
393 | #[cfg(test)]
394 | mod tests {
395 | use super::*;
396 |
397 | fn check_integrity(s: &Spectrum) {
398 | assert_eq!(
399 | ((s.highest - s.lowest) / s.width).round() as usize,
400 | s.buckets.len() - 1
401 | );
402 | }
403 |
404 | #[test]
405 | fn test_default() {
406 | let def: Spectrum<_> = Default::default();
407 |
408 | check_integrity(&def);
409 | }
410 |
411 | fn do_tests>)>(mut f: F) {
412 | for n in [100, 1000, 512, 1337].iter().cloned() {
413 | for (l, h, low, high) in [
414 | (100.0, 200.0, 125.0, 175.0),
415 | (50.0, 8000.0, 100.0, 200.0),
416 | (600.0, 750.0, 700.0, 750.0),
417 | (1.0, 20000.0, 1000.0, 2000.0),
418 | (1.0, 20000.0, 50.0, 100.0),
419 | (1.0, 20000.0, 2.0, 19999.0),
420 | (0.0, 10.0, 2.0, 5.0),
421 | ]
422 | .iter()
423 | .cloned()
424 | {
425 | println!("Parameters: N: {:5}, Range: {:7.2}-{:7.2}", n, l, h);
426 | let spectrum = Spectrum::new((0..n).map(|x| x as f32).collect::>(), l, h);
427 | check_integrity(&spectrum);
428 |
429 | f(n, l, h, low, high, spectrum)
430 | }
431 | }
432 | }
433 |
434 | #[test]
435 | fn test_iter() {
436 | do_tests(|_, _, _, _, _, spectrum| {
437 | let bucket_list = spectrum.iter().cloned().collect::>();
438 |
439 | assert_eq!(bucket_list, &*spectrum.buckets);
440 | })
441 | }
442 |
443 | #[test]
444 | fn test_maxima_alloc() {
445 | do_tests(|n, _, _, _, _, mut spectrum| {
446 | let m1 = n / 2 + 25;
447 | let m2 = n / 5;
448 |
449 | spectrum[m1 - 1] = 500000.0;
450 | spectrum[m1] = 1000000.0;
451 | spectrum[m1 + 1] = 500000.0;
452 |
453 | spectrum[m2 - 1] = 350000.0;
454 | spectrum[m2] = 400000.0;
455 | spectrum[m2 + 1] = 350000.0;
456 |
457 | let maxima = spectrum.find_maxima_alloc();
458 |
459 | assert_eq!(
460 | maxima,
461 | &[
462 | (spectrum.id_to_freq(m1), 1000000.0),
463 | (spectrum.id_to_freq(m2), 400000.0),
464 | ]
465 | );
466 | })
467 | }
468 |
469 | #[test]
470 | fn test_maxima() {
471 | do_tests(|n, _, _, _, _, mut spectrum| {
472 | let m1 = n / 2 + 25;
473 | let m2 = n / 5;
474 |
475 | spectrum[m1 - 1] = 500000.0;
476 | spectrum[m1] = 1000000.0;
477 | spectrum[m1 + 1] = 500000.0;
478 |
479 | spectrum[m2 - 1] = 350000.0;
480 | spectrum[m2] = 400000.0;
481 | spectrum[m2 + 1] = 350000.0;
482 |
483 | let mut maxima = [(0.0, 0.0); 10];
484 | let maxima = spectrum.find_maxima(&mut maxima);
485 |
486 | assert_eq!(
487 | &maxima,
488 | &[
489 | (spectrum.id_to_freq(m1), 1000000.0),
490 | (spectrum.id_to_freq(m2), 400000.0),
491 | ]
492 | );
493 | })
494 | }
495 |
496 | #[test]
497 | fn test_conversion() {
498 | do_tests(|n, _, _, _, _, spectrum| {
499 | for i in 0..n {
500 | assert_eq!(i, spectrum.freq_to_id(spectrum.id_to_freq(i)));
501 | }
502 | })
503 | }
504 |
505 | #[test]
506 | fn test_freq_index() {
507 | do_tests(|n, _, _, _, _, spectrum| {
508 | for i in 0..n {
509 | assert_eq!(
510 | spectrum[i as f32 * spectrum.width + spectrum.lowest],
511 | i as f32,
512 | );
513 | }
514 | })
515 | }
516 |
517 | #[test]
518 | fn test_consistency() {
519 | do_tests(|n, l, h, _, _, spectrum| {
520 | println!("- Sanity check");
521 | assert_eq!(spectrum.lowest, l);
522 | assert_eq!(spectrum.highest, h);
523 |
524 | println!("- `low` should be 0");
525 | assert_eq!(spectrum.freq_to_id(l), 0);
526 |
527 | println!("- `high` should be last");
528 | assert_eq!(spectrum.freq_to_id(h), n - 1);
529 | })
530 | }
531 |
532 | #[test]
533 | fn test_slice() {
534 | do_tests(|_, _, _, low, high, spectrum| {
535 | let sliced = spectrum.slice(low, high);
536 | check_integrity(&sliced);
537 |
538 | println!("- Size should stay the same");
539 | assert_eq!(sliced.width, spectrum.width);
540 |
541 | println!("- Low frequency right?");
542 | assert!(
543 | (sliced.lowest - low).abs() < spectrum.width,
544 | "{} < {}",
545 | (sliced.lowest - low).abs(),
546 | spectrum.width
547 | );
548 |
549 | println!("- High frequency right?");
550 | assert!(
551 | (sliced.highest - high).abs() < spectrum.width,
552 | "{} < {}",
553 | (sliced.highest - high).abs(),
554 | spectrum.width
555 | );
556 | })
557 | }
558 |
559 | #[test]
560 | fn test_fill() {
561 | let mut buf = Some(vec![50.0; 20]);
562 | do_tests(|_, _, _, _, _, spectrum| {
563 | let buckets = spectrum.fill_buckets(buf.take().unwrap());
564 | check_integrity(&buckets);
565 |
566 | let spec_sum = spectrum.iter().sum::();
567 | let bucket_sum = buckets.iter().sum::();
568 | assert_eq!(spec_sum, bucket_sum);
569 |
570 | buf = Some(buckets.buckets);
571 | })
572 | }
573 |
574 | #[test]
575 | fn test_self_move() {
576 | let a = Spectrum::new(vec![1.0; 200], 100.0, 800.0);
577 | let mut b = Spectrum::new(vec![0.0; 20], 200.0, 400.0);
578 | let mut c = Spectrum::new(vec![0.0; 20], 0.0, 1.0);
579 |
580 | for _ in 0..2 {
581 | a.fill_spectrum(&mut b);
582 | c = b.fill_buckets(c.buckets);
583 | }
584 |
585 | assert_eq!(b.lowest(), c.lowest());
586 | assert_eq!(b.highest(), c.highest());
587 | }
588 | }
589 |
--------------------------------------------------------------------------------
/vis-core/src/frames.rs:
--------------------------------------------------------------------------------
1 | use crate::{analyzer, recorder};
2 | use std::{cell, rc, time};
3 |
4 | /// Data for one Frame
5 | #[derive(Debug)]
6 | pub struct Frame {
7 | /// Timestamp since start
8 | pub time: f32,
9 |
10 | /// Frame number
11 | pub frame: usize,
12 |
13 | info: rc::Rc>>,
14 | }
15 |
16 | impl Frame {
17 | /// Get access to the latest info shared from the analyzer
18 | ///
19 | /// # Example
20 | /// ```
21 | /// # vis_core::default_config();
22 | /// # let mut frames = vis_core::Visualizer::new(0.0, |i, _s| i)
23 | /// # .frames();
24 | /// for frame in frames.iter() {
25 | /// println!("Time: {}", frame.time);
26 | ///
27 | /// frame.info(|info|
28 | /// println!("Info: {:?}", info)
29 | /// );
30 | /// #
31 | /// # if frame.time > 0.3 {
32 | /// # break;
33 | /// # }
34 | /// }
35 | /// ```
36 | pub fn info(&self, f: F) -> O
37 | where
38 | F: FnOnce(&R) -> O,
39 | {
40 | f(self.info.borrow_mut().read())
41 | }
42 | }
43 |
44 | /// Frames Iterator
45 | #[derive(Debug)]
46 | pub struct Frames
47 | where
48 | R: Clone + Send + 'static,
49 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
50 | {
51 | info: rc::Rc>>,
52 | analyzer: Option<(A, triple_buffer::Input)>,
53 | recorder: Box,
54 | }
55 |
56 | impl Frames
57 | where
58 | R: Clone + Send + 'static,
59 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
60 | {
61 | pub fn from_vis(vis: crate::Visualizer) -> Frames {
62 | let (inp, outp) = triple_buffer::TripleBuffer::new(&vis.initial).split();
63 | let mut f = Frames {
64 | info: rc::Rc::new(cell::RefCell::new(outp)),
65 | analyzer: Some((vis.analyzer, inp)),
66 | recorder: vis
67 | .recorder
68 | .unwrap_or_else(|| recorder::RecorderBuilder::new().build()),
69 | };
70 |
71 | if let Some(num) = vis.async_analyzer {
72 | if num != 0 {
73 | f.detach_analyzer(num);
74 | }
75 | } else {
76 | if let Some(num) = crate::CONFIG.get("audio.conversions") {
77 | f.detach_analyzer(num);
78 | }
79 | }
80 |
81 | f
82 | }
83 |
84 | /// Move analyzer to a separate thread
85 | pub fn detach_analyzer(&mut self, num: usize) {
86 | let (mut analyzer, mut info) = self.analyzer.take().unwrap();
87 | let buffer = self.recorder.sample_buffer().clone();
88 |
89 | let conv_time = std::time::Duration::new(0, (1000000000 / num) as u32);
90 | log::debug!("Conversion Time: {:?}", conv_time);
91 |
92 | std::thread::Builder::new()
93 | .name("analyzer".into())
94 | .spawn(move || loop {
95 | let start = std::time::Instant::now();
96 | analyzer(info.input_buffer(), &buffer);
97 | info.publish();
98 |
99 | let now = std::time::Instant::now();
100 | let duration = now - start;
101 | log::trace!("Conversion Time (real): {:?}", duration);
102 |
103 | if duration < conv_time {
104 | let sleep = conv_time - duration;
105 | log::trace!("Sleeping for {:?}", sleep);
106 | std::thread::sleep(sleep);
107 | }
108 | })
109 | .unwrap();
110 | }
111 |
112 | pub fn iter<'a>(&'a mut self) -> FramesIter<'a, R, A> {
113 | FramesIter {
114 | buffer: self.recorder.sample_buffer().clone(),
115 | visualizer: self,
116 | start_time: time::Instant::now(),
117 | frame: 0,
118 | }
119 | }
120 | }
121 |
122 | /// Borrowed Frames Iterator
123 | #[derive(Debug)]
124 | pub struct FramesIter<'a, R, A>
125 | where
126 | R: Clone + Send + 'static,
127 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
128 | {
129 | visualizer: &'a mut Frames,
130 | buffer: analyzer::SampleBuffer,
131 | start_time: time::Instant,
132 | frame: usize,
133 | }
134 |
135 | impl<'a, R, A> Iterator for FramesIter<'a, R, A>
136 | where
137 | R: Clone + Send + 'static,
138 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
139 | {
140 | type Item = Frame;
141 |
142 | fn next(&mut self) -> Option {
143 | if let Some((ref mut analyzer, ref mut info)) = self.visualizer.analyzer {
144 | analyzer(info.input_buffer(), &self.buffer);
145 | info.publish();
146 | }
147 |
148 | let frame = self.frame;
149 | self.frame += 1;
150 |
151 | Some(Frame {
152 | time: crate::helpers::time(self.start_time),
153 | frame,
154 | info: self.visualizer.info.clone(),
155 | })
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/vis-core/src/helpers.rs:
--------------------------------------------------------------------------------
1 | use std::time;
2 |
3 | pub fn time(start: time::Instant) -> f32 {
4 | let elapsed = time::Instant::now() - start;
5 |
6 | elapsed.as_secs() as f32 + elapsed.subsec_nanos() as f32 * 1e-9
7 | }
8 |
--------------------------------------------------------------------------------
/vis-core/src/lib.rs:
--------------------------------------------------------------------------------
1 | //! A framework for audio-visualization in Rust.
2 | //!
3 | //! # Example
4 | //! ```rust
5 | //! // The data-type for storing analyzer results
6 | //! #[derive(Debug, Clone)]
7 | //! pub struct AnalyzerResult {
8 | //! spectrum: vis_core::analyzer::Spectrum>,
9 | //! volume: f32,
10 | //! beat: f32,
11 | //! }
12 | //!
13 | //! fn main() {
14 | //! // Initialize the logger. Take a look at the sources if you want to customize
15 | //! // the logger.
16 | //! vis_core::default_log();
17 | //!
18 | //! // Load the default config source. More about config later on. You can also
19 | //! // do this manually if you have special requirements.
20 | //! vis_core::default_config();
21 | //!
22 | //! // Initialize some analyzer-tools. These will be moved into the analyzer closure
23 | //! // later on.
24 | //! let mut analyzer = vis_core::analyzer::FourierBuilder::new()
25 | //! .length(512)
26 | //! .window(vis_core::analyzer::window::nuttall)
27 | //! .plan();
28 | //!
29 | //! let spectrum = vis_core::analyzer::Spectrum::new(vec![0.0; analyzer.buckets()], 0.0, 1.0);
30 | //!
31 | //! let mut frames = vis_core::Visualizer::new(
32 | //! AnalyzerResult {
33 | //! spectrum,
34 | //! volume: 0.0,
35 | //! beat: 0.0,
36 | //! },
37 | //! // This closure is the "analyzer". It will be executed in a loop to always
38 | //! // have the latest data available.
39 | //! move |info, samples| {
40 | //! analyzer.analyze(samples);
41 | //!
42 | //! info.spectrum.fill_from(&analyzer.average());
43 | //! info.volume = samples.volume(0.3) * 400.0;
44 | //! info.beat = info.spectrum.slice(50.0, 100.0).max() * 0.01;
45 | //! info
46 | //! },
47 | //! )
48 | //! // Build the frame iterator which is the base of your loop later on
49 | //! .frames();
50 | //!
51 | //! for frame in frames.iter() {
52 | //! // This is just a primitive example, your vis code belongs here
53 | //!
54 | //! // Inside this closure you have access to the latest data from
55 | //! // the analyzer
56 | //! frame.info(|info| {
57 | //! for _ in 0..info.volume as usize {
58 | //! print!("#");
59 | //! }
60 | //! println!("");
61 | //! });
62 | //! std::thread::sleep(std::time::Duration::from_millis(30));
63 | //! #
64 | //! # if frame.frame > 20 {
65 | //! # break;
66 | //! # }
67 | //! }
68 | //! }
69 | //! ```
70 | pub mod analyzer;
71 | pub mod frames;
72 | pub mod helpers;
73 | pub mod recorder;
74 | pub mod visualizer;
75 |
76 | #[doc(inline)]
77 | pub use crate::frames::Frames;
78 | #[doc(inline)]
79 | pub use crate::visualizer::Visualizer;
80 |
81 | /// `ezconf` configuration
82 | ///
83 | /// Usually you will call [`default_config`](fn.default_config.html) in the beginning
84 | /// which will populate this object, but you can also specify your own custom config
85 | /// sources.
86 | ///
87 | /// # Example
88 | /// To make use of this config, use code similar to this:
89 | ///
90 | /// ```rust
91 | /// # vis_core::default_config();
92 | /// let some_configurable_value = vis_core::CONFIG.get_or(
93 | /// // Toml path to value
94 | /// "foo.bar",
95 | /// // Default value. Type gets inferred from this
96 | /// 123,
97 | /// );
98 | /// ```
99 | pub static CONFIG: ezconf::Config = ezconf::INIT;
100 |
101 | /// Initialize config from default sources
102 | ///
103 | /// The default sources are:
104 | /// * `./visualizer.toml`
105 | /// * `./config/visualizer.toml`
106 | /// * Defaults from code
107 | pub fn default_config() {
108 | CONFIG
109 | .init(
110 | [
111 | ezconf::Source::File("visualizer.toml"),
112 | ezconf::Source::File("config/visualizer.toml"),
113 | ]
114 | .iter(),
115 | )
116 | .expect("Can't load config");
117 | }
118 |
119 | /// Initialize logger
120 | ///
121 | /// By default, enable debug output in debug-builds.
122 | pub fn default_log() {
123 | #[cfg(not(debug_assertions))]
124 | env_logger::init();
125 |
126 | #[cfg(debug_assertions)]
127 | env_logger::Builder::from_default_env()
128 | .filter_level(log::LevelFilter::Debug)
129 | .init();
130 |
131 | color_backtrace::install();
132 | }
133 |
--------------------------------------------------------------------------------
/vis-core/src/recorder/cpal.rs:
--------------------------------------------------------------------------------
1 | use crate::analyzer;
2 | use std::thread;
3 | use cpal::traits::*;
4 |
5 | #[derive(Debug, Default)]
6 | pub struct CPalBuilder {
7 | pub rate: Option,
8 | pub buffer_size: Option,
9 | pub read_size: Option,
10 | }
11 |
12 | impl CPalBuilder {
13 | pub fn new() -> CPalBuilder {
14 | Default::default()
15 | }
16 |
17 | pub fn rate(&mut self, rate: usize) -> &mut CPalBuilder {
18 | self.rate = Some(rate);
19 | self
20 | }
21 |
22 | pub fn buffer_size(&mut self, buffer_size: usize) -> &mut CPalBuilder {
23 | self.buffer_size = Some(buffer_size);
24 | self
25 | }
26 |
27 | pub fn read_size(&mut self, read_size: usize) -> &mut CPalBuilder {
28 | self.read_size = Some(read_size);
29 | self
30 | }
31 |
32 | pub fn create(&self) -> CPalRecorder {
33 | CPalRecorder::from_builder(self)
34 | }
35 |
36 | pub fn build(&self) -> Box {
37 | Box::new(self.create())
38 | }
39 | }
40 |
41 | #[derive(Debug)]
42 | pub struct CPalRecorder {
43 | #[allow(unused)]
44 | rate: usize,
45 | buffer: analyzer::SampleBuffer,
46 | }
47 |
48 | impl CPalRecorder {
49 | fn from_builder(build: &CPalBuilder) -> CPalRecorder {
50 | let rate = build
51 | .rate
52 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.rate", 8000));
53 | let buffer_size = build
54 | .buffer_size
55 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.buffer", 16000));
56 | let read_size = build
57 | .buffer_size
58 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.read_size", 256));
59 |
60 | let buf = analyzer::SampleBuffer::new(buffer_size, rate);
61 |
62 | {
63 | let buf = buf.clone();
64 | let mut chunk_buffer = vec![[0.0; 2]; read_size];
65 |
66 | thread::Builder::new()
67 | .name("cpal-recorder".into())
68 | .spawn(move || {
69 | let host = cpal::default_host();
70 | let device = host.default_input_device().expect("Can't acquire input device");
71 |
72 | let config = cpal::StreamConfig {
73 | channels: 2,
74 | sample_rate: cpal::SampleRate(rate as u32),
75 | buffer_size: cpal::BufferSize::Fixed(read_size as u32),
76 | };
77 |
78 | let stream = device.build_input_stream_raw(
79 | &config,
80 | cpal::SampleFormat::F32,
81 | move |data, _info| {
82 | let slice = data.as_slice::().expect("Wrong sample buffer data type!");
83 | for chunk in slice.chunks(chunk_buffer.len() * 2) {
84 | let len = chunk.len() / 2;
85 | for p in chunk_buffer.iter_mut().zip(chunk.chunks_exact(2)) {
86 | match p {
87 | (b, [l, r]) => *b = [*l, *r],
88 | _ => unreachable!(),
89 | }
90 | }
91 | buf.push(&chunk_buffer[..len]);
92 | }
93 | },
94 | |err| {
95 | panic!("Stream Error: {err:?}");
96 | },
97 | None,
98 | ).expect("Failed to build input stream");
99 |
100 | log::debug!("CPal:");
101 | log::debug!(" Sample Rate = {:6}", rate);
102 | log::debug!(" Read Size = {:6}", read_size);
103 | log::debug!(" Buffer Size = {:6}", buffer_size);
104 | log::debug!(" Device = \"{}\"", device.name().as_deref().unwrap_or("unknown"));
105 |
106 | stream.play().unwrap();
107 |
108 | loop {
109 | std::thread::park();
110 | }
111 | })
112 | .unwrap();
113 | }
114 |
115 | CPalRecorder { rate, buffer: buf }
116 | }
117 | }
118 |
119 | impl super::Recorder for CPalRecorder {
120 | fn sample_buffer<'a>(&'a self) -> &'a analyzer::SampleBuffer {
121 | &self.buffer
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/vis-core/src/recorder/mod.rs:
--------------------------------------------------------------------------------
1 | #[cfg(feature = "pulseaudio")]
2 | pub mod pulse;
3 |
4 | #[cfg(feature = "cpalrecord")]
5 | pub mod cpal;
6 |
7 | use crate::analyzer;
8 |
9 | pub trait Recorder: std::fmt::Debug {
10 | /// Return the sample buffer where this recorder pushes data into
11 | fn sample_buffer<'a>(&'a self) -> &'a analyzer::SampleBuffer;
12 |
13 | /// Synchronize sample buffer for this time stamp
14 | ///
15 | /// Returns true as long as new samples are available
16 | ///
17 | /// Async recorders (eg. pulse) will always return true
18 | /// and ignore this call otherwise
19 | fn sync(&mut self, _time: f32) -> bool {
20 | true
21 | }
22 | }
23 |
24 | #[derive(Debug, Clone, Default)]
25 | pub struct RecorderBuilder {
26 | pub rate: Option,
27 | pub buffer_size: Option,
28 | pub read_size: Option,
29 | pub recorder: Option,
30 | }
31 |
32 | impl RecorderBuilder {
33 | pub fn new() -> RecorderBuilder {
34 | Default::default()
35 | }
36 |
37 | pub fn rate(&mut self, rate: usize) -> &mut RecorderBuilder {
38 | self.rate = Some(rate);
39 | self
40 | }
41 |
42 | pub fn buffer_size(&mut self, buffer_size: usize) -> &mut RecorderBuilder {
43 | self.buffer_size = Some(buffer_size);
44 | self
45 | }
46 |
47 | pub fn read_size(&mut self, read_size: usize) -> &mut RecorderBuilder {
48 | self.read_size = Some(read_size);
49 | self
50 | }
51 |
52 | pub fn recorder>(&mut self, rec: S) -> &mut RecorderBuilder {
53 | self.recorder = Some(rec.into());
54 | self
55 | }
56 |
57 | pub fn build(&mut self) -> Box {
58 | let recorder = self
59 | .recorder
60 | .as_ref()
61 | .map(|s| s.clone())
62 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.recorder", "cpal".to_string()));
63 |
64 | match &*recorder {
65 | #[cfg(feature = "cpalrecord")]
66 | "cpal" => self::cpal::CPalBuilder {
67 | rate: self.rate,
68 | buffer_size: self.buffer_size,
69 | read_size: self.read_size,
70 | ..Default::default()
71 | }
72 | .build(),
73 |
74 | #[cfg(feature = "pulseaudio")]
75 | "pulse" => self::pulse::PulseBuilder {
76 | rate: self.rate,
77 | buffer_size: self.buffer_size,
78 | read_size: self.read_size,
79 | ..Default::default()
80 | }
81 | .build(),
82 |
83 | _ => {
84 | panic!("Recorder type does not exist!");
85 | }
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/vis-core/src/recorder/pulse.rs:
--------------------------------------------------------------------------------
1 | use crate::analyzer;
2 | use std::thread;
3 |
4 | #[derive(Debug, Default)]
5 | pub struct PulseBuilder {
6 | pub rate: Option,
7 | pub read_size: Option,
8 | pub buffer_size: Option,
9 | pub name: Option<(String, String)>,
10 | pub device: Option,
11 | }
12 |
13 | impl PulseBuilder {
14 | pub fn new() -> PulseBuilder {
15 | Default::default()
16 | }
17 |
18 | pub fn rate(&mut self, rate: usize) -> &mut PulseBuilder {
19 | self.rate = Some(rate);
20 | self
21 | }
22 |
23 | pub fn read_size(&mut self, size: usize) -> &mut PulseBuilder {
24 | self.read_size = Some(size);
25 | self
26 | }
27 |
28 | pub fn buffer_size(&mut self, size: usize) -> &mut PulseBuilder {
29 | self.buffer_size = Some(size);
30 | self
31 | }
32 |
33 | pub fn name(&mut self, name: S1, desc: S2) -> &mut PulseBuilder
34 | where
35 | S1: Into,
36 | S2: Into,
37 | {
38 | self.name = Some((name.into(), desc.into()));
39 | self
40 | }
41 |
42 | pub fn device>(&mut self, dev: S) -> &mut PulseBuilder {
43 | self.device = Some(dev.into());
44 | self
45 | }
46 |
47 | pub fn create(&self) -> PulseRecorder {
48 | PulseRecorder::from_builder(self)
49 | }
50 |
51 | pub fn build(&self) -> Box {
52 | Box::new(self.create())
53 | }
54 | }
55 |
56 | #[derive(Debug)]
57 | pub struct PulseRecorder {
58 | rate: usize,
59 | buffer: analyzer::SampleBuffer,
60 | }
61 |
62 | impl PulseRecorder {
63 | fn from_builder(build: &PulseBuilder) -> PulseRecorder {
64 | let rate = build
65 | .rate
66 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.rate", 8000));
67 | let buffer_size = build
68 | .buffer_size
69 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.buffer", 16000));
70 | let read_size = build
71 | .buffer_size
72 | .unwrap_or_else(|| crate::CONFIG.get_or("audio.read_size", 32));
73 | let (name, desc) = build.name.clone().unwrap_or((
74 | "visualizer2".to_string(),
75 | "Pulseaudio recorder for visualizer2".to_string(),
76 | ));
77 | let device = build
78 | .device
79 | .clone()
80 | .or_else(|| crate::CONFIG.get("pulse.device"));
81 |
82 | let buf = analyzer::SampleBuffer::new(buffer_size, rate);
83 |
84 | {
85 | let buf = buf.clone();
86 |
87 | thread::Builder::new()
88 | .name("pulse-recorder".into())
89 | .spawn(move || {
90 | let rec: pulse_simple::Record<[analyzer::Sample; 2]> =
91 | pulse_simple::Record::new(
92 | &name,
93 | &desc,
94 | device.as_ref().map(|s| s.as_str()),
95 | rate as u32,
96 | );
97 |
98 | let mut read_buf = vec![[0.0; 2]; read_size];
99 |
100 | log::debug!("Pulseaudio:");
101 | log::debug!(" Sample Rate = {:6}", rate);
102 | log::debug!(" Read Size = {:6}", read_size);
103 | log::debug!(" Buffer Size = {:6}", buffer_size);
104 | if let Some(ref name) = device {
105 | log::debug!(" Device = \"{}\"", name);
106 | } else {
107 | log::debug!(" Device = \"default\"");
108 | }
109 |
110 | loop {
111 | rec.read(&mut read_buf);
112 |
113 | buf.push(&read_buf);
114 | log::trace!("Pushed {} samples", read_size);
115 | }
116 | })
117 | .unwrap();
118 | }
119 |
120 | PulseRecorder { rate, buffer: buf }
121 | }
122 | }
123 |
124 | impl super::Recorder for PulseRecorder {
125 | fn sample_buffer<'a>(&'a self) -> &'a analyzer::SampleBuffer {
126 | &self.buffer
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/vis-core/src/visualizer.rs:
--------------------------------------------------------------------------------
1 | use crate::analyzer;
2 | use crate::recorder;
3 |
4 | /// Builder for a Visualizer
5 | ///
6 | /// The "core" of `vis-core`. Take a look at the crate root for an example on
7 | /// how to use it.
8 | #[derive(Debug)]
9 | pub struct Visualizer
10 | where
11 | R: Clone + Send + 'static,
12 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
13 | {
14 | /// Initial value of the data buffer shared between *analyzer* and *recorder*.
15 | ///
16 | /// This type **must** be `Clone`.
17 | pub initial: R,
18 | /// Analyzer closure
19 | pub analyzer: A,
20 | /// Trait-Object for the recorder
21 | ///
22 | /// By default, [`recorder::default`](../recorder/fn.default.html) is called, which will consult the config
23 | /// (`"audio.recorder"`) or use pulse.
24 | pub recorder: Option>,
25 | /// Whether the analyzer should run asynchroneously and if so, how many times per second.
26 | ///
27 | /// Can also be set from config as `"audio.conversions"`.
28 | pub async_analyzer: Option,
29 | }
30 |
31 | impl Visualizer
32 | where
33 | R: Clone + Send + 'static,
34 | for<'r> A: FnMut(&'r mut R, &analyzer::SampleBuffer) -> &'r mut R + Send + 'static,
35 | {
36 | /// Create a new visualizer
37 | ///
38 | /// You need to supply an initial value for the shared data and the analyzer closure.
39 | pub fn new(initial: R, analyzer: A) -> Visualizer {
40 | Visualizer {
41 | initial,
42 | analyzer,
43 | recorder: None,
44 | async_analyzer: None,
45 | }
46 | }
47 |
48 | /// Specify the recorder to be used.
49 | ///
50 | /// By default, [`recorder::default`](../recorder/fn.default.html) is called, which will consult the config
51 | /// (`"audio.recorder"`) or use pulse.
52 | pub fn recorder(mut self, r: Box) -> Visualizer {
53 | self.recorder = Some(r);
54 | self
55 | }
56 |
57 | /// Make the analyzer run in a separate thread.
58 | ///
59 | /// `conversions_per_second` specifies how often the analyzer should be run (at max).
60 | pub fn async_analyzer(mut self, conversions_per_second: usize) -> Visualizer {
61 | self.async_analyzer = Some(conversions_per_second);
62 | self
63 | }
64 |
65 | /// Create a frames iterator from this visualizer config
66 | ///
67 | /// The frames iterator should then be iterated over in you main loop:
68 | ///
69 | /// ```
70 | /// # vis_core::default_config();
71 | /// # let mut frames = vis_core::Visualizer::new(0.0, |i, _s| i)
72 | /// # .frames();
73 | /// 'main: for frame in frames.iter() {
74 | /// println!("Time: {}", frame.time);
75 | ///
76 | /// if frame.time > 0.3 {
77 | /// break 'main;
78 | /// }
79 | /// }
80 | /// ```
81 | pub fn frames(self) -> crate::Frames {
82 | crate::Frames::from_vis(self)
83 | }
84 | }
85 |
--------------------------------------------------------------------------------