initial commit

Hunter
Thursday, November 12th, 2026 at 11:20 PM

.gitignorenew
LICENSEnew
index.htmlnew
manifest.jsonnew
readme.mdnew
readme_images/loud.gifnew
readme_images/play.gifnew
readme_images/record.gifnew
readme_images/scrub.gifnew
resources/deck.jsnew
resources/favicon.svgnew
resources/icon.pngnew
resources/main.jsnew
resources/style.cssnew
serve.pynew
service-worker.jsnew

.gitignore
 1 +# macOS
 2 +.DS_Store
 3 +
 4 +# Python
 5 +__pycache__/
 6 +
 7 +# Editor
 8 +.vscode/
 9 +.idea/
10 +*.swp
11 +*~
12 +
13 +# Recordings for readme
14 +recordings/
LICENSE
  1 +                    GNU GENERAL PUBLIC LICENSE
  2 +                       Version 3, 29 June 2007
  3 +
  4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
  5 + Everyone is permitted to copy and distribute verbatim copies
  6 + of this license document, but changing it is not allowed.
  7 +
  8 +                            Preamble
  9 +
 10 +  The GNU General Public License is a free, copyleft license for
 11 +software and other kinds of works.
 12 +
 13 +  The licenses for most software and other practical works are designed
 14 +to take away your freedom to share and change the works.  By contrast,
 15 +the GNU General Public License is intended to guarantee your freedom to
 16 +share and change all versions of a program--to make sure it remains free
 17 +software for all its users.  We, the Free Software Foundation, use the
 18 +GNU General Public License for most of our software; it applies also to
 19 +any other work released this way by its authors.  You can apply it to
 20 +your programs, too.
 21 +
 22 +  When we speak of free software, we are referring to freedom, not
 23 +price.  Our General Public Licenses are designed to make sure that you
 24 +have the freedom to distribute copies of free software (and charge for
 25 +them if you wish), that you receive source code or can get it if you
 26 +want it, that you can change the software or use pieces of it in new
 27 +free programs, and that you know you can do these things.
 28 +
 29 +  To protect your rights, we need to prevent others from denying you
 30 +these rights or asking you to surrender the rights.  Therefore, you have
 31 +certain responsibilities if you distribute copies of the software, or if
 32 +you modify it: responsibilities to respect the freedom of others.
 33 +
 34 +  For example, if you distribute copies of such a program, whether
 35 +gratis or for a fee, you must pass on to the recipients the same
 36 +freedoms that you received.  You must make sure that they, too, receive
 37 +or can get the source code.  And you must show them these terms so they
 38 +know their rights.
 39 +
 40 +  Developers that use the GNU GPL protect your rights with two steps:
 41 +(1) assert copyright on the software, and (2) offer you this License
 42 +giving you legal permission to copy, distribute and/or modify it.
 43 +
 44 +  For the developers' and authors' protection, the GPL clearly explains
 45 +that there is no warranty for this free software.  For both users' and
 46 +authors' sake, the GPL requires that modified versions be marked as
 47 +changed, so that their problems will not be attributed erroneously to
 48 +authors of previous versions.
 49 +
 50 +  Some devices are designed to deny users access to install or run
 51 +modified versions of the software inside them, although the manufacturer
 52 +can do so.  This is fundamentally incompatible with the aim of
 53 +protecting users' freedom to change the software.  The systematic
 54 +pattern of such abuse occurs in the area of products for individuals to
 55 +use, which is precisely where it is most unacceptable.  Therefore, we
 56 +have designed this version of the GPL to prohibit the practice for those
 57 +products.  If such problems arise substantially in other domains, we
 58 +stand ready to extend this provision to those domains in future versions
 59 +of the GPL, as needed to protect the freedom of users.
 60 +
 61 +  Finally, every program is threatened constantly by software patents.
 62 +States should not allow patents to restrict development and use of
 63 +software on general-purpose computers, but in those that do, we wish to
 64 +avoid the special danger that patents applied to a free program could
 65 +make it effectively proprietary.  To prevent this, the GPL assures that
 66 +patents cannot be used to render the program non-free.
 67 +
 68 +  The precise terms and conditions for copying, distribution and
 69 +modification follow.
 70 +
 71 +                       TERMS AND CONDITIONS
 72 +
 73 +  0. Definitions.
 74 +
 75 +  "This License" refers to version 3 of the GNU General Public License.
 76 +
 77 +  "Copyright" also means copyright-like laws that apply to other kinds of
 78 +works, such as semiconductor masks.
 79 +
 80 +  "The Program" refers to any copyrightable work licensed under this
 81 +License.  Each licensee is addressed as "you".  "Licensees" and
 82 +"recipients" may be individuals or organizations.
 83 +
 84 +  To "modify" a work means to copy from or adapt all or part of the work
 85 +in a fashion requiring copyright permission, other than the making of an
 86 +exact copy.  The resulting work is called a "modified version" of the
 87 +earlier work or a work "based on" the earlier work.
 88 +
 89 +  A "covered work" means either the unmodified Program or a work based
 90 +on the Program.
 91 +
 92 +  To "propagate" a work means to do anything with it that, without
 93 +permission, would make you directly or secondarily liable for
 94 +infringement under applicable copyright law, except executing it on a
 95 +computer or modifying a private copy.  Propagation includes copying,
 96 +distribution (with or without modification), making available to the
 97 +public, and in some countries other activities as well.
 98 +
 99 +  To "convey" a work means any kind of propagation that enables other
100 +parties to make or receive copies.  Mere interaction with a user through
101 +a computer network, with no transfer of a copy, is not conveying.
102 +
103 +  An interactive user interface displays "Appropriate Legal Notices"
104 +to the extent that it includes a convenient and prominently visible
105 +feature that (1) displays an appropriate copyright notice, and (2)
106 +tells the user that there is no warranty for the work (except to the
107 +extent that warranties are provided), that licensees may convey the
108 +work under this License, and how to view a copy of this License.  If
109 +the interface presents a list of user commands or options, such as a
110 +menu, a prominent item in the list meets this criterion.
111 +
112 +  1. Source Code.
113 +
114 +  The "source code" for a work means the preferred form of the work
115 +for making modifications to it.  "Object code" means any non-source
116 +form of a work.
117 +
118 +  A "Standard Interface" means an interface that either is an official
119 +standard defined by a recognized standards body, or, in the case of
120 +interfaces specified for a particular programming language, one that
121 +is widely used among developers working in that language.
122 +
123 +  The "System Libraries" of an executable work include anything, other
124 +than the work as a whole, that (a) is included in the normal form of
125 +packaging a Major Component, but which is not part of that Major
126 +Component, and (b) serves only to enable use of the work with that
127 +Major Component, or to implement a Standard Interface for which an
128 +implementation is available to the public in source code form.  A
129 +"Major Component", in this context, means a major essential component
130 +(kernel, window system, and so on) of the specific operating system
131 +(if any) on which the executable work runs, or a compiler used to
132 +produce the work, or an object code interpreter used to run it.
133 +
134 +  The "Corresponding Source" for a work in object code form means all
135 +the source code needed to generate, install, and (for an executable
136 +work) run the object code and to modify the work, including scripts to
137 +control those activities.  However, it does not include the work's
138 +System Libraries, or general-purpose tools or generally available free
139 +programs which are used unmodified in performing those activities but
140 +which are not part of the work.  For example, Corresponding Source
141 +includes interface definition files associated with source files for
142 +the work, and the source code for shared libraries and dynamically
143 +linked subprograms that the work is specifically designed to require,
144 +such as by intimate data communication or control flow between those
145 +subprograms and other parts of the work.
146 +
147 +  The Corresponding Source need not include anything that users
148 +can regenerate automatically from other parts of the Corresponding
149 +Source.
150 +
151 +  The Corresponding Source for a work in source code form is that
152 +same work.
153 +
154 +  2. Basic Permissions.
155 +
156 +  All rights granted under this License are granted for the term of
157 +copyright on the Program, and are irrevocable provided the stated
158 +conditions are met.  This License explicitly affirms your unlimited
159 +permission to run the unmodified Program.  The output from running a
160 +covered work is covered by this License only if the output, given its
161 +content, constitutes a covered work.  This License acknowledges your
162 +rights of fair use or other equivalent, as provided by copyright law.
163 +
164 +  You may make, run and propagate covered works that you do not
165 +convey, without conditions so long as your license otherwise remains
166 +in force.  You may convey covered works to others for the sole purpose
167 +of having them make modifications exclusively for you, or provide you
168 +with facilities for running those works, provided that you comply with
169 +the terms of this License in conveying all material for which you do
170 +not control copyright.  Those thus making or running the covered works
171 +for you must do so exclusively on your behalf, under your direction
172 +and control, on terms that prohibit them from making any copies of
173 +your copyrighted material outside their relationship with you.
174 +
175 +  Conveying under any other circumstances is permitted solely under
176 +the conditions stated below.  Sublicensing is not allowed; section 10
177 +makes it unnecessary.
178 +
179 +  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 +
181 +  No covered work shall be deemed part of an effective technological
182 +measure under any applicable law fulfilling obligations under article
183 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 +similar laws prohibiting or restricting circumvention of such
185 +measures.
186 +
187 +  When you convey a covered work, you waive any legal power to forbid
188 +circumvention of technological measures to the extent such circumvention
189 +is effected by exercising rights under this License with respect to
190 +the covered work, and you disclaim any intention to limit operation or
191 +modification of the work as a means of enforcing, against the work's
192 +users, your or third parties' legal rights to forbid circumvention of
193 +technological measures.
194 +
195 +  4. Conveying Verbatim Copies.
196 +
197 +  You may convey verbatim copies of the Program's source code as you
198 +receive it, in any medium, provided that you conspicuously and
199 +appropriately publish on each copy an appropriate copyright notice;
200 +keep intact all notices stating that this License and any
201 +non-permissive terms added in accord with section 7 apply to the code;
202 +keep intact all notices of the absence of any warranty; and give all
203 +recipients a copy of this License along with the Program.
204 +
205 +  You may charge any price or no price for each copy that you convey,
206 +and you may offer support or warranty protection for a fee.
207 +
208 +  5. Conveying Modified Source Versions.
209 +
210 +  You may convey a work based on the Program, or the modifications to
211 +produce it from the Program, in the form of source code under the
212 +terms of section 4, provided that you also meet all of these conditions:
213 +
214 +    a) The work must carry prominent notices stating that you modified
215 +    it, and giving a relevant date.
216 +
217 +    b) The work must carry prominent notices stating that it is
218 +    released under this License and any conditions added under section
219 +    7.  This requirement modifies the requirement in section 4 to
220 +    "keep intact all notices".
221 +
222 +    c) You must license the entire work, as a whole, under this
223 +    License to anyone who comes into possession of a copy.  This
224 +    License will therefore apply, along with any applicable section 7
225 +    additional terms, to the whole of the work, and all its parts,
226 +    regardless of how they are packaged.  This License gives no
227 +    permission to license the work in any other way, but it does not
228 +    invalidate such permission if you have separately received it.
229 +
230 +    d) If the work has interactive user interfaces, each must display
231 +    Appropriate Legal Notices; however, if the Program has interactive
232 +    interfaces that do not display Appropriate Legal Notices, your
233 +    work need not make them do so.
234 +
235 +  A compilation of a covered work with other separate and independent
236 +works, which are not by their nature extensions of the covered work,
237 +and which are not combined with it such as to form a larger program,
238 +in or on a volume of a storage or distribution medium, is called an
239 +"aggregate" if the compilation and its resulting copyright are not
240 +used to limit the access or legal rights of the compilation's users
241 +beyond what the individual works permit.  Inclusion of a covered work
242 +in an aggregate does not cause this License to apply to the other
243 +parts of the aggregate.
244 +
245 +  6. Conveying Non-Source Forms.
246 +
247 +  You may convey a covered work in object code form under the terms
248 +of sections 4 and 5, provided that you also convey the
249 +machine-readable Corresponding Source under the terms of this License,
250 +in one of these ways:
251 +
252 +    a) Convey the object code in, or embodied in, a physical product
253 +    (including a physical distribution medium), accompanied by the
254 +    Corresponding Source fixed on a durable physical medium
255 +    customarily used for software interchange.
256 +
257 +    b) Convey the object code in, or embodied in, a physical product
258 +    (including a physical distribution medium), accompanied by a
259 +    written offer, valid for at least three years and valid for as
260 +    long as you offer spare parts or customer support for that product
261 +    model, to give anyone who possesses the object code either (1) a
262 +    copy of the Corresponding Source for all the software in the
263 +    product that is covered by this License, on a durable physical
264 +    medium customarily used for software interchange, for a price no
265 +    more than your reasonable cost of physically performing this
266 +    conveying of source, or (2) access to copy the
267 +    Corresponding Source from a network server at no charge.
268 +
269 +    c) Convey individual copies of the object code with a copy of the
270 +    written offer to provide the Corresponding Source.  This
271 +    alternative is allowed only occasionally and noncommercially, and
272 +    only if you received the object code with such an offer, in accord
273 +    with subsection 6b.
274 +
275 +    d) Convey the object code by offering access from a designated
276 +    place (gratis or for a charge), and offer equivalent access to the
277 +    Corresponding Source in the same way through the same place at no
278 +    further charge.  You need not require recipients to copy the
279 +    Corresponding Source along with the object code.  If the place to
280 +    copy the object code is a network server, the Corresponding Source
281 +    may be on a different server (operated by you or a third party)
282 +    that supports equivalent copying facilities, provided you maintain
283 +    clear directions next to the object code saying where to find the
284 +    Corresponding Source.  Regardless of what server hosts the
285 +    Corresponding Source, you remain obligated to ensure that it is
286 +    available for as long as needed to satisfy these requirements.
287 +
288 +    e) Convey the object code using peer-to-peer transmission, provided
289 +    you inform other peers where the object code and Corresponding
290 +    Source of the work are being offered to the general public at no
291 +    charge under subsection 6d.
292 +
293 +  A separable portion of the object code, whose source code is excluded
294 +from the Corresponding Source as a System Library, need not be
295 +included in conveying the object code work.
296 +
297 +  A "User Product" is either (1) a "consumer product", which means any
298 +tangible personal property which is normally used for personal, family,
299 +or household purposes, or (2) anything designed or sold for incorporation
300 +into a dwelling.  In determining whether a product is a consumer product,
301 +doubtful cases shall be resolved in favor of coverage.  For a particular
302 +product received by a particular user, "normally used" refers to a
303 +typical or common use of that class of product, regardless of the status
304 +of the particular user or of the way in which the particular user
305 +actually uses, or expects or is expected to use, the product.  A product
306 +is a consumer product regardless of whether the product has substantial
307 +commercial, industrial or non-consumer uses, unless such uses represent
308 +the only significant mode of use of the product.
309 +
310 +  "Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to install
312 +and execute modified versions of a covered work in that User Product from
313 +a modified version of its Corresponding Source.  The information must
314 +suffice to ensure that the continued functioning of the modified object
315 +code is in no case prevented or interfered with solely because
316 +modification has been made.
317 +
318 +  If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information.  But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
328 +
329 +  The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or updates
331 +for a work that has been modified or installed by the recipient, or for
332 +the User Product in which it has been modified or installed.  Access to a
333 +network may be denied when the modification itself materially and
334 +adversely affects the operation of the network or violates the rules and
335 +protocols for communication across the network.
336 +
337 +  Corresponding Source conveyed, and Installation Information provided,
338 +in accord with this section must be in a format that is publicly
339 +documented (and with an implementation available to the public in
340 +source code form), and must require no special password or key for
341 +unpacking, reading or copying.
342 +
343 +  7. Additional Terms.
344 +
345 +  "Additional permissions" are terms that supplement the terms of this
346 +License by making exceptions from one or more of its conditions.
347 +Additional permissions that are applicable to the entire Program shall
348 +be treated as though they were included in this License, to the extent
349 +that they are valid under applicable law.  If additional permissions
350 +apply only to part of the Program, that part may be used separately
351 +under those permissions, but the entire Program remains governed by
352 +this License without regard to the additional permissions.
353 +
354 +  When you convey a copy of a covered work, you may at your option
355 +remove any additional permissions from that copy, or from any part of
356 +it.  (Additional permissions may be written to require their own
357 +removal in certain cases when you modify the work.)  You may place
358 +additional permissions on material, added by you to a covered work,
359 +for which you have or can give appropriate copyright permission.
360 +
361 +  Notwithstanding any other provision of this License, for material you
362 +add to a covered work, you may (if authorized by the copyright holders of
363 +that material) supplement the terms of this License with terms:
364 +
365 +    a) Disclaiming warranty or limiting liability differently from the
366 +    terms of sections 15 and 16 of this License; or
367 +
368 +    b) Requiring preservation of specified reasonable legal notices or
369 +    author attributions in that material or in the Appropriate Legal
370 +    Notices displayed by works containing it; or
371 +
372 +    c) Prohibiting misrepresentation of the origin of that material, or
373 +    requiring that modified versions of such material be marked in
374 +    reasonable ways as different from the original version; or
375 +
376 +    d) Limiting the use for publicity purposes of names of licensors or
377 +    authors of the material; or
378 +
379 +    e) Declining to grant rights under trademark law for use of some
380 +    trade names, trademarks, or service marks; or
381 +
382 +    f) Requiring indemnification of licensors and authors of that
383 +    material by anyone who conveys the material (or modified versions of
384 +    it) with contractual assumptions of liability to the recipient, for
385 +    any liability that these contractual assumptions directly impose on
386 +    those licensors and authors.
387 +
388 +  All other non-permissive additional terms are considered "further
389 +restrictions" within the meaning of section 10.  If the Program as you
390 +received it, or any part of it, contains a notice stating that it is
391 +governed by this License along with a term that is a further
392 +restriction, you may remove that term.  If a license document contains
393 +a further restriction but permits relicensing or conveying under this
394 +License, you may add to a covered work material governed by the terms
395 +of that license document, provided that the further restriction does
396 +not survive such relicensing or conveying.
397 +
398 +  If you add terms to a covered work in accord with this section, you
399 +must place, in the relevant source files, a statement of the
400 +additional terms that apply to those files, or a notice indicating
401 +where to find the applicable terms.
402 +
403 +  Additional terms, permissive or non-permissive, may be stated in the
404 +form of a separately written license, or stated as exceptions;
405 +the above requirements apply either way.
406 +
407 +  8. Termination.
408 +
409 +  You may not propagate or modify a covered work except as expressly
410 +provided under this License.  Any attempt otherwise to propagate or
411 +modify it is void, and will automatically terminate your rights under
412 +this License (including any patent licenses granted under the third
413 +paragraph of section 11).
414 +
415 +  However, if you cease all violation of this License, then your
416 +license from a particular copyright holder is reinstated (a)
417 +provisionally, unless and until the copyright holder explicitly and
418 +finally terminates your license, and (b) permanently, if the copyright
419 +holder fails to notify you of the violation by some reasonable means
420 +prior to 60 days after the cessation.
421 +
422 +  Moreover, your license from a particular copyright holder is
423 +reinstated permanently if the copyright holder notifies you of the
424 +violation by some reasonable means, this is the first time you have
425 +received notice of violation of this License (for any work) from that
426 +copyright holder, and you cure the violation prior to 30 days after
427 +your receipt of the notice.
428 +
429 +  Termination of your rights under this section does not terminate the
430 +licenses of parties who have received copies or rights from you under
431 +this License.  If your rights have been terminated and not permanently
432 +reinstated, you do not qualify to receive new licenses for the same
433 +material under section 10.
434 +
435 +  9. Acceptance Not Required for Having Copies.
436 +
437 +  You are not required to accept this License in order to receive or
438 +run a copy of the Program.  Ancillary propagation of a covered work
439 +occurring solely as a consequence of using peer-to-peer transmission
440 +to receive a copy likewise does not require acceptance.  However,
441 +nothing other than this License grants you permission to propagate or
442 +modify any covered work.  These actions infringe copyright if you do
443 +not accept this License.  Therefore, by modifying or propagating a
444 +covered work, you indicate your acceptance of this License to do so.
445 +
446 +  10. Automatic Licensing of Downstream Recipients.
447 +
448 +  Each time you convey a covered work, the recipient automatically
449 +receives a license from the original licensors, to run, modify and
450 +propagate that work, subject to this License.  You are not responsible
451 +for enforcing compliance by third parties with this License.
452 +
453 +  An "entity transaction" is a transaction transferring control of an
454 +organization, or substantially all assets of one, or subdividing an
455 +organization, or merging organizations.  If propagation of a covered
456 +work results from an entity transaction, each party to that
457 +transaction who receives a copy of the work also receives whatever
458 +licenses to the work the party's predecessor in interest had or could
459 +give under the previous paragraph, plus a right to possession of the
460 +Corresponding Source of the work from the predecessor in interest, if
461 +the predecessor has it or can get it with reasonable efforts.
462 +
463 +  You may not impose any further restrictions on the exercise of the
464 +rights granted or affirmed under this License.  For example, you may
465 +not impose a license fee, royalty, or other charge for exercise of
466 +rights granted under this License, and you may not initiate litigation
467 +(including a cross-claim or counterclaim in a lawsuit) alleging that
468 +any patent claim is infringed by making, using, selling, offering for
469 +sale, or importing the Program or any portion of it.
470 +
471 +  11. Patents.
472 +
473 +  A "contributor" is a copyright holder who authorizes use under this
474 +License of the Program or a work on which the Program is based.  The
475 +work thus licensed is called the contributor's "contributor version".
476 +
477 +  A contributor's "essential patent claims" are all patent claims
478 +owned or controlled by the contributor, whether already acquired or
479 +hereafter acquired, that would be infringed by some manner, permitted
480 +by this License, of making, using, or selling its contributor version,
481 +but do not include claims that would be infringed only as a
482 +consequence of further modification of the contributor version.  For
483 +purposes of this definition, "control" includes the right to grant
484 +patent sublicenses in a manner consistent with the requirements of
485 +this License.
486 +
487 +  Each contributor grants you a non-exclusive, worldwide, royalty-free
488 +patent license under the contributor's essential patent claims, to
489 +make, use, sell, offer for sale, import and otherwise run, modify and
490 +propagate the contents of its contributor version.
491 +
492 +  In the following three paragraphs, a "patent license" is any express
493 +agreement or commitment, however denominated, not to enforce a patent
494 +(such as an express permission to practice a patent or covenant not to
495 +sue for patent infringement).  To "grant" such a patent license to a
496 +party means to make such an agreement or commitment not to enforce a
497 +patent against the party.
498 +
499 +  If you convey a covered work, knowingly relying on a patent license,
500 +and the Corresponding Source of the work is not available for anyone
501 +to copy, free of charge and under the terms of this License, through a
502 +publicly available network server or other readily accessible means,
503 +then you must either (1) cause the Corresponding Source to be so
504 +available, or (2) arrange to deprive yourself of the benefit of the
505 +patent license for this particular work, or (3) arrange, in a manner
506 +consistent with the requirements of this License, to extend the patent
507 +license to downstream recipients.  "Knowingly relying" means you have
508 +actual knowledge that, but for the patent license, your conveying the
509 +covered work in a country, or your recipient's use of the covered work
510 +in a country, would infringe one or more identifiable patents in that
511 +country that you have reason to believe are valid.
512 +
513 +  If, pursuant to or in connection with a single transaction or
514 +arrangement, you convey, or propagate by procuring conveyance of, a
515 +covered work, and grant a patent license to some of the parties
516 +receiving the covered work authorizing them to use, propagate, modify
517 +or convey a specific copy of the covered work, then the patent license
518 +you grant is automatically extended to all recipients of the covered
519 +work and works based on it.
520 +
521 +  A patent license is "discriminatory" if it does not include within
522 +the scope of its coverage, prohibits the exercise of, or is
523 +conditioned on the non-exercise of one or more of the rights that are
524 +specifically granted under this License.  You may not convey a covered
525 +work if you are a party to an arrangement with a third party that is
526 +in the business of distributing software, under which you make payment
527 +to the third party based on the extent of your activity of conveying
528 +the work, and under which the third party grants, to any of the
529 +parties who would receive the covered work from you, a discriminatory
530 +patent license (a) in connection with copies of the covered work
531 +conveyed by you (or copies made from those copies), or (b) primarily
532 +for and in connection with specific products or compilations that
533 +contain the covered work, unless you entered into that arrangement,
534 +or that patent license was granted, prior to 28 March 2007.
535 +
536 +  Nothing in this License shall be construed as excluding or limiting
537 +any implied license or other defenses to infringement that may
538 +otherwise be available to you under applicable patent law.
539 +
540 +  12. No Surrender of Others' Freedom.
541 +
542 +  If conditions are imposed on you (whether by court order, agreement or
543 +otherwise) that contradict the conditions of this License, they do not
544 +excuse you from the conditions of this License.  If you cannot convey a
545 +covered work so as to satisfy simultaneously your obligations under this
546 +License and any other pertinent obligations, then as a consequence you may
547 +not convey it at all.  For example, if you agree to terms that obligate you
548 +to collect a royalty for further conveying from those to whom you convey
549 +the Program, the only way you could satisfy both those terms and this
550 +License would be to refrain entirely from conveying the Program.
551 +
552 +  13. Use with the GNU Affero General Public License.
553 +
554 +  Notwithstanding any other provision of this License, you have
555 +permission to link or combine any covered work with a work licensed
556 +under version 3 of the GNU Affero General Public License into a single
557 +combined work, and to convey the resulting work.  The terms of this
558 +License will continue to apply to the part which is the covered work,
559 +but the special requirements of the GNU Affero General Public License,
560 +section 13, concerning interaction through a network will apply to the
561 +combination as such.
562 +
563 +  14. Revised Versions of this License.
564 +
565 +  The Free Software Foundation may publish revised and/or new versions of
566 +the GNU General Public License from time to time.  Such new versions will
567 +be similar in spirit to the present version, but may differ in detail to
568 +address new problems or concerns.
569 +
570 +  Each version is given a distinguishing version number.  If the
571 +Program specifies that a certain numbered version of the GNU General
572 +Public License "or any later version" applies to it, you have the
573 +option of following the terms and conditions either of that numbered
574 +version or of any later version published by the Free Software
575 +Foundation.  If the Program does not specify a version number of the
576 +GNU General Public License, you may choose any version ever published
577 +by the Free Software Foundation.
578 +
579 +  If the Program specifies that a proxy can decide which future
580 +versions of the GNU General Public License can be used, that proxy's
581 +public statement of acceptance of a version permanently authorizes you
582 +to choose that version for the Program.
583 +
584 +  Later license versions may give you additional or different
585 +permissions.  However, no additional obligations are imposed on any
586 +author or copyright holder as a result of your choosing to follow a
587 +later version.
588 +
589 +  15. Disclaimer of Warranty.
590 +
591 +  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 +APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 +PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 +IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 +
600 +  16. Limitation of Liability.
601 +
602 +  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 +SUCH DAMAGES.
611 +
612 +  17. Interpretation of Sections 15 and 16.
613 +
614 +  If the disclaimer of warranty and limitation of liability provided
615 +above cannot be given local legal effect according to their terms,
616 +reviewing courts shall apply local law that most closely approximates
617 +an absolute waiver of all civil liability in connection with the
618 +Program, unless a warranty or assumption of liability accompanies a
619 +copy of the Program in return for a fee.
620 +
621 +                     END OF TERMS AND CONDITIONS
622 +
623 +            How to Apply These Terms to Your New Programs
624 +
625 +  If you develop a new program, and you want it to be of the greatest
626 +possible use to the public, the best way to achieve this is to make it
627 +free software which everyone can redistribute and change under these terms.
628 +
629 +  To do so, attach the following notices to the program.  It is safest
630 +to attach them to the start of each source file to most effectively
631 +state the exclusion of warranty; and each file should have at least
632 +the "copyright" line and a pointer to where the full notice is found.
633 +
634 +    <one line to give the program's name and a brief idea of what it does.>
635 +    Copyright (C) <year>  <name of author>
636 +
637 +    This program is free software: you can redistribute it and/or modify
638 +    it under the terms of the GNU General Public License as published by
639 +    the Free Software Foundation, either version 3 of the License, or
640 +    (at your option) any later version.
641 +
642 +    This program is distributed in the hope that it will be useful,
643 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
644 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645 +    GNU General Public License for more details.
646 +
647 +    You should have received a copy of the GNU General Public License
648 +    along with this program.  If not, see <https://www.gnu.org/licenses/>.
649 +
650 +Also add information on how to contact you by electronic and paper mail.
651 +
652 +  If the program does terminal interaction, make it output a short
653 +notice like this when it starts in an interactive mode:
654 +
655 +    <program>  Copyright (C) <year>  <name of author>
656 +    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 +    This is free software, and you are welcome to redistribute it
658 +    under certain conditions; type `show c' for details.
659 +
660 +The hypothetical commands `show w' and `show c' should show the appropriate
661 +parts of the General Public License.  Of course, your program's commands
662 +might be different; for a GUI interface, you would use an "about box".
663 +
664 +  You should also get your employer (if you work as a programmer) or school,
665 +if any, to sign a "copyright disclaimer" for the program, if necessary.
666 +For more information on this, and how to apply and follow the GNU GPL, see
667 +<https://www.gnu.org/licenses/>.
668 +
669 +  The GNU General Public License does not permit incorporating your program
670 +into proprietary programs.  If your program is a subroutine library, you
671 +may consider it more useful to permit linking proprietary applications with
672 +the library.  If this is what you want to do, use the GNU Lesser General
673 +Public License instead of this License.  But first, please read
674 +<https://www.gnu.org/licenses/why-not-lgpl.html>.
index.html
 1 +<!DOCTYPE html>
 2 +<html lang="en">
 3 +<head>
 4 +	<meta charset="utf-8">
 5 +	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
 6 +	<meta name="theme-color" content="#000000">
 7 +	<title>soundstone</title>
 8 +	<meta name="apple-mobile-web-app-capable" content="yes">
 9 +	<meta name="apple-mobile-web-app-status-bar-style" content="black">
10 +	<link rel="manifest" href="manifest.json">
11 +	<link rel="icon" href="resources/favicon.svg" type="image/svg+xml">
12 +	<link rel="apple-touch-icon" href="resources/icon.png">
13 +	<link rel="stylesheet" href="resources/style.css">
14 +</head>
15 +<body>
16 +	<main id="tapes"></main>
17 +	<footer>
18 +		<button id="record" aria-label="record"></button>
19 +	</footer>
20 +	<script src="resources/main.js"></script>
21 +</body>
22 +</html>
manifest.json
 1 +{
 2 +	"name": "soundstone",
 3 +	"short_name": "soundstone",
 4 +	"description": "A minimal multitrack tape recorder.",
 5 +	"start_url": "./",
 6 +	"scope": "./",
 7 +	"display": "standalone",
 8 +	"background_color": "#000000",
 9 +	"theme_color": "#000000",
10 +	"icons": [
11 +		{
12 +			"src": "resources/icon.png",
13 +			"sizes": "1024x1024",
14 +			"type": "image/png",
15 +			"purpose": "any maskable"
16 +		}
17 +	]
18 +}
readme.md
 1 +# soundstone
 2 +
 3 +### lay down a track.
 4 +
 5 +<p align="center"><img src="readme_images/record.gif" width="390"></p>
 6 +
 7 +### play it back.
 8 +
 9 +<p align="center"><img src="readme_images/play.gif" width="390"></p>
10 +
11 +### play it loud.
12 +
13 +<p align="center"><img src="readme_images/loud.gif" width="390"></p>
14 +
15 +### scrub a dub, bub.
16 +
17 +<p align="center"><img src="readme_images/scrub.gif" width="390"></p>
18 +
19 +### home recording.
20 +
21 +try soundstone <a href="https://hunterirving.github.io/soundstone">in your web browser</a>, or install it as a <a href="https://hunterirving.github.io/web_workshop/pages/pwa">progressive web app</a>.
readme_images/loud.gif
Binary files differ.
readme_images/play.gif
Binary files differ.
readme_images/record.gif
Binary files differ.
readme_images/scrub.gif
Binary files differ.
resources/deck.js
  1 +const BAR_SECONDS = 0.1;
  2 +const SPLICE_SECONDS = 0.005;
  3 +// Time constant of a held tape chasing the finger.
  4 +const FOLLOW_SECONDS = 0.05;
  5 +// Extra acceleration for the part of a speed gap beyond 1, so big gaps close fast.
  6 +const FAST_DECAY_SECONDS = 0.35;
  7 +// A release slower than this, as a fraction of normal speed, leaves the tape stopped.
  8 +const SLOWEST_THROW = 0.05;
  9 +// Volume smoothing, against clicks.
 10 +const VOLUME_SECONDS = 0.02;
 11 +const RENDERS_PER_REPORT = 3;
 12 +// A working microphone is never exactly zero for this long.
 13 +const SILENT_SECONDS = 0.5;
 14 +
 15 +const BAR_SAMPLES = Math.round(sampleRate * BAR_SECONDS);
 16 +const FAST_DECAY_RATE = 1 / (FAST_DECAY_SECONDS * sampleRate);
 17 +const FOLLOW_SAMPLES = FOLLOW_SECONDS * sampleRate;
 18 +const VOLUME_RATE = 1 / (VOLUME_SECONDS * sampleRate);
 19 +
 20 +class Deck extends AudioWorkletProcessor {
 21 +	constructor({processorOptions}) {
 22 +		super();
 23 +		this.spinUpRate = 1 / (processorOptions.spinUpSeconds * sampleRate);
 24 +		this.spinDownSamples = processorOptions.spinDownSeconds * sampleRate;
 25 +		this.tapes = [];
 26 +		this.recording = null;
 27 +		this.renders = 0;
 28 +		// Samples of exact zeros since the microphone opened; null when not checking.
 29 +		this.silence = null;
 30 +		this.microphoneGain = 1;
 31 +		this.playbackGain = 1;
 32 +		this.port.onmessage = ({data}) => {
 33 +			const tape = this.tapes[data.id];
 34 +			if (data.type === 'record') this.record();
 35 +			if (data.type === 'stop') this.stop();
 36 +			if (data.type === 'playbackGain') this.playbackGain = data.value;
 37 +			if (data.type === 'microphone') {
 38 +				this.silence = 0;
 39 +				this.microphoneGain = data.gain;
 40 +				this.playbackGain = data.playbackGain;
 41 +			}
 42 +			if (data.type === 'load') this.add(data.samples, data.volume);
 43 +			if (data.type === 'play') tape.target = 1;
 44 +			if (data.type === 'press' || data.type === 'brake') {
 45 +				// Stop time is fixed at any speed. A brake after a press keeps the press's rate.
 46 +				if (!tape.pressed) tape.stopRate = Math.abs(tape.speed) / this.spinDownSamples;
 47 +				tape.pressed = data.type === 'press';
 48 +				if (data.type === 'brake') tape.target = 0;
 49 +			}
 50 +			if (data.type === 'volume') tape.volume = data.value;
 51 +			if (data.type === 'grab') {
 52 +				tape.held = true;
 53 +				tape.pressed = false;
 54 +			}
 55 +			// Nulled, not spliced, so the other ids stay valid.
 56 +			if (data.type === 'delete') this.tapes[data.id] = null;
 57 +			if (data.type === 'drag') tape.pull += data.bars * BAR_SAMPLES;
 58 +			if (data.type === 'drop') tape.pressed = false;
 59 +			if (data.type === 'release') {
 60 +				// No decay: the tape coasts at its drag speed.
 61 +				tape.held = false;
 62 +				tape.pull = 0;
 63 +				if (Math.abs(tape.speed) < SLOWEST_THROW) tape.speed = 0;
 64 +				tape.target = tape.speed;
 65 +				this.port.postMessage({type: 'released', id: data.id, speed: tape.speed});
 66 +			}
 67 +		};
 68 +	}
 69 +
 70 +	record() {
 71 +		this.recording = {
 72 +			blocks: [],
 73 +			block: new Float32Array(sampleRate),
 74 +			fill: 0,
 75 +			peak: 0,
 76 +			peakFill: 0,
 77 +		};
 78 +	}
 79 +
 80 +	capture(input) {
 81 +		const rec = this.recording;
 82 +		const gain = this.microphoneGain;
 83 +		for (let i = 0; i < input.length; i++) {
 84 +			const sample = gain === 1 ? input[i] : Math.tanh(input[i] * gain);
 85 +			rec.block[rec.fill++] = sample;
 86 +			if (rec.fill === rec.block.length) {
 87 +				rec.blocks.push(rec.block);
 88 +				rec.block = new Float32Array(sampleRate);
 89 +				rec.fill = 0;
 90 +			}
 91 +			rec.peak = Math.max(rec.peak, Math.abs(sample));
 92 +			if (++rec.peakFill === BAR_SAMPLES) {
 93 +				this.port.postMessage({type: 'peak', value: rec.peak});
 94 +				rec.peak = 0;
 95 +				rec.peakFill = 0;
 96 +			}
 97 +		}
 98 +	}
 99 +
100 +	stop() {
101 +		const rec = this.recording;
102 +		if (!rec) return;
103 +		this.recording = null;
104 +
105 +		const length = rec.blocks.length * sampleRate + rec.fill;
106 +		const splice = Math.round(sampleRate * SPLICE_SECONDS);
107 +		if (length < splice * 2) {
108 +			this.port.postMessage({type: 'discard'});
109 +			return;
110 +		}
111 +		const samples = new Float32Array(length);
112 +		rec.blocks.forEach((block, i) => samples.set(block, i * sampleRate));
113 +		samples.set(rec.block.subarray(0, rec.fill), rec.blocks.length * sampleRate);
114 +
115 +		// Fade both ends so the loop point does not click.
116 +		for (let i = 0; i < splice; i++) {
117 +			samples[i] *= i / splice;
118 +			samples[length - 1 - i] *= i / splice;
119 +		}
120 +
121 +		// The last bar is shorter than the others unless the take ends on a bar boundary.
122 +		const peaks = new Float32Array(Math.ceil(length / BAR_SAMPLES));
123 +		for (let i = 0; i < length; i++) {
124 +			const bar = Math.floor(i / BAR_SAMPLES);
125 +			peaks[bar] = Math.max(peaks[bar], Math.abs(samples[i]));
126 +		}
127 +
128 +		this.add(samples, 1);
129 +		this.port.postMessage({type: 'tape', peaks, length: length / BAR_SAMPLES, samples});
130 +	}
131 +
132 +	add(samples, volume) {
133 +		this.tapes.push({
134 +			samples,
135 +			position: 0,
136 +			reported: 0,
137 +			// Samples per output sample; negative is backwards.
138 +			speed: 0,
139 +			// Speed a free tape eases towards.
140 +			target: 0,
141 +			held: false,
142 +			// A resting finger brakes the tape towards zero.
143 +			pressed: false,
144 +			// Speed lost per sample while stopping.
145 +			stopRate: 0,
146 +			// Samples a held tape still lags behind the finger.
147 +			pull: 0,
148 +			volume,
149 +			// Smoothed `volume`.
150 +			gain: volume,
151 +		});
152 +	}
153 +
154 +	process(inputs, outputs) {
155 +		const input = inputs[0][0];
156 +		const output = outputs[0][0];
157 +		if (this.recording && input) this.capture(input);
158 +		if (this.silence !== null && input) {
159 +			if (input.some(sample => sample !== 0)) {
160 +				this.silence = null;
161 +			} else if ((this.silence += input.length) >= SILENT_SECONDS * sampleRate) {
162 +				this.silence = null;
163 +				this.port.postMessage({type: 'silent'});
164 +			}
165 +		}
166 +
167 +		for (const tape of this.tapes) {
168 +			if (!tape) continue;
169 +			const goal = tape.pressed ? 0 : tape.target;
170 +			if (tape.speed === 0 && tape.pull === 0 && (tape.held || goal === 0)) {
171 +				tape.gain = tape.volume;
172 +				continue;
173 +			}
174 +			const {samples} = tape;
175 +			const length = samples.length;
176 +			for (let i = 0; i < output.length; i++) {
177 +				if (tape.held) {
178 +					tape.speed = tape.pull / FOLLOW_SAMPLES;
179 +					tape.pull -= tape.speed;
180 +				} else if (tape.speed !== goal) {
181 +					const gap = goal - tape.speed;
182 +					const distance = Math.abs(gap);
183 +					const change = goal
184 +						? this.spinUpRate + Math.max(0, distance - 1) * FAST_DECAY_RATE
185 +						: tape.stopRate;
186 +					tape.speed += Math.sign(gap) * Math.min(distance, change);
187 +				}
188 +				tape.gain += (tape.volume - tape.gain) * VOLUME_RATE;
189 +				const index = Math.floor(tape.position);
190 +				const fraction = tape.position - index;
191 +				const a = samples[index];
192 +				const b = samples[index + 1 === length ? 0 : index + 1];
193 +				// Level follows speed up to 1, like a real playback head.
194 +				output[i] += (a + (b - a) * fraction) * Math.min(1, Math.abs(tape.speed)) * tape.gain;
195 +				tape.position += tape.speed;
196 +				if (tape.position < 0 || tape.position >= length) {
197 +					tape.position = (tape.position % length + length) % length;
198 +					// Rounding can land a tiny negative position exactly on `length`.
199 +					if (tape.position >= length) tape.position = 0;
200 +				}
201 +			}
202 +			if (tape.held && Math.abs(tape.pull) < 1) {
203 +				tape.pull = 0;
204 +				tape.speed = 0;
205 +			}
206 +		}
207 +
208 +		// Soft-clip the raised mix, as in capture().
209 +		if (this.playbackGain !== 1) {
210 +			for (let i = 0; i < output.length; i++) {
211 +				output[i] = Math.tanh(output[i] * this.playbackGain);
212 +			}
213 +		}
214 +
215 +		const moved = tape => tape && tape.position !== tape.reported;
216 +		if (++this.renders % RENDERS_PER_REPORT === 0 && this.tapes.some(moved)) {
217 +			this.port.postMessage({
218 +				type: 'positions',
219 +				positions: this.tapes.map(tape => tape && (tape.reported = tape.position) / BAR_SAMPLES),
220 +			});
221 +		}
222 +		return true;
223 +	}
224 +}
225 +
226 +registerProcessor('deck', Deck);
resources/favicon.svg
1 +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1058 1058">
2 +	<ellipse cx="529" cy="529" rx="540.4" ry="413.7" transform="rotate(-41.18 529 529)" fill="#fff"/>
3 +</svg>
resources/icon.png
Binary files differ.
resources/main.js
  1 +// The head is the middle slot, above the record button.
  2 +const SLOTS = 51;
  3 +const HEAD = (SLOTS - 1) / 2;
  4 +const SPIN_UP_SECONDS = 0.4;
  5 +// Independent of the starting speed.
  6 +const SPIN_DOWN_SECONDS = 0.7;
  7 +// A finger resting on a playing tape brakes it after this. A volume drag that
  8 +// begins sooner leaves the tape alone.
  9 +const PRESS_DELAY_MILLISECONDS = 150;
 10 +// In CSS px.
 11 +const DRAG_THRESHOLD = 5;
 12 +const APPEAR_MILLISECONDS = 300;
 13 +const HOLD_TO_DELETE_MILLISECONDS = 2000;
 14 +const UPCOMING_OPACITY = 0.35;
 15 +const MAX_VOLUME = 2;
 16 +// Time constant of bar height changes.
 17 +const BAR_EASE_SECONDS = 0.035;
 18 +// Jog scroll speed grows with drag distance up to SCROLL_FULL_DRAG px, where it
 19 +// reaches SCROLL_TOP_SPEED px/s.
 20 +const SCROLL_FULL_DRAG = 100;
 21 +const SCROLL_TOP_SPEED = 1000;
 22 +// The iOS built-in microphone is super quiet with processing off, and while it is
 23 +// open the speaker plays quieter. These gains compensate.
 24 +const BUILT_IN_MICROPHONE_GAIN = 20;
 25 +const BUILT_IN_PLAYBACK_GAIN = 2;
 26 +
 27 +const tapesElement = document.querySelector('#tapes');
 28 +const recordButton = document.querySelector('#record');
 29 +
 30 +// A tape's index is its id on the audio thread. A deleted tape leaves a null behind.
 31 +const tapes = [];
 32 +let recording = null;
 33 +let audio = null;
 34 +let deck = null;
 35 +let setup = null;
 36 +let microphone = null;
 37 +let microphoneOpening = null;
 38 +// Decides whether the microphone is reopened when the page returns.
 39 +let microphoneUsed = false;
 40 +let microphoneRepaired = false;
 41 +
 42 +const database = new Promise((resolve, reject) => {
 43 +	const request = indexedDB.open('soundstone', 1);
 44 +	request.onupgradeneeded = () => {
 45 +		request.result.createObjectStore('tapes', {autoIncrement: true});
 46 +		request.result.createObjectStore('samples');
 47 +	};
 48 +	request.onsuccess = () => resolve(request.result);
 49 +	request.onerror = () => reject(request.error);
 50 +});
 51 +
 52 +const settled = request => new Promise((resolve, reject) => {
 53 +	request.onsuccess = () => resolve(request.result);
 54 +	request.onerror = () => reject(request.error);
 55 +});
 56 +
 57 +// Resolves to the storage key.
 58 +async function saveTape(tape, samples) {
 59 +	const transaction = (await database).transaction(['tapes', 'samples'], 'readwrite');
 60 +	const key = await settled(transaction.objectStore('tapes').add({
 61 +		peaks: tape.peaks,
 62 +		length: tape.length,
 63 +		volume: tape.volume,
 64 +		sampleRate: audio.sampleRate,
 65 +	}));
 66 +	transaction.objectStore('samples').put(samples, key);
 67 +	return key;
 68 +}
 69 +
 70 +async function saveVolume(tape) {
 71 +	const key = await tape.saved;
 72 +	const store = (await database).transaction('tapes', 'readwrite').objectStore('tapes');
 73 +	const record = await settled(store.get(key));
 74 +	record.volume = tape.volume;
 75 +	store.put(record, key);
 76 +}
 77 +
 78 +async function forgetTape(tape) {
 79 +	const key = await tape.saved;
 80 +	const transaction = (await database).transaction(['tapes', 'samples'], 'readwrite');
 81 +	transaction.objectStore('tapes').delete(key);
 82 +	transaction.objectStore('samples').delete(key);
 83 +}
 84 +
 85 +// The device rate can change between visits, eg with headphones. Converting keeps the pitch.
 86 +async function resample(samples, rate) {
 87 +	if (rate === audio.sampleRate) return samples;
 88 +	const length = Math.round(samples.length * audio.sampleRate / rate);
 89 +	const offline = new OfflineAudioContext(1, length, audio.sampleRate);
 90 +	const source = offline.createBufferSource();
 91 +	source.buffer = new AudioBuffer({length: samples.length, sampleRate: rate});
 92 +	source.buffer.copyToChannel(samples, 0);
 93 +	source.connect(offline.destination);
 94 +	source.start();
 95 +	return (await offline.startRendering()).getChannelData(0);
 96 +}
 97 +
 98 +async function loadTapes() {
 99 +	const transaction = (await database).transaction(['tapes', 'samples']);
100 +	const [keys, records, takes] = await Promise.all([
101 +		settled(transaction.objectStore('tapes').getAllKeys()),
102 +		settled(transaction.objectStore('tapes').getAll()),
103 +		settled(transaction.objectStore('samples').getAll()),
104 +	]);
105 +	for (const [i, {peaks, length, volume, sampleRate}] of records.entries()) {
106 +		const samples = await resample(takes[i], sampleRate);
107 +		deck.port.postMessage({type: 'load', samples, volume});
108 +		const tape = addTape({peaks, length, volume, saved: keys[i]});
109 +		makeGrabbable(tape, tapes.length);
110 +		tapes.push(tape);
111 +	}
112 +	tapesElement.scrollTop = tapesElement.scrollHeight;
113 +}
114 +
115 +// Runs on load. Audio stays suspended until the first touch, but saved tapes load meanwhile.
116 +async function setUpAudio() {
117 +	audio = new AudioContext();
118 +	await audio.audioWorklet.addModule('resources/deck.js');
119 +	deck = new AudioWorkletNode(audio, 'deck', {
120 +		outputChannelCount: [1],
121 +		processorOptions: {spinUpSeconds: SPIN_UP_SECONDS, spinDownSeconds: SPIN_DOWN_SECONDS},
122 +	});
123 +	deck.connect(audio.destination);
124 +	deck.port.onmessage = ({data}) => handlers[data.type](data);
125 +	setAudioSessionType('playback');
126 +	await loadTapes();
127 +}
128 +
129 +// Safari only. The type decides whether sound continues while the device is locked.
130 +function setAudioSessionType(type) {
131 +	if (navigator.audioSession) navigator.audioSession.type = type;
132 +}
133 +
134 +function openMicrophone() {
135 +	microphoneOpening ??= (async () => {
136 +		setAudioSessionType('play-and-record');
137 +		const stream = await navigator.mediaDevices.getUserMedia({
138 +			audio: {echoCancellation: false, noiseSuppression: false, autoGainControl: false},
139 +		});
140 +		const source = audio.createMediaStreamSource(stream);
141 +		source.connect(deck);
142 +		// iOS names the built-in microphone after the device, as in "iPhone Microphone".
143 +		const builtIn = /iPhone|iPad/.test(stream.getAudioTracks()[0].label);
144 +		deck.port.postMessage({
145 +			type: 'microphone',
146 +			gain: builtIn ? BUILT_IN_MICROPHONE_GAIN : 1,
147 +			playbackGain: builtIn ? BUILT_IN_PLAYBACK_GAIN : 1,
148 +		});
149 +		microphone = {stream, source};
150 +		microphoneUsed = true;
151 +	})().finally(() => microphoneOpening = null);
152 +	return microphoneOpening;
153 +}
154 +
155 +function closeMicrophone() {
156 +	microphone.source.disconnect();
157 +	for (const track of microphone.stream.getTracks()) track.stop();
158 +	microphone = null;
159 +	deck.port.postMessage({type: 'playbackGain', value: 1});
160 +}
161 +
162 +// iOS can get stuck delivering silence to an unprocessed microphone, across
163 +// launches. A hacky attempt at fixing this.
164 +async function repairMicrophone() {
165 +	if (!microphone || microphoneRepaired) return;
166 +	microphoneRepaired = true;
167 +	const stream = await navigator.mediaDevices.getUserMedia({audio: true});
168 +	for (const track of stream.getTracks()) track.stop();
169 +	if (!microphone) return;
170 +	closeMicrophone();
171 +	await openMicrophone();
172 +}
173 +
174 +// In Safari an open microphone stops audio at lock, so it is released while
175 +// hidden unless a take is in progress.
176 +document.addEventListener('visibilitychange', async () => {
177 +	if (!navigator.audioSession || !deck) return;
178 +	if (!document.hidden) {
179 +		audio.resume();
180 +		if (microphoneUsed && !microphone) await openMicrophone();
181 +	}
182 +	if (document.hidden && microphone && !recording) {
183 +		closeMicrophone();
184 +		setAudioSessionType('playback');
185 +	}
186 +});
187 +
188 +const handlers = {
189 +	peak({value}) {
190 +		recording.peaks.push(value);
191 +	},
192 +
193 +	tape({peaks, length, samples}) {
194 +		const tape = recording;
195 +		recording = null;
196 +		tape.peaks = peaks;
197 +		tape.length = length;
198 +		tape.saved = saveTape(tape, samples);
199 +		tape.recording = false;
200 +		tape.redraw = true;
201 +		makeGrabbable(tape, tapes.length);
202 +		tapes.push(tape);
203 +	},
204 +
205 +	silent() {
206 +		repairMicrophone();
207 +	},
208 +
209 +	discard() {
210 +		recording.row.remove();
211 +		recording = null;
212 +	},
213 +
214 +	released({id, speed}) {
215 +		if (tapes[id]) tapes[id].direction = Math.sign(speed);
216 +	},
217 +
218 +	positions({positions}) {
219 +		positions.forEach((position, id) => {
220 +			if (tapes[id]) tapes[id].position = position;
221 +		});
222 +	},
223 +};
224 +
225 +function addTape(fields) {
226 +	const row = document.createElement('div');
227 +	row.className = 'tape';
228 +	const canvas = row.appendChild(document.createElement('canvas'));
229 +	tapesElement.append(row);
230 +	const tape = {
231 +		row,
232 +		canvas,
233 +		peaks: [],
234 +		// In bars; not always whole.
235 +		length: 0,
236 +		// Head position, in bars.
237 +		position: 0,
238 +		recording: false,
239 +		// 1, -1, or 0 when stopped.
240 +		direction: 0,
241 +		volume: 1,
242 +		// Drawn bar lengths in canvas px, trailing their targets.
243 +		lengths: null,
244 +		// Dimming left and right of the head, 0 to 1.
245 +		dim: [0, 0],
246 +		redraw: true,
247 +		// Storage key, or a promise of it while saving.
248 +		saved: null,
249 +		...fields,
250 +	};
251 +	fit(tape);
252 +	return tape;
253 +}
254 +
255 +async function toggleRecording() {
256 +	if (recording) {
257 +		deck.port.postMessage({type: 'stop'});
258 +		recordButton.classList.remove('recording');
259 +		return;
260 +	}
261 +	// Only a press may start audio, and it stops counting once the microphone
262 +	// prompt is answered, so resume before awaiting.
263 +	audio.resume();
264 +	await setup;
265 +	if (!microphone) await openMicrophone();
266 +	if (recording) return;
267 +	audio.resume();
268 +
269 +	recording = addTape({recording: true});
270 +	const {row} = recording;
271 +	deck.port.postMessage({type: 'record'});
272 +	recordButton.classList.add('recording');
273 +
274 +	row.animate(
275 +		[{height: 0, opacity: 0}, {}],
276 +		{duration: APPEAR_MILLISECONDS, easing: 'ease-out'},
277 +	);
278 +	const scrollStart = tapesElement.scrollTop;
279 +	const began = performance.now();
280 +	const follow = now => {
281 +		const progress = Math.min(1, Math.max(0, (now - began) / APPEAR_MILLISECONDS));
282 +		const bottom = tapesElement.scrollHeight - tapesElement.clientHeight;
283 +		tapesElement.scrollTop = scrollStart + (bottom - scrollStart) * (1 - (1 - progress) ** 3);
284 +		if (progress < 1) requestAnimationFrame(follow);
285 +	};
286 +	requestAnimationFrame(follow);
287 +}
288 +
289 +// pointerdown, because a second finger on the screen produces no click.
290 +// The click listener serves the keyboard (detail 0).
291 +recordButton.addEventListener('pointerdown', toggleRecording);
292 +recordButton.addEventListener('click', event => {
293 +	if (event.detail === 0) toggleRecording();
294 +});
295 +
296 +function makeGrabbable(tape, id) {
297 +	const {row} = tape;
298 +	const send = (type, fields) => deck.port.postMessage({type, id, ...fields});
299 +	let start = null;
300 +	let lastX = 0;
301 +	let mode = null;
302 +	let wasPlaying = false;
303 +	// This pointer has started braking the tape.
304 +	let pressed = false;
305 +	let pressTimer = null;
306 +	let holdTimer = null;
307 +	// One pointer per tape, so several tapes can be touched at once.
308 +	let pointerId = null;
309 +	row.classList.add('finished');
310 +
311 +	const remove = () => {
312 +		start = null;
313 +		send('delete');
314 +		forgetTape(tape);
315 +		tapes[id] = null;
316 +		row.classList.remove('finished');
317 +		row.animate(
318 +			[{}, {height: 0, opacity: 0}],
319 +			{duration: APPEAR_MILLISECONDS, easing: 'ease-out'},
320 +		).finished.then(() => row.remove());
321 +	};
322 +
323 +	row.addEventListener('pointerdown', event => {
324 +		if (pointerId !== null) return;
325 +		if (event.shiftKey) {
326 +			remove();
327 +			return;
328 +		}
329 +		audio.resume();
330 +		pointerId = event.pointerId;
331 +		row.setPointerCapture(pointerId);
332 +		start = {x: event.clientX, y: event.clientY, volume: tape.volume};
333 +		lastX = event.clientX;
334 +		mode = null;
335 +		wasPlaying = tape.direction !== 0;
336 +		pressed = false;
337 +		if (wasPlaying) {
338 +			pressTimer = setTimeout(() => {
339 +				pressed = true;
340 +				send('press');
341 +			}, PRESS_DELAY_MILLISECONDS);
342 +		}
343 +		holdTimer = setTimeout(remove, HOLD_TO_DELETE_MILLISECONDS);
344 +	});
345 +
346 +	row.addEventListener('pointermove', event => {
347 +		if (event.pointerId !== pointerId || !start) return;
348 +		if (!mode) {
349 +			const acrossTravel = Math.abs(event.clientX - start.x);
350 +			const upTravel = Math.abs(event.clientY - start.y);
351 +			if (Math.max(acrossTravel, upTravel) < DRAG_THRESHOLD) return;
352 +			if (acrossTravel < upTravel && pressed) return;
353 +			mode = acrossTravel >= upTravel ? 'scrub' : 'volume';
354 +			clearTimeout(pressTimer);
355 +			clearTimeout(holdTimer);
356 +			row.classList.add('grabbed');
357 +			if (mode === 'scrub') send('grab');
358 +			pressed = false;
359 +		}
360 +		if (mode === 'scrub') {
361 +			// Dragging left pulls later tape under the head, which is forwards.
362 +			const pitch = tape.canvas.clientWidth / SLOTS;
363 +			send('drag', {bars: (lastX - event.clientX) / pitch});
364 +			lastX = event.clientX;
365 +		} else {
366 +			const change = (start.y - event.clientY) / row.clientHeight;
367 +			tape.volume = Math.min(MAX_VOLUME, Math.max(0, start.volume + change));
368 +			send('volume', {value: tape.volume});
369 +		}
370 +	});
371 +
372 +	const end = event => {
373 +		if (event.pointerId !== pointerId) return;
374 +		pointerId = null;
375 +		clearTimeout(pressTimer);
376 +		clearTimeout(holdTimer);
377 +		if (!start) return;
378 +		start = null;
379 +		row.classList.remove('grabbed');
380 +		if (mode === 'volume') saveVolume(tape);
381 +		if (mode === 'scrub') {
382 +			send('release');
383 +		} else if (!mode && event.type === 'pointerup') {
384 +			send(wasPlaying ? 'brake' : 'play');
385 +			tape.direction = wasPlaying ? 0 : 1;
386 +		} else if (pressed) {
387 +			send('drop');
388 +		}
389 +		pressed = false;
390 +	};
391 +	row.addEventListener('pointerup', end);
392 +	row.addEventListener('pointercancel', end);
393 +}
394 +
395 +// Jog control: while held, scroll speed follows the offset from the press point.
396 +const footer = document.querySelector('footer');
397 +let scrollDrag = null;
398 +
399 +footer.addEventListener('pointerdown', event => {
400 +	if (scrollDrag || event.target === recordButton) return;
401 +	footer.setPointerCapture(event.pointerId);
402 +	scrollDrag = {pointerId: event.pointerId, startY: event.clientY, y: event.clientY};
403 +	let last = performance.now();
404 +	const step = now => {
405 +		if (!scrollDrag) return;
406 +		const pull = Math.min(1, Math.max(-1, (scrollDrag.y - scrollDrag.startY) / SCROLL_FULL_DRAG));
407 +		tapesElement.scrollTop += pull * SCROLL_TOP_SPEED * Math.max(0, now - last) / 1000;
408 +		last = now;
409 +		requestAnimationFrame(step);
410 +	};
411 +	requestAnimationFrame(step);
412 +});
413 +
414 +footer.addEventListener('pointermove', event => {
415 +	if (scrollDrag?.pointerId === event.pointerId) scrollDrag.y = event.clientY;
416 +});
417 +
418 +const endScrollDrag = event => {
419 +	if (scrollDrag?.pointerId === event.pointerId) scrollDrag = null;
420 +};
421 +footer.addEventListener('pointerup', endScrollDrag);
422 +footer.addEventListener('pointercancel', endScrollDrag);
423 +
424 +function fit(tape) {
425 +	const {width, height} = tape.canvas.getBoundingClientRect();
426 +	tape.canvas.width = Math.round(width * devicePixelRatio);
427 +	tape.canvas.height = Math.round(height * devicePixelRatio);
428 +	tape.lengths = null;
429 +}
430 +
431 +addEventListener('resize', () => {
432 +	tapes.filter(Boolean).forEach(fit);
433 +	if (recording) fit(recording);
434 +});
435 +
436 +// Null where there is no tape.
437 +function peakAt(tape, slot) {
438 +	const offset = slot - HEAD;
439 +	const {peaks, length} = tape;
440 +	if (tape.recording) {
441 +		const index = peaks.length + offset;
442 +		return offset < 0 && index >= 0 ? peaks[index] : null;
443 +	}
444 +	// Blend the two bars a slot lies between, so motion is smooth across the loop point.
445 +	const bar = ((tape.position + offset) % length + length) % length;
446 +	const index = Math.min(Math.floor(bar), peaks.length - 1);
447 +	const next = (index + 1) % peaks.length;
448 +	// The last bar of a tape can be shorter than the others.
449 +	const span = Math.min(1, length - index);
450 +	return peaks[index] + (peaks[next] - peaks[index]) * (bar - index) / span;
451 +}
452 +
453 +// Eases bars and dimming towards their targets; redraws only on change.
454 +function animate(tape, seconds) {
455 +	const {canvas} = tape;
456 +	const {width, height} = canvas;
457 +	const pitch = width / SLOTS;
458 +	const thickness = pitch * 0.42;
459 +	const shortest = thickness * 2.5;
460 +	let changed = tape.redraw;
461 +	tape.redraw = false;
462 +
463 +	const snap = !tape.lengths;
464 +	tape.lengths ??= new Float32Array(SLOTS);
465 +	const ease = snap ? 1 : 1 - Math.exp(-seconds / BAR_EASE_SECONDS);
466 +	const recorded = [];
467 +	for (let slot = 0; slot < SLOTS; slot++) {
468 +		const peak = peakAt(tape, slot);
469 +		recorded[slot] = peak !== null;
470 +		const wanted = peak === null
471 +			? thickness
472 +			: shortest + (height * 0.85 - shortest) * Math.min(1, peak * tape.volume) ** 0.6;
473 +		const gap = wanted - tape.lengths[slot];
474 +		if (Math.abs(gap) < 0.1) continue;
475 +		tape.lengths[slot] += gap * ease;
476 +		changed = true;
477 +	}
478 +
479 +	// Dim the side about to play, over the spin-down time.
480 +	const wantedDim = [tape.direction < 0 ? 1 : 0, tape.direction > 0 ? 1 : 0];
481 +	for (const side of [0, 1]) {
482 +		const gap = wantedDim[side] - tape.dim[side];
483 +		if (gap === 0) continue;
484 +		tape.dim[side] += Math.sign(gap) * Math.min(Math.abs(gap), seconds / SPIN_DOWN_SECONDS);
485 +		changed = true;
486 +	}
487 +
488 +	if (!changed) return;
489 +	const context = canvas.getContext('2d');
490 +	context.clearRect(0, 0, width, height);
491 +	context.lineCap = 'round';
492 +	context.lineWidth = thickness;
493 +	for (let slot = 0; slot < SLOTS; slot++) {
494 +		const reach = Math.max(tape.lengths[slot] - thickness, 0.01) / 2;
495 +		const x = (slot + 0.5) * pitch;
496 +		const dim = slot === HEAD ? 0 : tape.dim[slot < HEAD ? 0 : 1];
497 +		context.globalAlpha = 1 - dim * (1 - UPCOMING_OPACITY);
498 +		context.strokeStyle = tape.recording && recorded[slot] ? '#f00' : '#fff';
499 +		context.beginPath();
500 +		context.moveTo(x, height / 2 - reach);
501 +		context.lineTo(x, height / 2 + reach);
502 +		context.stroke();
503 +	}
504 +}
505 +
506 +let lastFrame = performance.now();
507 +function frame(now) {
508 +	const seconds = (now - lastFrame) / 1000;
509 +	lastFrame = now;
510 +	for (const tape of tapes) {
511 +		if (tape) animate(tape, seconds);
512 +	}
513 +	if (recording) animate(recording, seconds);
514 +	requestAnimationFrame(frame);
515 +}
516 +requestAnimationFrame(frame);
517 +
518 +if (navigator.mediaSession) {
519 +	navigator.mediaSession.metadata = new MediaMetadata({
520 +		title: 'new soundscape',
521 +		artist: 'soundstone',
522 +		artwork: [{src: 'resources/icon.png', sizes: '1024x1024', type: 'image/png'}],
523 +	});
524 +}
525 +
526 +setup = setUpAudio();
527 +
528 +// Skipped on localhost so edits show on the first reload.
529 +if ('serviceWorker' in navigator && !['localhost', '127.0.0.1'].includes(location.hostname)) {
530 +	navigator.serviceWorker.register('service-worker.js');
531 +}
resources/style.css
 1 +html {
 2 +	background: #000;
 3 +	touch-action: manipulation;
 4 +}
 5 +
 6 +body {
 7 +	--footer-space: calc((22.5dvh - 72px) / 2);
 8 +	display: flex;
 9 +	flex-direction: column;
10 +	height: 100dvh;
11 +	max-width: 520px;
12 +	margin: 0 auto;
13 +	overflow: hidden;
14 +	touch-action: manipulation;
15 +	-webkit-user-select: none;
16 +	user-select: none;
17 +	-webkit-tap-highlight-color: transparent;
18 +}
19 +
20 +#tapes {
21 +	flex: 1;
22 +	display: flex;
23 +	flex-direction: column;
24 +	overflow-y: auto;
25 +	scrollbar-width: none;
26 +}
27 +
28 +.tape {
29 +	flex: none;
30 +	height: 15.5dvh;
31 +	overflow: hidden;
32 +	touch-action: none;
33 +}
34 +
35 +.tape:first-child {
36 +	margin-top: auto;
37 +}
38 +
39 +.tape.finished {
40 +	cursor: grab;
41 +}
42 +
43 +.tape.grabbed {
44 +	cursor: grabbing;
45 +}
46 +
47 +.tape canvas {
48 +	display: block;
49 +	width: 92%;
50 +	height: 15.5dvh;
51 +	margin-inline: auto;
52 +}
53 +
54 +footer {
55 +	flex: none;
56 +	position: relative;
57 +	display: grid;
58 +	place-items: center;
59 +	padding: calc(var(--footer-space) / 2) 0 var(--footer-space);
60 +	touch-action: none;
61 +}
62 +
63 +footer::before {
64 +	content: '';
65 +	position: absolute;
66 +	inset: auto 0 100%;
67 +	height: 28px;
68 +	background: linear-gradient(to top, #000, rgb(0 0 0 / 0.6) 30%, transparent);
69 +	pointer-events: none;
70 +}
71 +
72 +#record {
73 +	width: 72px;
74 +	height: 72px;
75 +	padding: 0;
76 +	border: 0;
77 +	background: none;
78 +	cursor: pointer;
79 +}
80 +
81 +#record::before {
82 +	content: '';
83 +	display: block;
84 +	height: 100%;
85 +	border-radius: 50%;
86 +	background: #f00;
87 +	transition: transform 0.1s ease-out, border-radius 0.1s ease-out;
88 +}
89 +
90 +#record.recording::before {
91 +	transform: scale(0.905);
92 +	border-radius: 22%;
93 +}
serve.py
  1 +#!/usr/bin/env python3
  2 +"""
  3 +Serve soundstone over HTTPS so that devices on your local network can install
  4 +it as a PWA without a public web host.
  5 +
  6 +This script uses mkcert to make a certificate for this computer's address on
  7 +the local network. A device does not trust that certificate until it trusts
  8 +mkcert's root certificate authority (CA), so this script prints two QR codes:
  9 +
 10 +	1. an HTTP link that gives the device the mkcert root CA certificate.
 11 +	   This is the public certificate, not the private key.
 12 +	2. an HTTPS link to soundstone itself.
 13 +
 14 +Both servers stop together on Ctrl+C.
 15 +
 16 +Without mkcert or a network connection, it serves plain HTTP on this computer
 17 +only. That is enough to use soundstone here, but not to install it elsewhere.
 18 +
 19 +After scanning the first QR code, install and trust the CA on the device:
 20 +	iOS:     Settings → General → VPN & Device Management → install the profile,
 21 +	         then Settings → General → About → Certificate Trust Settings →
 22 +	         enable full trust
 23 +	Android: open the downloaded file and follow the prompt to install it as a
 24 +	         CA certificate
 25 +"""
 26 +
 27 +import http.server
 28 +import socket
 29 +import socketserver
 30 +import ssl
 31 +import subprocess
 32 +import sys
 33 +import threading
 34 +from pathlib import Path
 35 +from shutil import which
 36 +
 37 +HTTP_PORT = 8000       # preferred; falls back to the next free port
 38 +CERT_HTTP_PORT = 8001  # preferred; falls back to the next free port
 39 +HTTPS_PORT = 8443      # preferred; falls back to the next free port
 40 +SCRIPT_DIR = Path(__file__).parent.absolute()
 41 +DATA_DIR = Path.home() / ".soundstone"
 42 +VENV_DIR = DATA_DIR / "venv"
 43 +CERT_FILE = DATA_DIR / "https_certs" / "cert.pem"
 44 +KEY_FILE = DATA_DIR / "https_certs" / "key.pem"
 45 +
 46 +# The HTTPS server mounts the app here, so that it does not share an install
 47 +# with another app served from the same address and port.
 48 +BASE_PATH = "/soundstone/"
 49 +
 50 +# Path the device fetches the root CA from. Anything else over HTTP is a 404.
 51 +CA_DOWNLOAD_PATH = "/rootCA.pem"
 52 +
 53 +
 54 +def run_in_venv():
 55 +	"""Re-run this script in a private venv that has the qrcode package.
 56 +	If the venv or the package cannot be set up, the script still runs and
 57 +	prints URLs without QR codes."""
 58 +	python_path = VENV_DIR / ("Scripts" if sys.platform == "win32" else "bin") / "python"
 59 +	if not python_path.exists():
 60 +		print("Creating a Python environment for QR codes...")
 61 +		subprocess.call([sys.executable, "-m", "venv", str(VENV_DIR)])
 62 +	if python_path.exists():
 63 +		has_qrcode = subprocess.run([str(python_path), "-c", "import qrcode"], capture_output=True)
 64 +		if has_qrcode.returncode != 0:
 65 +			subprocess.call([str(python_path), "-m", "pip", "install", "-q", "qrcode"])
 66 +	else:
 67 +		python_path = Path(sys.executable)
 68 +	try:
 69 +		subprocess.check_call([str(python_path), __file__, "--in-venv"])
 70 +	except (KeyboardInterrupt, subprocess.CalledProcessError):
 71 +		pass
 72 +	sys.exit(0)
 73 +
 74 +
 75 +def get_local_ip():
 76 +	"""Return the address other devices on the network can reach this
 77 +	computer at, or None if there is no network."""
 78 +	try:
 79 +		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 80 +		# Asks which local address would route to a reserved documentation
 81 +		# address (RFC 5737).
 82 +		s.connect(("192.0.2.1", 80))
 83 +		local_ip = s.getsockname()[0]
 84 +		s.close()
 85 +		return local_ip
 86 +	except OSError:
 87 +		return None
 88 +
 89 +
 90 +def find_available_port(start_port, max_attempts=20):
 91 +	"""Return the first port at or after start_port that can be bound.
 92 +	SO_REUSEADDR stops a socket left in TIME_WAIT by an earlier run from
 93 +	blocking the port."""
 94 +	for port in range(start_port, start_port + max_attempts):
 95 +		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 96 +		s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 97 +		try:
 98 +			s.bind(("", port))
 99 +			return port
100 +		except OSError:
101 +			continue
102 +		finally:
103 +			s.close()
104 +	sys.exit(f"Error: no free port near {start_port}.")
105 +
106 +
107 +def print_qr_code(url, caption):
108 +	"""Print a QR code made of block characters, two rows of the code per line."""
109 +	try:
110 +		import qrcode
111 +	except ImportError:
112 +		print(f"\n{caption}\n  (QR code unavailable; open this URL by hand)")
113 +		return
114 +	qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=1, border=1)
115 +	qr.add_data(url)
116 +	qr.make(fit=True)
117 +	matrix = qr.get_matrix()
118 +
119 +	print(f"\n{caption}\n")
120 +	for y in range(0, len(matrix), 2):
121 +		line = " "
122 +		for x in range(len(matrix[y])):
123 +			top = matrix[y][x]
124 +			bottom = matrix[y + 1][x] if y + 1 < len(matrix) else False
125 +			line += "█" if top and bottom else "▀" if top else "▄" if bottom else " "
126 +		print(line)
127 +
128 +
129 +def ca_root_file():
130 +	"""Path to mkcert's root CA certificate."""
131 +	caroot = subprocess.run(["mkcert", "-CAROOT"], capture_output=True, text=True).stdout.strip()
132 +	return Path(caroot) / "rootCA.pem"
133 +
134 +
135 +def ensure_ca_installed():
136 +	"""Make sure mkcert's local CA exists and this computer trusts it.
137 +	mkcert may ask for your password to write to the system trust store."""
138 +	if not ca_root_file().exists():
139 +		print("Setting up the mkcert local CA (you may be asked for your password)...")
140 +		subprocess.check_call(["mkcert", "-install"])
141 +
142 +
143 +def ensure_leaf_cert(local_ip):
144 +	"""Make a certificate and key for this computer's network address and for
145 +	localhost, unless there is already one for the same address."""
146 +	CERT_FILE.parent.mkdir(parents=True, exist_ok=True)
147 +	if CERT_FILE.exists() and KEY_FILE.exists():
148 +		try:
149 +			names = ssl._ssl._test_decode_cert(str(CERT_FILE)).get("subjectAltName", ())
150 +		except (AttributeError, OSError):
151 +			names = ()
152 +		if ("IP Address", local_ip) in names:
153 +			return
154 +	print(f"Making a certificate for {local_ip}...")
155 +	subprocess.check_call([
156 +		"mkcert",
157 +		"-cert-file", str(CERT_FILE),
158 +		"-key-file", str(KEY_FILE),
159 +		local_ip, "localhost", "127.0.0.1",
160 +	])
161 +
162 +
163 +def start_ca_server(local_ip):
164 +	"""Start a plain HTTP server that hands out the mkcert root CA certificate,
165 +	and return it running. The certificate is public, so it is served to any
166 +	device for as long as the script runs. The caller shuts the server down."""
167 +	ca_bytes = ca_root_file().read_bytes()
168 +
169 +	class CAHandler(http.server.BaseHTTPRequestHandler):
170 +		def log_message(self, *args):
171 +			pass
172 +
173 +		def do_GET(self):
174 +			if self.path in ("/", "/index.html"):
175 +				self.send_response(302)
176 +				self.send_header("Location", CA_DOWNLOAD_PATH)
177 +				self.end_headers()
178 +				return
179 +			if self.path != CA_DOWNLOAD_PATH:
180 +				self.send_error(404)
181 +				return
182 +			# This content type makes iOS offer to install the file as a CA profile.
183 +			self.send_response(200)
184 +			self.send_header("Content-Type", "application/x-x509-ca-cert")
185 +			self.send_header("Content-Length", str(len(ca_bytes)))
186 +			self.send_header("Content-Disposition", 'attachment; filename="rootCA.pem"')
187 +			self.end_headers()
188 +			try:
189 +				self.wfile.write(ca_bytes)
190 +			except (BrokenPipeError, ConnectionResetError):
191 +				return
192 +
193 +	port = find_available_port(CERT_HTTP_PORT)
194 +	http.server.HTTPServer.allow_reuse_address = True
195 +	httpd = http.server.HTTPServer(("", port), CAHandler)
196 +	threading.Thread(target=httpd.serve_forever, daemon=True).start()
197 +
198 +	cert_url = f"http://{local_ip}:{port}{CA_DOWNLOAD_PATH}"
199 +	print("=" * 69)
200 +	print("STEP 1: install + trust the local CA on each device (first time only)")
201 +	print("=" * 69)
202 +	print_qr_code(cert_url, "Scan to download the root certificate:")
203 +	print(f"  {cert_url}")
204 +	print("\nOn iOS, after downloading:")
205 +	print("  • Settings → General → VPN & Device Management → install the profile")
206 +	print("  • Settings → General → About → Certificate Trust Settings →")
207 +	print("    toggle ON full trust for the mkcert CA")
208 +	print("\nOn Android, after downloading:")
209 +	print("  • open the downloaded file, or Settings → Security → Encryption &")
210 +	print("    credentials → Install a certificate → CA certificate, then confirm")
211 +	print("\n(skip this step on a device that already trusts the CA from an earlier run)")
212 +	return httpd
213 +
214 +
215 +class ThreadingServer(socketserver.ThreadingTCPServer):
216 +	daemon_threads = True
217 +	allow_reuse_address = True
218 +
219 +
220 +class TLSThreadingServer(ThreadingServer):
221 +	"""Threading server that does the TLS handshake in the worker thread, so
222 +	that one slow or abandoned handshake does not block other connections."""
223 +
224 +	def __init__(self, server_address, handler_cls, ssl_context):
225 +		self.ssl_context = ssl_context
226 +		super().__init__(server_address, handler_cls)
227 +
228 +	def process_request_thread(self, request, client_address):
229 +		try:
230 +			request.settimeout(20)
231 +			request = self.ssl_context.wrap_socket(request, server_side=True)
232 +			request.settimeout(None)
233 +		except (ssl.SSLError, OSError):
234 +			# A device that does not trust the CA, a probe, or a client that left.
235 +			self.shutdown_request(request)
236 +			return
237 +		super().process_request_thread(request, client_address)
238 +
239 +
240 +def make_handler(base_path):
241 +	"""Return a handler that serves SCRIPT_DIR mounted under base_path."""
242 +	class Handler(http.server.SimpleHTTPRequestHandler):
243 +		def __init__(self, *args, **kwargs):
244 +			super().__init__(*args, directory=str(SCRIPT_DIR), **kwargs)
245 +
246 +		def end_headers(self):
247 +			# Makes browsers check for a newer file on every load.
248 +			self.send_header("Cache-Control", "no-cache")
249 +			super().end_headers()
250 +
251 +		def log_message(self, *args):
252 +			pass
253 +
254 +		def handle(self):
255 +			try:
256 +				super().handle()
257 +			except (BrokenPipeError, ConnectionResetError, ssl.SSLError):
258 +				pass
259 +
260 +		def translate_path(self, path):
261 +			if base_path != "/" and path.startswith(base_path):
262 +				path = "/" + path[len(base_path):]
263 +			return super().translate_path(path)
264 +
265 +		def do_GET(self):
266 +			# Sends a visit to the bare address into the app.
267 +			if base_path != "/" and self.path in ("/", "/index.html"):
268 +				self.send_response(302)
269 +				self.send_header("Location", base_path)
270 +				self.send_header("Content-Length", "0")
271 +				self.end_headers()
272 +				return
273 +			return super().do_GET()
274 +
275 +	return Handler
276 +
277 +
278 +def serve_http():
279 +	"""Serve over plain HTTP to this computer only. Runs until Ctrl+C."""
280 +	port = find_available_port(HTTP_PORT)
281 +	with ThreadingServer(("127.0.0.1", port), make_handler("/")) as httpd:
282 +		print(f"\nServing over plain HTTP at http://localhost:{port}")
283 +		print("Other devices can't install soundstone from here, because that needs HTTPS.")
284 +		print("\nPress Ctrl+C to stop the server")
285 +		try:
286 +			httpd.serve_forever()
287 +		except KeyboardInterrupt:
288 +			print("\n\nShutting down...")
289 +
290 +
291 +def serve_https(local_ip, ca_httpd):
292 +	"""Serve over HTTPS under BASE_PATH. Runs until Ctrl+C, then also shuts
293 +	down the CA server."""
294 +	ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
295 +	ctx.load_cert_chain(certfile=str(CERT_FILE), keyfile=str(KEY_FILE))
296 +	port = find_available_port(HTTPS_PORT)
297 +
298 +	with TLSThreadingServer(("", port), make_handler(BASE_PATH), ctx) as httpd:
299 +		https_url = f"https://{local_ip}:{port}{BASE_PATH}"
300 +		print("\n" + "=" * 60)
301 +		print("STEP 2: install soundstone (once the device trusts the CA)")
302 +		print("=" * 60)
303 +		print_qr_code(https_url, "Scan to open soundstone over HTTPS:")
304 +		print(f"  {https_url}")
305 +		print("\nThen install it: Share → Add to Home Screen on iOS, or the")
306 +		print("browser menu → Install app on Android.")
307 +		print(f"\nOn this computer, open https://localhost:{port}{BASE_PATH}")
308 +		print("\nPress Ctrl+C to stop the servers")
309 +		try:
310 +			httpd.serve_forever()
311 +		except KeyboardInterrupt:
312 +			print("\n\nShutting down...")
313 +		finally:
314 +			ca_httpd.shutdown()
315 +			ca_httpd.server_close()
316 +
317 +
318 +def start():
319 +	local_ip = get_local_ip()
320 +	if not local_ip:
321 +		print("Couldn't find this computer's address on a local network.")
322 +		serve_http()
323 +		return
324 +	if which("mkcert") is None:
325 +		print("mkcert isn't installed, so HTTPS isn't available.")
326 +		print("Install it from https://github.com/FiloSottile/mkcert and run serve.py again.")
327 +		serve_http()
328 +		return
329 +
330 +	ensure_ca_installed()
331 +	ensure_leaf_cert(local_ip)
332 +	serve_https(local_ip, start_ca_server(local_ip))
333 +
334 +
335 +if __name__ == "__main__":
336 +	if "--in-venv" in sys.argv:
337 +		start()
338 +	else:
339 +		run_in_venv()
service-worker.js
 1 +// Keeps an installed copy of soundstone working when the server it came from
 2 +// cannot be reached, which is the usual case for an install from a local network.
 3 +
 4 +const CACHE_NAME = 'soundstone';
 5 +const FILES = ['./', 'resources/style.css', 'resources/main.js', 'resources/deck.js', 'manifest.json', 'resources/favicon.svg', 'resources/icon.png'];
 6 +
 7 +self.addEventListener('install', event => {
 8 +	self.skipWaiting();
 9 +	event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(FILES)));
10 +});
11 +
12 +self.addEventListener('activate', event => {
13 +	event.waitUntil(self.clients.claim());
14 +});
15 +
16 +// Answers from the cache immediately, and refreshes the cache from the network in
17 +// the background. A change on the server therefore shows up on the second launch.
18 +self.addEventListener('fetch', event => {
19 +	if (event.request.method !== 'GET') return;
20 +	event.respondWith(caches.open(CACHE_NAME).then(async cache => {
21 +		const cached = await cache.match(event.request);
22 +		const fresh = fetch(event.request).then(response => {
23 +			if (response.ok) cache.put(event.request, response.clone());
24 +			return response;
25 +		});
26 +		if (!cached) return fresh;
27 +		event.waitUntil(fresh.catch(() => {}));
28 +		return cached;
29 +	}));
30 +});