├── .gitignore
├── LICENSE.txt
├── README.md
├── docs
├── changelog.md
├── index.md
├── tzxcat.md
├── tzxcleanup.md
├── tzxcut.md
├── tzxls.md
├── tzxmerge.md
├── tzxplay.md
├── tzxsplit.md
├── tzxtap.md
└── tzxwav.md
├── mkdocs.yml
├── setup.py
├── tzxlib
├── __init__.py
├── convert.py
├── loader.py
├── saver.py
├── tapfile.py
├── tzxblocks.py
├── tzxfile.py
└── z80dis.py
└── tzxtools
├── __init__.py
├── tzxcat.py
├── tzxcleanup.py
├── tzxcut.py
├── tzxls.py
├── tzxmerge.py
├── tzxplay.py
├── tzxsplit.py
├── tzxtap.py
└── tzxwav.py
/.gitignore:
--------------------------------------------------------------------------------
1 | /dist/
2 | /site/
3 | /*.egg
4 | /*.egg-info
5 | *.py[cod]
6 | *.tzx
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # tzxtools
2 |
3 | This is a collection of command line tools for processing TZX files.
4 |
5 | TZX is a common file format for preserving computer tapes of the ZX Spectrum, but also Amstrad CPC, C64 and MSX. `tzxtools` mainly supports ZX Spectrum TZX files, but raw file operations can be applied on any TZX file. It also supports TSX files, which are mainly used for MSX.
6 |
7 | ## Features
8 |
9 | * Convert your old ZX Spectrum tape recordings into TZX files.
10 | * List, split, merge, and divide the blocks inside TZX files.
11 | * Play back TZX files and load them into the real hardware.
12 | * Extract binary content from TZX blocks.
13 | * Read hex dumps, disassembled Z80 machine code, or ZX Spectrum BASIC code.
14 | * Convert ZX Spectrum screens to PNG files.
15 | * Generate TAP files for ZX Spectrum Next and some emulators.
16 | * Disassembler also supports all undocumented Z80 instructions and Z80N (ZX Spectrum Next) instructions.
17 | * Also supports TSX Kansas City Standard blocks.
18 | * All tools can also read TAP files.
19 |
20 | ## Installation
21 |
22 | All the _tzxtools_ are written in Python 3.
23 |
24 | ```sh
25 | pip install tzxtools
26 | ```
27 |
28 | On MacOS X, [PortAudio](http://www.portaudio.com/) needs to be installed before:
29 |
30 | ```sh
31 | brew install portaudio
32 | pip3 install tzxtools
33 | ```
34 |
35 | ## Tools
36 |
37 | * `tzxcat` - Extracts data from a TZX file. Optionally disassembles, hex dumps or converts blocks to PNG.
38 | * `tzxcleanup` - Removes all clutter blocks and leaves a clean TZX file.
39 | * `tzxcut` - Cuts blocks from a TZX file.
40 | * `tzxls` - Lists the contents of a TZX file.
41 | * `tzxmerge` - Concatenates multiple TZX files into one file.
42 | * `tzxplay` - Plays back a TZX file for loading into a real ZX Spectrum.
43 | * `tzxsplit` - Splits a TZX file into separate programs.
44 | * `tzxtap` - Converts a TZX file to TAP file format.
45 | * `tzxwav` - Converts WAV file ZX Spectrum tape recordings to TZX files.
46 |
47 | See the [documentation](https://shredzone.org/docs/tzxtools/index.html) for how the tools are used.
48 |
49 | ## File Format References
50 |
51 | The TZX File Format is specified at [World of Spectrum](https://worldofspectrum.net/features/TZXformat.html).
52 |
53 | The TSX "ID 4B - Kansas City Standard" block is not a part of the specification. A documentation can be found at the [makeTSX wiki](https://github.com/nataliapc/makeTSX/wiki/Tutorial-How-to-generate-TSX-files#14-the-new-4b-block).
54 |
55 | The TAP File Format is described at [Sinclair Wiki](https://sinclair.wiki.zxnet.co.uk/wiki/TAP_format).
56 |
57 | ## Contribute
58 |
59 | * Fork the [Source code at Codeberg](https://codeberg.org/shred/tzxtools). Feel free to send pull requests.
60 | * Found a bug? [File a bug report!](https://codeberg.org/shred/tzxtools/issues)
61 |
62 | ## License
63 |
64 | _tzxtools_ is open source software. The source code is distributed under the terms of [GNU General Public License (GPLv3)](https://www.gnu.org/licenses/gpl-3.0.en.html#content).
65 |
66 | ## Acknowledgements
67 |
68 | * I would like to thank all the people who keep the retro computing scene alive.
69 |
--------------------------------------------------------------------------------
/docs/changelog.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## v1.9.4 (2025-04-17)
4 |
5 | * `tzxcat`: Bright colors were not properly converted, fixed (reported by @PedroFreire)
6 | * `tzxcat`: Use the color palette of Fuse emulator for PNG conversion
7 |
8 | ## v1.9.3 (2025-03-18)
9 |
10 | * `tzxcat`: Fix broken linebreaks on Windows (reported by @v-ein)
11 |
12 | ## v1.9.2 (2023-09-21)
13 |
14 | * `tzxplay`: Fix crash on zero length wavelets
15 |
16 | ## v1.9.1 (2022-08-03)
17 |
18 | * `tzxls`: Verbose option threw a Python error, fixed
19 |
20 | ## v1.9.0 (2022-06-03)
21 |
22 | * `tzxtap`: Skip comment blocks, as the TAP file can be read without them
23 |
24 | ## v1.8.0 (2022-03-20)
25 |
26 | * All tools can now also read TAP files
27 | * Use sounddevice instead of pyaudio (which is not maintained any more)
28 |
29 | ## v1.7.0 (2021-02-28)
30 |
31 | * Add new `tzxplay` tool for playing back TZX files
32 | * `tzxcleanup`: Add `--headermustmatch` option (by @oxidaan)
33 | * `tzxwav`: Verbose output shows tape time of each found block (idea by @oxidaan)
34 |
35 | ## v1.6.0 (2020-11-11)
36 |
37 | * Fix `stdin` and `stdout` usage on Windows installations
38 | * `tzxcat`: Also dump contents of deprecated C64 data blocks
39 |
40 | ## v1.5.0 (2020-05-29)
41 |
42 | * `tzxls`: Add `--verbose` option to get more details about TZX blocks
43 | * Add support for TSX Kansas City Standard blocks
44 | * `tzxcat`: Also dump contents of TZX text description blocks
45 |
46 | ## v1.4.0 (2020-05-02)
47 |
48 | * Add more Z80N and CSpect op codes to the disassembler
49 | * Enhance `tzxwav` debug output
50 |
51 | ## v1.3.0 (2019-11-14)
52 |
53 | * Fix broken raw binary output on `tzxcat`
54 |
55 | ## v1.2.0 (2019-01-13)
56 |
57 | * `tzxcat`: Add `--screen` option, to convert a standard ZX Spectrum `SCREEN$` block to a PNG file
58 | * `tzxcat`: Add `--org` option, to set the base address of dumps and disassembles. If not given, the base address of the previous `CODE` header is used
59 | * `tzxcat`: Add `--assembler` option, which disassembles the machine code of a block
60 | * `tzxcat`: Add `--dump` option, which creates a hex dump of the block content
61 | * `tzxcat`: Add `--skip` and `--length` option to extract only parts of a block
62 |
63 | ## v1.1.0 (2018-08-30)
64 |
65 | * Add `tzxtap` tool, it generates `tap` files from `tzx` files
66 |
67 | ## v1.0.1 (2018-08-23)
68 |
69 | * First release
70 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | # tzxtools
2 |
3 | This is a collection of command line tools for processing TZX files.
4 |
5 | TZX is a common file format for preserving computer tapes of the ZX Spectrum, but also Amstrad CPC and C64. `tzxtools` mainly supports ZX Spectrum TZX files, but raw file operations can be applied on any TZX file. It also supports TSX files, which are mainly used for MSX.
6 |
7 | ## Features
8 |
9 | * Convert your old ZX Spectrum tape recordings into TZX files.
10 | * List, split, merge, and divide the blocks inside TZX files.
11 | * Extract binary content from TZX blocks.
12 | * Read hex dumps, disassembled Z80 machine code, or ZX Spectrum BASIC code.
13 | * Convert ZX Spectrum screens to PNG files.
14 | * Generate TAP files for ZX Spectrum Next and some emulators.
15 | * Disassembler also supports all undocumented Z80 instructions and Z80N (ZX Spectrum Next) instructions.
16 | * Also supports TSX Kansas City Standard blocks.
17 | * All tools can also read TAP files.
18 |
19 | ## Installation
20 |
21 | All the _tzxtools_ are written in Python 3.
22 |
23 | ```sh
24 | pip install tzxtools
25 | ```
26 |
27 | On MacOS X, [PortAudio](http://www.portaudio.com/) needs to be installed before:
28 |
29 | ```sh
30 | brew install portaudio
31 | pip3 install tzxtools
32 | ```
33 |
34 | ## The Tools
35 |
36 | * [`tzxcat`](tzxcat.md) - Extracts data from a TZX file. Optionally disassembles, hex dumps or converts blocks to PNG.
37 | * [`tzxcleanup`](tzxcleanup.md) - Removes all clutter and leaves a clean tape file.
38 | * [`tzxcut`](tzxcut.md) - Cuts blocks from a TZX file.
39 | * [`tzxls`](tzxls.md) - Lists the contents of a TZX file.
40 | * [`tzxmerge`](tzxmerge.md) - Concatenates multiple TZX files into one file.
41 | * [`tzxplay`](tzxplay.md) - Plays back a TZX file for loading into real hardware.
42 | * [`tzxsplit`](tzxsplit.md) - Splits a TZX file into separate programs.
43 | * [`tzxtap`](tzxtap.md) - Converts a TZX file to TAP file format.
44 | * [`tzxwav`](tzxwav.md) - Converts WAV file ZX Spectrum tape recordings to TZX files.
45 |
46 | ## TZX and TSX File Format References
47 |
48 | The TZX File Format is specified at [World of Spectrum](https://www.worldofspectrum.org/TZXformat.html).
49 |
50 | The TSX "ID 4B - Kansas City Standard" block is not a part of the specification. A documentation can be found at the [makeTSX wiki](https://github.com/nataliapc/makeTSX/wiki/Tutorial-How-to-generate-TSX-files#14-the-new-4b-block).
51 |
52 | ## Open Source
53 |
54 | _tzxtools_ is open source software. The source code is available [at Codeberg](https://codeberg.org/shred/tzxtools), and is distributed under the terms of [GNU General Public License (GPLv3)](https://www.gnu.org/licenses/gpl-3.0.en.html#content).
55 |
--------------------------------------------------------------------------------
/docs/tzxcat.md:
--------------------------------------------------------------------------------
1 | # `tzxcat`
2 |
3 | Extracts the binary content of TZX data blocks to a file.
4 |
5 | This tool is useful to migrate tape computer files to modern computers.
6 |
7 | It also brings a set of converters to ZX Spectrum BASIC, assembler, ZX Spectrum screens, plain text and hex dump.
8 |
9 | This tool also accepts TAP files. They are converted to TZX format internally.
10 |
11 | ## Usage
12 |
13 | ```
14 | tzxcat [-h] [-b NR] [-o TARGET] [-s BYTES] [-l BYTES]
15 | [-t] [-B] [-A] [-S] [-d] [-O BASE] [file]
16 | ```
17 |
18 | * `file`: TZX file to read from, or `stdin` if not given.
19 | * `-o`, `--to`: Target file. If omitted, `stdout` is used.
20 | * `-b`, `--block`: Only extract the TZX block with the given block number. If omitted, all data blocks are concatenated to a single output stream. The selected block must be a data block. If the block has a bad CRC, a warning is printed, but the content is extracted nevertheless. If this is not a ZX Spectrum block, a false CRC error is always reported and can be ignored.
21 | * `-s`, `--skip`: Skip the given number of bytes before output. If omitted, nothing is skipped. If it exceeds the block length, an empty block is written.
22 | * `-l`, `--length`: Limit the output to the given number of bytes. The rest of the block is written if this parameter is omitted or if it exceeds the block length.
23 | * `-h`, `--help`: Show help message and exit.
24 |
25 | A converter can be applied to the output. If no converter is chosen, the output is just the binary content of the selected block. Available converters are:
26 |
27 | * `-t`, `--text`: Convert ZX Spectrum text to plain text.
28 | * `-B`, `--basic`: Convert ZX Spectrum BASIC to plain text. The result is what you would see on the screen after a `LIST` command. Inline attribute changes are ignored though.
29 | * `-A`, `--assembler`: Disassemble the block, using a simple Z80 disassembler. Undocumented Z80 op codes and Z80N (ZX Spectrum Next) op codes are supported. The disassembler also supports the `exit` and `break` pseudo op codes of the #CSpect emulator.
30 | * `-S`, `--screen`: Convert a ZX Spectrum SCREEN$ to PNG. It is recommended to select the SCREEN block using the `--block` option.
31 | * `-d`, `--dump`: Generate a hex dump of the block contents.
32 |
33 | Additional converter options:
34 |
35 | * `-O`, `--org`: Define the base address for hex dumps and disassembled code. If not given, the starting address given in the previous `Bytes` header is used automatically. If there is no such header, 0 is assumed as base address.
36 |
37 | Converters use your system's encoding as target encoding. If your system does not use Unicode, the presence of some special characters may lead to an error.
38 |
39 | ## Example
40 |
41 | ```
42 | tzxcat --block 4 --to screen.scr game.tzx
43 | ```
44 |
45 | Reads the `game.tzx` file and copies the binary contents of the 4th block to `screen.scr`.
46 |
47 | ```
48 | tzxcat --block 4 --screen --to screen.png game.tzx
49 | ```
50 |
51 | The same as above, but now the screen is converted to PNG.
52 |
53 | ```
54 | tzxcat --block 4 --text sources.tzx
55 | ```
56 |
57 | Dumps block 4 in a (more or less) readable plain text format to stdout.
58 |
59 | ```
60 | tzxcat --block 4 --dump sources.tzx
61 | ```
62 |
63 | The same as above, but dumps block 4 as hex dump to stdout.
64 |
65 | ```
66 | tzxcat --block 2 --basic sources.tzx
67 | ```
68 |
69 | Shows block 2 as BASIC listing.
70 |
71 | ```
72 | tzxcat --block 6 --assembler sources.tzx
73 | ```
74 |
75 | Shows block 6 as disassembled machine code. The starting address of the `Bytes` header in block 5 is used automatically as the base address.
76 |
77 | ```
78 | tzxcat --block 6 --assembler --org 32768 sources.tzx
79 | ```
80 |
81 | The same as above, but 32768 is used as fixed base address.
82 |
83 | ## Supported Block Types
84 |
85 | `tzxcat` can extract binary data from all block types containing actual data:
86 |
87 | - 10 - Standard Speed Data Block
88 | - 11 - Turbo Speed Data Block
89 | - 14 - Pure Data Block
90 | - 30 - Text description
91 | - 31 - Message
92 | - 35 - Custom info
93 | - 4B - Kansas City Standard
94 |
--------------------------------------------------------------------------------
/docs/tzxcleanup.md:
--------------------------------------------------------------------------------
1 | # `tzxcleanup`
2 |
3 | The only purpose of this tool is to post-process and clean up TZX files **that have been just generated by a tape converter**. It will set idealized timings for ZX Spectrum blocks where applicable. It will remove all unnecessary blocks, like comment blocks or (optionally) blocks with a bad CRC.
4 |
5 | The result might not be loadable at all, so be careful and keep a backup of the original file.
6 |
7 | It is not necessary to use this tool on the output of [`tzxwav`](tzxwav.md), as it wouldn't change anything.
8 |
9 | Use [`tzxcut`](tzxcut.md) to manually clean up all kind of TZX files.
10 |
11 | This tool also accepts a TAP file. It is converted to TZX format internally.
12 |
13 | ## Usage
14 |
15 | ```
16 | tzxcleanup [-h] [-o TARGET] [-c] [file]
17 | ```
18 |
19 | * `file`: TZX file to read from, or `stdin` if not given.
20 | * `-o`, `--to`: Target file. If omitted, `stdout` is used.
21 | * `-c`, `--stripcrc`: Also remove all data blocks with a bad CRC. They would usually lead to a "tape loading error".
22 | * `-H`, `--headermustmatch`: Remove all blocks that are not preceeded by a matching header.
23 | * `-h`, `--help`: Show help message and exit.
24 |
25 | ## Example
26 |
27 | ```
28 | tzxcleanup recording.tzx | tzxls -l
29 | ```
30 |
31 | Shows the content of a cleaned-up `recording.tzx` file.
32 |
33 | ```
34 | tzxcleanup -o game.tzx recording.tzx
35 | ```
36 |
37 | Cleans up a raw `recording.tzx` file and writes it to `game.tzx`.
38 |
--------------------------------------------------------------------------------
/docs/tzxcut.md:
--------------------------------------------------------------------------------
1 | # `tzxcut`
2 |
3 | Cuts out blocks from a TZX file into a new TZX file.
4 |
5 | This tool is useful to split the copy of a mixed tape into a separate TZX file for one of the programs.
6 |
7 | See also `tzxsplit`.
8 |
9 | This tool also accepts a TAP file. It is converted to TZX format internally.
10 |
11 | ## Usage
12 |
13 | ```
14 | tzxcut [-h] [-i SOURCE] [-o TARGET] [-v] [blocks [blocks ...]]
15 | ```
16 |
17 | * `blocks`: Block number, or range of block numbers, to keep in the output file. Use `tzxls` to find out the block numbers of a TZX file.
18 | * `-i`, `--from`: TZX file to read from, or `stdin` if not given.
19 | * `-o`, `--to`: Target file. If omitted, `stdout` is used.
20 | * `-v`, `--invert`: Invert block matches. The given block numbers are not kept, but removed.
21 | * `-h`, `--help`: Show help message and exit.
22 |
23 | Blocks can be addressed in a single number or in a range:
24 |
25 | * `13` - Keep block number 13.
26 | * `4:8` - Keep block numbers 4 to 8 (inclusive).
27 | * `3:` - Keep block numbers 3 and higher.
28 | * `:4` - Keep the first blocks up to block 4 (inclusive).
29 |
30 | Remember that blocks are counted starting from zero.
31 |
32 | Negative block numbers are counted backwards from the last block:
33 |
34 | * `-1` - Keep only the last block.
35 | * `4:-2` - Keep block numbers from 4 up to the second to last block.
36 | * `-4:` - Keep the last four blocks.
37 | * `:-3` - Keep all the blocks up the third to last block.
38 |
39 | If you use negative block numbers, it is wise to place a `--` at the command line before the block ranges, so negative block numbers are not interpreted as options (see example below).
40 |
41 | ## Example
42 |
43 | ```
44 | tzxcut -i games.tzx -o first-game.tzx 0:5 7
45 | ```
46 |
47 | Copies the blocks 0 to 5 (inclusive) and block 7 of `games.tzx` into a new file `first-game.tzx`.
48 |
49 | ```
50 | tzxcut -i games.tzx -o first-game.tzx -- -5 -3:
51 | ```
52 |
53 | Copies the fifth to last and the three last blocks of `games.tzx` into a new file `first-game.tzx`.
54 |
--------------------------------------------------------------------------------
/docs/tzxls.md:
--------------------------------------------------------------------------------
1 | # `tzxls`
2 |
3 | Lists the contents of a TZX file.
4 |
5 | Ths tool shows the block numbers, block types and some block contents of a TZX file.
6 |
7 | For ZX Spectrum TZX files, it also shows header contents (like program names or data types). Note that CRC checks only apply for ZX Spectrum files. For other machines, this tool will always report false CRC errors.
8 |
9 | This tool also accepts TAP files. They are converted to TZX format internally.
10 |
11 | ## Usage
12 |
13 | ```
14 | tzxls [-h] [-s] [-v] file [file ...]
15 | ```
16 |
17 | * `file`: TZX file or files to read from, or `stdin` if not given.
18 | * `-s`, `--short`: Only shows the names found in ZX Spectrum file headers.
19 | * `-h`, `--help`: Show help message and exit.
20 | * `-v`, `--verbose`: Show more details about each block, if available.
21 |
22 | ## Example
23 |
24 | ```
25 | tzxls tape.tzx
26 | ```
27 |
28 | Lists all the TZX file blocks of `tape.tzx`.
29 |
30 | ```
31 | tzxls -s tape.tzx
32 | ```
33 | Lists the names of all the ZX Spectrum program and data files found on the `tape.tzx`.
34 |
35 | ```
36 | tzxls -v tape.tzx
37 | ```
38 |
39 | Lists all the TZX file blocks of `tape.tzx`, and shows details about each block.
40 |
--------------------------------------------------------------------------------
/docs/tzxmerge.md:
--------------------------------------------------------------------------------
1 | # `tzxmerge`
2 |
3 | Merges multiple TZX files into a single TZX file.
4 |
5 | Multiple TZX files can also just be concatenated (e.g. `cat file1.tzx file2.tzx > files.tzx`), but this will add an unused "glue" block. `tzxmerge` merges TZX files without a "glue" block. It also fails if one of the files is not a TZX file.
6 |
7 | This tool also accepts TAP files. They are converted to TZX format internally.
8 |
9 | ## Usage
10 |
11 | ```
12 | tzxmerge [-h] [--to TARGET] files [files ...]
13 | ```
14 |
15 | * `files`: TZX files to merge.
16 | * `-o`, `--to`: Target file. If omitted, `stdout` is used.
17 | * `-h`, `--help`: Show help message and exit.
18 |
19 | ## Example
20 |
21 | ```
22 | tzxmerge -o demo.tzx demo-loader.tzx demo-screen.tzx demo-binaries.tzx
23 | ```
24 |
25 | Creates a `demo.tzx` file consisting of `demo-loader.tzx`, `demo-screen.tzx` and `demo-binaries.tzx`.
26 |
27 | ```
28 | tzxmerge -o demo.tzx demo.tap
29 | ```
30 |
31 | Converts the TAP file `demo.tap` to a TZX file `demo.tzx`.
32 |
--------------------------------------------------------------------------------
/docs/tzxplay.md:
--------------------------------------------------------------------------------
1 | # `tzxplay`
2 |
3 | Plays back a TZX file.
4 |
5 | This tool is useful to feed a real ZX Spectrum with a TZX file. It is played back via your system's audio output. Usually you would connect your ZX Spectrum to your computer's headphone output, and then play back the TZX file.
6 |
7 | Optionally, a WAV file can be generated instead. You can store this WAV file on a portable media player, and then use the player to load files into your ZX Spectrum.
8 |
9 | Playback can always be aborted by pressing Ctrl-C.
10 |
11 | This tool also accepts a TAP file. It is converted to TZX format internally.
12 |
13 | ## Notes
14 |
15 | * **TURN DOWN THE SYSTEM VOLUME FIRST!** The output signal is very loud, and may damage your speakers with its rectangle pulses. Make sure to turn down your system volume before using `tzxplay` for the first time.
16 |
17 | * Do not compress the WAV file with a lossy format like mp3 or Ogg Vorbis. This may lead to tape loading errors. Remember that lossy compressors are optimized for human ears, not ZX Spectrum ears. Lossless formats like FLAC can be used, though.
18 |
19 | * `tzxplay` supports the most commonly used blocks at the moment, so classic recordings and even many speedloaders can be played back. However, some very special data blocks and control blocks will be ignored, or lead to an error.
20 |
21 | * The generated WAV file can become quite large, especially if the TZX file contains jumps or loops. Broken TZX files can even result in an endless loop. You can press Ctrl-C to abort `tzxplay`.
22 |
23 | * Playback of C64 or Kansas City Standard blocks is not supported at the moment.
24 |
25 | * You can use [`tzxcut`](tzxcut.md) to play only a subset of blocks from a TZX file (see example below).
26 |
27 | ## Usage
28 |
29 | ```
30 | tzxplay [-h] [-o TARGET] [-v] [-s] [-K] [-r RATE] [-c CLOCK] [-S] [file]
31 | ```
32 |
33 | * `file`: TZX file to read from, or `stdin` if not given.
34 | * `-o`, `--to`: Create a WAV file instead of playing audio.
35 | * `-v`, `--verbose`: Be verbose about what you are doing.
36 | * `-s`, `--stop`: Stop playback on Stop-The-Tape blocks. By default, playback only stops when the end of the TZX file is reached.
37 | * `-K`, `--48k`: Enable ZX Spectrum 48K mode. If set, playback stops on a 2A block ("Stop the tape if in 48K mode"). Use this option if you have a dual 48K/128K tape, and only want to load the ZX Spectrum 48K part.
38 | * `-r`, `--rate`: Output sampling rate, default is 44100 Hz. Please use only common sampling rates like 22050, 32000, 44100, 48000. While `tzxplay` will accept other rates, they may result in playback problems.
39 | * `-c`, `--clock`: Change reference Z80 CPU clock speed, in Hz. Default is 3500000. There is usually no need to change it.
40 | * `-S`, `--sine`: By default `tzxplay` generates perfect rectangle pulses. They are optimal for loading, but do not sound really Spectrum-ish. With this option, the sine pulses of a classic tape recording are simulated.
41 | * `-h`, `--help`: Show help message and exit.
42 |
43 | ## Example
44 |
45 | ```
46 | tzxplay game.tzx
47 | ```
48 |
49 | Read `game.tzx` and play it back via your computer's audio interface.
50 |
51 | ```
52 | tzxplay -v game.tzx
53 | ```
54 |
55 | Like above, but also shows what block is being processed.
56 |
57 | ```
58 | tzxplay -o game.wav game.tzx
59 | ```
60 |
61 | Generate a WAV file instead.
62 |
63 | ```
64 | tzxcut -i games.tzx 0:5 | tzxplay
65 | ```
66 |
67 | Only play back blocks 0 to 5 (inclusive).
--------------------------------------------------------------------------------
/docs/tzxsplit.md:
--------------------------------------------------------------------------------
1 | # `tzxsplit`
2 |
3 | Splits a TZX file into its different programs.
4 |
5 | This tool is useful to automatically split up a single TZX file of a mixed tape with different programs. `tzxsplit` searches for a ZX Spectrum "Program" block, and then extracts the program itself and all subsequent blocks up to the next "Program" block.
6 |
7 | Each program and the subsequent blocks are written into a separate TZX file, which is named like the program itself. A number is added to the file name, in order to avoid file name collisions.
8 |
9 | If the tape file should not start with a "Program", all blocks up to the first Program are stored into a TZX file called "preamble.tzx".
10 |
11 | See also `tzxcut`.
12 |
13 | This tool also accepts a TAP file. It is converted to TZX format internally.
14 |
15 | ## Usage
16 |
17 | ```
18 | tzxsplit [-h] [-d TARGET] [-s] [file]
19 | ```
20 |
21 | * `file`: TZX file to read from, or `stdin` if not given.
22 | * `-d`, `--dir`: Target directory of the generated TZX files. If omitted, the current directory is used.
23 | * `-s`, `--skip`: Instead of writing a preamble file, just skip all blocks up to the first program.
24 | * `-1`, `--single`: Split at every loadable file instead of splitting at every program.
25 | * `-h`, `--help`: Show help message and exit.
26 |
27 | ## Example
28 |
29 | ```
30 | tzxsplit tape.tzx
31 | ```
32 |
33 | Read `tape.tzx` and generate TZX files for all the programs (and the subsequent data blocks) found in it.
34 |
--------------------------------------------------------------------------------
/docs/tzxtap.md:
--------------------------------------------------------------------------------
1 | # `tzxtap`
2 |
3 | Converts a TZX file to a TAP file.
4 |
5 | This tool is useful to convert TZX files to the TAP file format. Some emulators or computers are unable to read TZX files, but accept TAP files. This tool converts a TZX file into this format.
6 |
7 | TAP files are much simpler than TZX files, as they only support Standard Speed Data Blocks. TZX comment blocks will be skipped with a warning. Other TZX blocks (like those used by speedloaders) will result in an error, because they cannot be converted to the TAP format. You can enforce conversion by using the `--ignore` option, but it is very unlikely that the resulting TAP file can be loaded successfully.
8 |
9 | This tool also accepts a TAP file, but will generate an identical TAP file from it.
10 |
11 | ## Usage
12 |
13 | ```
14 | tzxtap [-h] [-o TARGET] [-i] [file]
15 | ```
16 |
17 | * `file`: TZX file to read from, or `stdin` if not given.
18 | * `-o`, `--to`: Target TAP file to write. If omitted, `stdout` is used.
19 | * `-i`, `--ignore`: Ignore blocks that cannot be stored into a TAP file.
20 | * `-h`, `--help`: Show help message and exit.
21 |
22 | ## Example
23 |
24 | ```
25 | tzxtap -o tape.tap tape.tzx
26 | ```
27 |
28 | Read `tape.tzx` and generate a `tape.tap` file from its Standard Speed Data Blocks.
29 |
30 | ```
31 | tzxtap --ignore -o tape.tap
32 | ```
33 |
34 | Like above, but ignore all blocks that cannot be converted to TAP files.
35 |
--------------------------------------------------------------------------------
/docs/tzxwav.md:
--------------------------------------------------------------------------------
1 | # `tzxwav`
2 |
3 | Reads ZX Spectum tapes from a WAV file and converts it to TZX.
4 |
5 | `tzxwav` is very slow and is only able to convert standard speed recordings. However, its main goal is to handle poor quality recordings. It is robust against tape speed flutter, different recording levels, inverted signals and other tape related problems.
6 |
7 | `tzxwav` is optimized for ZX Spectrum tape recordings with standard timing, and thus unable to properly convert non-standard files, like speedloaders. There are other tools for this purpose, for example `audio2tape` that comes with the [Fuse emulator](http://fuse-emulator.sourceforge.net/).
8 |
9 | ## Usage
10 |
11 | ```
12 | tzxwav [-h] [-o TARGET] [-p] [-v] [-t {low,med,high}]
13 | [-T {low,med,high}] [-l {none,short,normal,long}] [-c CLOCK]
14 | [-s START] [-e END] [-S {left,mix,right}] [-D] file
15 | ```
16 |
17 | * `file`: WAV file to read from. Supported is mono and stereo, 8 and 16 bit per channel, any sampling rate. Other file formats are not supported.
18 | * `-o`, `--to`: Target file. If omitted, `stdout` is used.
19 | * `-p`, `--progress`: Show a progress bar on `stderr`.
20 | * `-v`, `--verbose`: Be verbose, show blocks as they are found. It also shows the starting and ending frame number of each block. This can be used for manually repairing CRC errors at the ending frame, or for selecting individual blocks with the `--start` and `--end` option.
21 | * `-t`, `--treshold`: Change sound/noise ratio treshold. Default is `mid`. Try `low` if data blocks are missing or shorter than expected. Try `high` if data blocks are longer than expected.
22 | * `-T`, `--tolerance`: Change tape speed flutter tolerance. Default is `mid`. Try `low` if the TZX file contains many useless blocks. Try `high` if you miss headers or data blocks in the TZX file, or if data blocks are shorter than expected.
23 | * `-l`, `--leader`: Acceptable minimal leader signal length. Default is `normal`. If there are a lot of headerless blocks, or if there are blocks missing in the TZX file, it is worth a try to play with this parameter. `none` even accepts a single header pulse.
24 | * `-s`, `--start`: Set the first frame of the WAV file to be read. If not set, the start of file is used.
25 | * `-e`, `--end`: Set the last frame of the WAV file to be read. For technical reasons, this limit may be exceeded by a few frames. If not set, or if set out of range, the file will be read to the end.
26 | * `-c`, `--clock`: Change reference Z80 CPU clock speed, in Hz. Default is 3500000. It is also useful for correcting a wrong playback speed. For example, if your tape was played back 5% too fast, adjust the clock to 3500000 * 5% = 3675000 to improve the results.
27 | * `-S`, `--stereo`: Select channel of the stereo WAV file to be used. Default is `mix` of both channels.
28 | * `-D`, `--debug`: Show debugging output. Useful for finding out why `tzxwav` was unable to correctly read a file. Prints detected blocks and their position frame in the WAV file. If given two times, also prints detected bits and bytes. If given three times, prints detected pulse lengths (in T states) and their WAV file position. If given four times, also prints the reason why a sync or bit pulse was rejected. Attention, it will create a *lot* of useless output!
29 | * `-h`, `--help`: Show help message and exit.
30 |
31 | ## Sampling recommendation
32 |
33 | You will get best results if you use a sampling rate of at least 44100 Hz, 16 bit resolution per sample, and a single audio channel. I recommend to decide either on the left or right channel, depending on the quality. Avoid mixing down stereo to mono.
34 |
35 | Use a proper recording level, but try to avoid clipping.
36 |
37 | Do not apply any low pass or band pass digital filters, unless the audio quality is really bad and you get too many CRC errors. However for tape files that were generated by a tool or were compressed by a lossy compression, it may help to apply a low pass filter with a cut off frequency of 1600 Hz first.
38 |
39 | ## Example
40 |
41 | ```
42 | tzxwav -o tape.tzx tape.wav
43 | ```
44 |
45 | Reads the `tape.wav` file and converts it to a `tape.tzx` file.
46 |
47 | ```
48 | tzxwav -tlow -Thigh -lshort -o tape.tzx tape.wav
49 | ```
50 |
51 | Tries its best to read a poor quality audio file from `tape.wav`, but may also generate some useless blocks in the TZX file.
52 |
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: tzxtools
2 | site_author: Richard Körber
3 | site_url: https://shredzone.org/docs/tzxtools/index.html
4 | theme:
5 | name: material
6 | font: false
7 | icon:
8 | logo: 'material/cassette'
9 | palette:
10 | primary: 'blue'
11 | accent: 'deep orange'
12 | nav:
13 | - 'Installation': 'index.md'
14 | - 'tzxcat': 'tzxcat.md'
15 | - 'tzxcleanup': 'tzxcleanup.md'
16 | - 'tzxcut': 'tzxcut.md'
17 | - 'tzxls': 'tzxls.md'
18 | - 'tzxmerge': 'tzxmerge.md'
19 | - 'tzxplay': 'tzxplay.md'
20 | - 'tzxsplit': 'tzxsplit.md'
21 | - 'tzxtap': 'tzxtap.md'
22 | - 'tzxwav': 'tzxwav.md'
23 | - 'Changelog': 'changelog.md'
24 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #
2 | # tzxtools - a collection for processing tzx files
3 | #
4 | # Copyright (C) 2018 Richard "Shred" Körber
5 | # https://codeberg.org/shred/tzxtools
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 |
21 | from setuptools import setup
22 |
23 | def readme():
24 | with open('README.md') as f:
25 | return f.read()
26 |
27 | setup(
28 | name='tzxtools',
29 | version='1.9.4',
30 | description='A tool collection for processing tzx files',
31 | long_description=readme(),
32 | long_description_content_type='text/markdown',
33 | url='https://codeberg.org/shred/tzxtools',
34 | keywords='ZX-Spectrum tzx wav',
35 | license='GPLv3+',
36 |
37 | python_requires='>=3',
38 |
39 | author='Richard Körber',
40 | author_email='dev@shredzone.de',
41 |
42 | project_urls={
43 | 'Source': 'https://codeberg.org/shred/tzxtools',
44 | 'Tracker': 'https://codeberg.org/shred/tzxtools/issues',
45 | },
46 |
47 | classifiers=[
48 | 'Development Status :: 5 - Production/Stable',
49 | 'Environment :: Console',
50 | 'Intended Audience :: Developers',
51 | 'Intended Audience :: End Users/Desktop',
52 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
53 | 'Operating System :: OS Independent',
54 | 'Programming Language :: Python :: 3 :: Only',
55 | 'Topic :: System :: Archiving',
56 | 'Topic :: System :: Emulators',
57 | 'Topic :: Utilities'
58 | ],
59 |
60 | packages=['tzxtools', 'tzxlib'],
61 |
62 | install_requires=[
63 | 'numpy >= 1.20.0',
64 | 'pypng >= 0.0.20',
65 | 'sounddevice >= 0.4.0',
66 | ],
67 |
68 | entry_points={
69 | 'console_scripts': [
70 | 'tzxcat=tzxtools.tzxcat:main',
71 | 'tzxcleanup=tzxtools.tzxcleanup:main',
72 | 'tzxcut=tzxtools.tzxcut:main',
73 | 'tzxls=tzxtools.tzxls:main',
74 | 'tzxmerge=tzxtools.tzxmerge:main',
75 | 'tzxplay=tzxtools.tzxplay:main',
76 | 'tzxsplit=tzxtools.tzxsplit:main',
77 | 'tzxtap=tzxtools.tzxtap:main',
78 | 'tzxwav=tzxtools.tzxwav:main',
79 | ],
80 | },
81 | )
82 |
--------------------------------------------------------------------------------
/tzxlib/__init__.py:
--------------------------------------------------------------------------------
1 | name = "tzxlib"
2 |
--------------------------------------------------------------------------------
/tzxlib/convert.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2018 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import os
23 | from sys import getdefaultencoding
24 | from struct import unpack
25 | from tzxlib.z80dis import disassemble
26 |
27 | UPPER = [ ' ', '▝', '▘', '▀', '▗', '▐', '▚', '▜', '▖', '▞', '▌', '▛', '▄', '▟',
28 | '▙', '█', 'Ⓐ', 'Ⓑ', 'Ⓒ', 'Ⓓ', 'Ⓔ', 'Ⓕ', 'Ⓖ', 'Ⓗ', 'Ⓘ', 'Ⓙ', 'Ⓚ',
29 | 'Ⓛ', 'Ⓜ', 'Ⓝ', 'Ⓞ', 'Ⓟ', 'Ⓠ', 'Ⓡ', 'Ⓢ', 'Ⓣ', 'Ⓤ', 'RND', 'INKEY$',
30 | 'PI', 'FN ', 'POINT ', 'SCREEN$ ', 'ATTR ', 'AT ', 'TAB ', 'VAL$ ',
31 | 'CODE ', 'VAL ', 'LEN ', 'SIN ', 'COS ', 'TAN ', 'ASN ', 'ACS ', 'ATN ',
32 | 'LN ', 'EXP ', 'INT ', 'SQR ', 'SGN ', 'ABS ', 'PEEK ', 'IN ', 'USR ',
33 | 'STR$ ', 'CHR$ ', 'NOT ', 'BIN ', ' OR ', ' AND ', '<=', '>=', '<>',
34 | ' LINE ', ' THEN ', ' TO ', ' STEP ', ' DEF FN ', ' CAT ', ' FORMAT ',
35 | ' MOVE ', ' ERASE ', ' OPEN #', ' CLOSE #', ' MERGE ', ' VERIFY ',
36 | ' BEEP ', ' CIRCLE ', ' INK ', ' PAPER ', ' FLASH ', ' BRIGHT ',
37 | ' INVERSE ', ' OVER ', ' OUT ', ' LPRINT ', ' LLIST ', ' STOP ', ' READ ',
38 | ' DATA ', ' RESTORE ', ' NEW ', ' BORDER ', ' CONTINUE ', ' DIM ', ' REM ',
39 | ' FOR ', ' GO TO ', ' GO SUB ', ' INPUT ', ' LOAD ', ' LIST ', ' LET ',
40 | ' PAUSE ', ' NEXT ', ' POKE ', ' PRINT ', ' PLOT ', ' RUN ', ' SAVE ',
41 | ' RANDOMIZE ', ' IF ', ' CLS ', ' DRAW ', ' CLEAR ', ' RETURN ', ' COPY ' ]
42 |
43 | def convChar(ch, noLeadingSpace=False):
44 | if ch == 0x0D: return '\n'
45 | elif ch >= 0x80:
46 | result = UPPER[ch - 0x80]
47 | if noLeadingSpace and ch >= 0xA5 and result[0] == ' ':
48 | return result[1:]
49 | else:
50 | return result
51 | elif ch == 0x5E: return '↑'
52 | elif ch == 0x60: return '£'
53 | elif ch == 0x7F: return '©'
54 | else: return chr(ch)
55 |
56 | def convert(data):
57 | result = ''
58 | for d in data:
59 | if d >= 0x20:
60 | result += convChar(d, result[-1:] == ' ')
61 | return result
62 |
63 | def convertCR(data):
64 | result = ''
65 | for d in data:
66 | if d >= 0x20 or d == 0x0D:
67 | result += convChar(d, result[-1:] == ' ')
68 | return result
69 |
70 | def decodeBasicLine(line):
71 | result = ''
72 | pos = 0
73 | while pos < len(line):
74 | ch = line[pos]
75 | pos += 1
76 | if 0x10 <= ch <= 0x15:
77 | pos += 1
78 | elif 0x16 <= ch <= 0x17:
79 | pos += 2
80 | elif ch == 0x0E:
81 | pos += 5
82 | else:
83 | result += convChar(ch, result[-1:] == ' ')
84 | return result
85 |
86 | def convertToText(data, out, org=0):
87 | out.write(convertCR(data).replace('\n', os.linesep).encode(getdefaultencoding()))
88 |
89 | def convertToBasic(data, out, org=0):
90 | pos = 0
91 | end = len(data)
92 | while pos + 4 < end:
93 | lineNum = unpack('>H', data[pos + 0 : pos + 2])[0]
94 | lineLen = unpack(' end:
96 | break
97 | line = '%4d%s' % (lineNum, decodeBasicLine(unpack('%dB' % (lineLen), data[pos + 4 : pos + 4 + lineLen])))
98 | out.write(line.replace('\n', os.linesep).encode(getdefaultencoding()))
99 | pos += lineLen + 4
100 |
101 | def convertToDump(data, out, org=0, bytesPerRow=16):
102 | pos = 0
103 | end = len(data)
104 | while pos < end:
105 | line = '%04X | ' % (pos + org)
106 | text = ''
107 | for x in range(bytesPerRow):
108 | if pos + x < end:
109 | line += '%02X ' % (data[pos + x])
110 | ch = data[pos + x]
111 | if ch < 32:
112 | text += '‧'
113 | else:
114 | ch = convChar(ch)
115 | if len(ch) == 1:
116 | text += ch
117 | else:
118 | text += '‧'
119 | else:
120 | line += ' '
121 | line += '| '
122 | line += text
123 | line += '\n'
124 | out.write(line.replace('\n', os.linesep).encode(getdefaultencoding()))
125 | pos += bytesPerRow
126 |
127 | def convertToAssembler(data, out, org=0):
128 | pos = 0
129 | end = len(data)
130 | while pos < end:
131 | try:
132 | (ins, length) = disassemble(data, pos, org)
133 | except:
134 | (ins, length) = ('???', 1)
135 | line = '%04X ' % (pos + org)
136 | for x in range(6):
137 | if x == 5 and length > 6:
138 | line += '...'
139 | elif x < length:
140 | line += '%02X ' % (data[pos + x])
141 | else:
142 | line += ' '
143 | line += ' '
144 | line += ins
145 | line += '\n'
146 | out.write(line.replace('\n', os.linesep).encode(getdefaultencoding()))
147 | pos += length
148 |
149 | def convertToScreen(data, out, org=0):
150 | pixel = []
151 | for y in range(192):
152 | pixrow = []
153 | pixel.append(pixrow)
154 | for col in range(32):
155 | palette = readColor(data, y, col)
156 | bits = readBits(data, y, col)
157 | for b in range(8):
158 | if bits & (0b10000000 >> b):
159 | pixrow.append(palette[0])
160 | else:
161 | pixrow.append(palette[1])
162 |
163 | import png
164 | pngw = png.Writer(256, 192, palette=PALETTE)
165 | pngw.write(out, pixel)
166 |
167 | def readBits(data, y, col):
168 | block = int(y / 64)
169 | line = int((y % 64) / 8)
170 | row = y % 8
171 | offset = ((((block * 8) + row) * 8) + line) * 32 + col
172 | return data[offset] if offset < len(data) else 0
173 |
174 | def readColor(data, y, col):
175 | row = (int)(y / 8)
176 | offset = 6144 + row * 32 + col
177 | cols = data[offset] if offset < len(data) else 0b00111000
178 | if (cols & 0b01000000) != 0:
179 | return ((cols & 0x07) + 8, (cols >> 3 & 0x07) + 8)
180 | else:
181 | return ((cols & 0x07), (cols >> 3 & 0x07))
182 |
183 | PALETTE = [
184 | (0,0,0), (0,0,192), (192,0,0), (192,0,192), (0,192,0), (0,192,192), (192,192,0), (192,192,192),
185 | (0,0,0), (0,0,255), (255,0,0), (255,0,255), (0,255,0), (0,255,255), (255,255,0), (255,255,255),
186 | ]
187 |
--------------------------------------------------------------------------------
/tzxlib/loader.py:
--------------------------------------------------------------------------------
1 | #
2 | # tzxtools - a collection for processing tzx files
3 | #
4 | # Copyright (C) 2016 Richard "Shred" Körber
5 | # https://codeberg.org/shred/tzxtools
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 |
21 | from collections import deque
22 | from struct import unpack
23 | import sys
24 | import wave
25 |
26 | from tzxlib.tapfile import TapFile, TapHeader, TapData
27 | from tzxlib.tzxblocks import TzxbData
28 | from tzxlib.tzxfile import TzxFile
29 |
30 | def sgn(val):
31 | return 1 if val >= 0 else -1
32 |
33 | def unpackMono(data, size):
34 | return unpack('<' + size, data)[0]
35 |
36 | def unpackStereo(data, size, leftMix = 0.5):
37 | val = unpack('<' + size + size, data)
38 | return (val[0] * leftMix + val[1] * (1 - leftMix))
39 |
40 | class TapeLoader():
41 |
42 | # Actual ZX Spectrum pulse timings:
43 | # length of a half wave, in number of T-states
44 | leaderT = 2168 # leader pulse
45 | syncT = 701 # sync pulse (on: 667, off: 735)
46 | lowT = 855 # 0 bit pulse
47 | highT = 1710 # 1 bit pulse
48 |
49 | def __init__(self, progress=None, debug=None, verbose=False, treshold=3500, tolerance=1.2, leaderMin=20, cpufreq=3500000, leftChMix=0.5):
50 | maxlenT = self.leaderT * 2.2 * tolerance
51 | self.samples = TapeReader(progress=progress, cpufreq=cpufreq, maxlenT=maxlenT, leftChMix=leftChMix)
52 | self.debug = debug if debug is not None else 0
53 | self.verbose = verbose
54 | self.treshold = treshold
55 | self.tolerance = tolerance
56 | self.leaderMin = leaderMin
57 |
58 | def load(self, filename, startFrame=None, endFrame=None):
59 | try:
60 | self.samples.open(filename)
61 | self.samples.fileRange(startFrame, endFrame)
62 | tzx = TzxFile()
63 | while True:
64 | try:
65 | tzxbd = TzxbData()
66 | (tzxData, startPos, endPos) = self._loadBlock()
67 | tzxbd.setup(tzxData)
68 | tzx.blocks.append(tzxbd)
69 | if self.verbose:
70 | startMillis = self.samples.toMilliSeconds(startPos)
71 | startSecs = startMillis // 1000
72 | startMins = startSecs // 60
73 | print(('{:3d}:{:02d}.{:03d} {:9d} - {:9d}: {}').format(
74 | startMins,
75 | startSecs % 60,
76 | startMillis % 1000,
77 | startPos,
78 | endPos,
79 | str(tzxbd)
80 | ), file=sys.stderr)
81 | except BadBlock:
82 | continue # Try again with the next block
83 | except EOFError:
84 | break # we're done!
85 | finally:
86 | self.samples.close()
87 | return tzx
88 |
89 | def _loadBlock(self):
90 | tapCreator = TapCreator()
91 | if self.debug >= 2:
92 | tapCreator.callback = lambda val, crc, lng: \
93 | print(' > {:5d}: {:02x} {:c} CRC={:02x}'.format(
94 | lng,
95 | val,
96 | val if 0x20 <= val < 0x80 else 0x20,
97 | crc), file=sys.stderr)
98 | self.samples.invert = False
99 |
100 | # Wait for leader
101 | self.samples.nextRaisingEdge()
102 | length = self._testLeaderPulse()
103 | while length is None:
104 | self.samples.advance(self.samples.toFrames(self.leaderT / self.tolerance))
105 | self.samples.nextRaisingEdge()
106 | length = self._testLeaderPulse()
107 | leaderPos = self.lastPulse
108 |
109 | # Skip leader, wait for sync
110 | leaderLengths = deque([length], maxlen=max(self.leaderMin, 20))
111 | while True:
112 | length = self._testLeaderPulse()
113 | if length is not None:
114 | leaderLengths.append(length)
115 | continue
116 |
117 | if len(leaderLengths) >= self.leaderMin:
118 | expectedSyncT = 1.1 * (sum(leaderLengths) * self.syncT) / (len(leaderLengths) * self.leaderT)
119 | length = self._testSyncPulse(expectedSyncT)
120 | if length is not None:
121 | # Sync was found
122 | syncPos = self.lastPulse
123 | break
124 |
125 | # Leader was lost
126 | raise BadBlock()
127 |
128 | # Read data block
129 | expectedLowT = (sum(leaderLengths) * self.lowT) / (len(leaderLengths) * self.leaderT)
130 | expectedHighT = (sum(leaderLengths) * self.highT) / (len(leaderLengths) * self.leaderT)
131 | letMeGuess = False
132 |
133 | while True:
134 | lowLen = self._testBitPulse(expectedLowT, '0')
135 | highLen = self._testBitPulse(expectedHighT, '1')
136 |
137 | # We detected a bit for sure?
138 | if lowLen is not None and lowLen[0]:
139 | letMeGuess = True
140 | self._advance(False, lowLen[1])
141 | tapCreator.shift(False)
142 | continue
143 |
144 | if highLen is not None and highLen[0]:
145 | letMeGuess = True
146 | self._advance(True, highLen[1])
147 | tapCreator.shift(True)
148 | continue
149 |
150 | # We're not sure, but maybe we're lucky...
151 | if lowLen is not None and highLen is None:
152 | self._advance(False, lowLen[1], tag='gap')
153 | tapCreator.shift(False)
154 | continue
155 |
156 | if highLen is not None and lowLen is None:
157 | self._advance(True, highLen[1], tag='gap')
158 | tapCreator.shift(True)
159 | continue
160 |
161 | # Hope for a broken Low bit, but not too often...
162 | if lowLen is not None and highLen is not None and letMeGuess:
163 | letMeGuess = False
164 | self._advance(False, lowLen[1], tag='noise')
165 | tapCreator.shift(False)
166 | continue
167 |
168 | # Seems we have lost the bit stream...
169 | if len(tapCreator) <= 2:
170 | raise BadBlock
171 | tap = tapCreator.createTap()
172 | if self.debug >= 1:
173 | self._showBlock(tap, leaderPos, syncPos, self.samples.position())
174 | return (tap, leaderPos, self.samples.position())
175 |
176 | def _testLeaderPulse(self):
177 | self.samples.ensure()
178 | self.lastPulse = self.samples.position()
179 |
180 | # Convert range to samples
181 | minRange = self.samples.toFrames(self.leaderT / ( 1.3 * self.tolerance))
182 | maxRange = self.samples.toFrames(self.leaderT * ( 1.1 * self.tolerance))
183 |
184 | # Find end of half pulse
185 | startSign = sgn(self.samples[0])
186 | count = 1
187 | while sgn(self.samples[count]) == startSign:
188 | count += 1
189 | if count > maxRange:
190 | return None
191 |
192 | if not (minRange <= count <= maxRange):
193 | return None
194 |
195 | # Compute pulse duration in Z80 T-states
196 | length = self.samples.toTStates(count)
197 | if self.debug >= 3:
198 | print(' # {:5d} @{:n}~{:n}'.format(length, self.lastPulse, self.lastPulse + count), file=sys.stderr)
199 | self.samples.advance(count)
200 | return length
201 |
202 | def _testSyncPulse(self, tCycles):
203 | self.lastPulse = self.samples.position()
204 | self.samples.ensure()
205 |
206 | # Convert to samples
207 | frames = self.samples.toFrames(tCycles * 2)
208 | (minv, maxv, bias) = self.samples.minMaxAvg(frames)
209 |
210 | # Is amplitude above treshold?
211 | if abs(maxv - minv) < self.treshold:
212 | if self.debug >= 4:
213 | print(' ! - below treshold, {} < {}'.format(
214 | abs(maxv - minv),
215 | self.treshold), file=sys.stderr)
216 | return None
217 |
218 | # Find next zero crossing, normal signal
219 | self.samples.invert = False
220 | tag = '-'
221 | count = self._findZeroCrossing(frames, bias, tag)
222 | if not count:
223 | # Find next zero crossing, inverted signal
224 | self.samples.invert = True
225 | (minv, maxv, bias) = (-maxv, -minv, -bias)
226 | tag = '~'
227 | count = self._findZeroCrossing(frames, bias, tag)
228 | if not count:
229 | return None
230 |
231 | # Integrate both half waves
232 | countHalf = count // 2
233 | w1 = sum([self.samples[i] for i in range(0, countHalf)]) / countHalf
234 | w2 = sum([self.samples[i] for i in range(countHalf, count)]) / countHalf
235 |
236 | # Is it a full wave?
237 | if not (w1 < bias and w2 > bias and abs(w2 - w1) >= self.treshold / 2):
238 | if self.debug >= 4:
239 | print(' ! {} not a full wave, w1={} w2={} bias={}'.format(tag, w1, w2, bias), file=sys.stderr)
240 | return None
241 |
242 | # Success, this is a sync
243 | length = self.samples.toTStates(count / 2)
244 | if self.debug >= 3:
245 | print(' {} {:5d} @{:n}~{:n}'.format(tag, length, self.lastPulse, self.lastPulse + count), file=sys.stderr)
246 | self.samples.advance(count)
247 | return length
248 |
249 | def _testBitPulse(self, tCycles, tag):
250 | self.lastPulse = self.samples.position()
251 | self.samples.ensure()
252 |
253 | # Convert to samples
254 | frames = self.samples.toFrames(tCycles * 2)
255 | (minv, maxv, bias) = self.samples.minMaxAvg(frames)
256 |
257 | # Is amplitude above treshold?
258 | if abs(maxv - minv) < self.treshold:
259 | if self.debug >= 4:
260 | print(' ! {} below treshold, {} < {}'.format(
261 | tag,
262 | abs(maxv - minv),
263 | self.treshold), file=sys.stderr)
264 | return None
265 |
266 | # Find next zero crossing
267 | count = self._findZeroCrossing(frames, bias, tag)
268 | if not count:
269 | return None
270 |
271 | # Integrate both half waves
272 | countHalf = count // 2
273 | w1 = sum([self.samples[i] for i in range(0, countHalf)]) / countHalf
274 | w2 = sum([self.samples[i] for i in range(countHalf, count)]) / countHalf
275 |
276 | # Is it a full wave?
277 | if not (w1 < bias and w2 > bias and abs(w2 - w1) >= self.treshold):
278 | if self.debug >= 4:
279 | print(' ! {} not a full wave, w1={} w2={} bias={}'.format(tag, w1, w2, bias), file=sys.stderr)
280 | return (False, count)
281 |
282 | # Success, this is a bit
283 | return (True, count)
284 |
285 | def _advance(self, bit, count, tag=''):
286 | self.samples.advance(count)
287 | if self.debug >= 3:
288 | length = self.samples.toTStates(count / 2)
289 | print(' {} {:5d} @{:n}~{:n} {}'.format(1 if bit else 0, length, self.lastPulse, self.lastPulse + count, tag), file=sys.stderr)
290 |
291 | def _findZeroCrossing(self, frames, bias, tag):
292 | count = frames
293 | countL = int(frames / self.tolerance)
294 | countH = int(frames * self.tolerance)
295 |
296 | while self.samples[count] <= bias:
297 | count -= 1
298 | if count < countL:
299 | if self.debug >= 4:
300 | print(' ! {} no zero crossing detected, count={}, bias={}'.format(tag, count, bias), file=sys.stderr)
301 | return None
302 |
303 | while self.samples[count] > bias:
304 | count += 1
305 | if count > countH:
306 | if self.debug >= 4:
307 | print(' ! {} no wave end in range, count={}, bias={}'.format(tag, count, bias), file=sys.stderr)
308 | return None
309 |
310 | return count
311 |
312 | def _showBlock(self, tap, leaderPos, syncPos, endPos):
313 | if isinstance(tap, TapHeader):
314 | print('=== {}: {}'.format(tap.type(), tap.name()), file=sys.stderr)
315 | if tap.typeId() == 3:
316 | print(' Start: {}, Expected length: {}'.format(tap.param1(), tap.length()), file=sys.stderr)
317 | else:
318 | print(' Expected length: {}'.format(tap.length()), file=sys.stderr)
319 | else:
320 | print('--- data', file=sys.stderr)
321 | print(' Length: {}'.format(tap.length()), file=sys.stderr)
322 |
323 | if not tap.valid():
324 | print(' CRC ERROR!', file=sys.stderr)
325 |
326 | print(' Leader: @{:n}, Sync: @{:n}, End: @{:n}'.format(leaderPos, syncPos, endPos), file=sys.stderr)
327 |
328 |
329 |
330 | class TapeReader():
331 | def __init__(self, progress=None, cpufreq=3500000, maxlenT=6000, leftChMix=0.5):
332 | self.cpufreq = cpufreq
333 | self.progress = progress
334 | self.maxlenT = maxlenT
335 | self.invert = False
336 | self.startFrame = None
337 | self.endFrame = None
338 | self.leftChMix = leftChMix
339 |
340 | def open(self, filename):
341 | """ Opens the given WAV file name """
342 | self.wav = wave.open(filename, 'r')
343 | self.frameCount = 0
344 | self.readFrame = self._createReader()
345 | self.bytesPerFrame = self.wav.getnchannels() * self.wav.getsampwidth()
346 | self.maxlen = self.toFrames(self.maxlenT)
347 | self.samples = deque(maxlen=self.maxlen)
348 |
349 | def fileRange(self, startFrame, endFrame):
350 | self.startFrame = startFrame
351 | self.endFrame = endFrame
352 |
353 | def close(self):
354 | """ Closes the tape reader """
355 | if self.progress is not None:
356 | self.progress(self.wav.getnframes(), self.wav.getnframes())
357 | self.wav.close()
358 |
359 | def __len__(self):
360 | """ Current length of sample buffer """
361 | return len(self.samples)
362 |
363 | def __getitem__(self, ix):
364 | """ Gets the sample at given index """
365 | return self.samples[ix] if not self.invert else -self.samples[ix]
366 |
367 | def position(self):
368 | """ Returns current frame position """
369 | return self.frameCount
370 |
371 | def ensure(self, needed=None):
372 | """ Ensures buffer is filled with sufficient samples """
373 | if self.startFrame is not None and self.frameCount < self.startFrame:
374 | skip = self.startFrame - self.frameCount
375 | self.frameCount = self.startFrame
376 | self.startFrame = None
377 | while skip > 0:
378 | sf = skip if skip < 1000 else 1000
379 | skip -= sf
380 | frames = self.wav.readframes(sf)
381 | if not frames:
382 | raise EOFError()
383 |
384 | if needed is not None and len(self.samples) >= needed:
385 | return # sufficient data available
386 |
387 | missing = self.samples.maxlen - len(self.samples)
388 | if missing <= 0:
389 | return # buffer is filled to maximum
390 |
391 | frames = self.wav.readframes(missing)
392 | if not frames:
393 | raise EOFError()
394 |
395 | for ix in range(0, len(frames), self.bytesPerFrame):
396 | self.samples.append(self.readFrame(frames[ix:ix+self.bytesPerFrame]))
397 |
398 | def advance(self, frames):
399 | """ Advance number of frames """
400 | if frames == 0:
401 | return
402 | self.ensure(frames)
403 | for i in range(0, frames):
404 | self.samples.popleft()
405 | self.frameCount += frames
406 | if self.endFrame is not None and self.frameCount > self.endFrame:
407 | raise EOFError()
408 | if self.progress is not None:
409 | self.progress(self.frameCount, self.wav.getnframes())
410 |
411 | def minMaxAvg(self, frames):
412 | """ Returns a tuple of minimum, maximum and average of given range """
413 | self.ensure(frames)
414 | data = [self[i] for i in range(0, frames)]
415 | return (min(data), max(data), sum(data) / frames)
416 |
417 | def nextRaisingEdge(self):
418 | """ Finds the next raising edge """
419 | self.ensure(2)
420 | while not (self[0] < 0 and self[1] >= 0):
421 | self.advance(1)
422 | self.ensure(2)
423 | self.advance(1) # position on the first positive value
424 |
425 | def toTStates(self, frames):
426 | """ Converts number of frames to T-States """
427 | return int(frames * self.cpufreq / self.wav.getframerate())
428 |
429 | def toMilliSeconds(self, frames):
430 | """ Converts number of frames to seconds """
431 | return int(frames * 1000 / self.wav.getframerate())
432 |
433 | def toFrames(self, tCycles):
434 | """ Converts T-States to number of frames """
435 | return int(tCycles * self.wav.getframerate() / self.cpufreq)
436 |
437 | def _createReader(self):
438 | """ Returns a function that converts frame byte array to sample data """
439 | channels = self.wav.getnchannels()
440 | bpc = self.wav.getsampwidth()
441 | if bpc == 2:
442 | if channels == 2: return lambda f: unpackStereo(f, 'h', self.leftChMix)
443 | elif channels == 1: return lambda f: unpackMono(f, 'h')
444 | else: raise IOError('Cannot handle WAV files with {} channels'.format(channels))
445 | elif bpc == 1:
446 | if channels == 2: return lambda f: unpackStereo(f, 'b', self.leftChMix) * 256
447 | elif channels == 1: return lambda f: unpackMono(f, 'b') * 256
448 | else: raise IOError('Cannot handle WAV files with {} channels'.format(channels))
449 | else:
450 | raise IOError('Cannot handle WAV files with {} bits per channel'.format(bpc * 8))
451 |
452 |
453 |
454 | class TapCreator():
455 | def __init__(self, callback=None):
456 | self.data = bytearray()
457 | self.crc = 0
458 | self.shifter = 0
459 | self.bits = 0
460 | self.callback = callback
461 |
462 | def shift(self, bit):
463 | """ Shifts in a bit """
464 | self.shifter <<= 1
465 | if bit: self.shifter |= 1
466 |
467 | self.bits += 1
468 | if self.bits == 8:
469 | self.crc ^= self.shifter
470 | self.data.append(self.shifter)
471 | if self.callback is not None:
472 | self.callback(self.shifter, self.crc, len(self.data))
473 | self.shifter = 0
474 | self.bits = 0
475 |
476 | def __len__(self):
477 | """ Current length of collected data, in bytes """
478 | return len(self.data)
479 |
480 | def createTap(self):
481 | """ Creates a TapFile from the collected data """
482 | return TapFile.create(self.data)
483 |
484 |
485 |
486 | class BadBlock(Exception):
487 | """ Cannot read this block, try the next one. """
488 | pass
489 |
--------------------------------------------------------------------------------
/tzxlib/saver.py:
--------------------------------------------------------------------------------
1 | #
2 | # tzxtools - a collection for processing tzx files
3 | #
4 | # Copyright (C) 2021 Richard "Shred" Körber
5 | # https://codeberg.org/shred/tzxtools
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 |
21 | from tzxlib.tapfile import TapFile
22 |
23 | BYTE_ORDER = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]
24 |
25 | class TapeSaver():
26 | def __init__(self, cpufreq=3500000):
27 | self.cpufreq = cpufreq
28 | self.currentState = False
29 |
30 | def pulse(self, length):
31 | self.currentState = not self.currentState
32 | yield self.tStatesToNs(length)
33 |
34 | def tone(self, length, number):
35 | lstates = self.tStatesToNs(length)
36 | for _ in range(number // 2):
37 | yield lstates
38 | yield lstates
39 | if number % 2 == 1:
40 | self.currentState = not self.currentState
41 | yield lstates
42 |
43 | def saveTapFile(self, tap, pilotPulse=2168, syncHiPulse=667, syncLoPulse=735,
44 | zeroPulse=855, onePulse=1710, leaderTone=None, finalBits=8):
45 | # Generate leader tone
46 | if pilotPulse is not None:
47 | lpulse = self.tStatesToNs(pilotPulse)
48 | for _ in range(leaderTone if leaderTone is not None else tap.leaderCycles() // 2):
49 | yield lpulse
50 | yield lpulse
51 |
52 | # Generate sync pulse
53 | if syncHiPulse is not None:
54 | yield self.tStatesToNs(syncHiPulse)
55 | if syncLoPulse is not None:
56 | yield self.tStatesToNs(syncLoPulse)
57 |
58 | # Send all bits
59 | counter = finalBits
60 | lone = self.tStatesToNs(onePulse)
61 | lzero = self.tStatesToNs(zeroPulse)
62 | for i in range(len(tap.data)):
63 | b = tap.data[i]
64 | for m in BYTE_ORDER:
65 | if b & m != 0:
66 | yield lone
67 | yield lone
68 | else:
69 | yield lzero
70 | yield lzero
71 | if i == len(tap.data)-1:
72 | counter -= 1
73 | if counter <= 0:
74 | break
75 |
76 | def saveDirect(self, data, finalBits, tstates):
77 | if len(data) == 0:
78 | return
79 | counter = finalBits
80 | lstate = self.tStatesToNs(tstates)
81 | for i in range(len(data)):
82 | b = data[i]
83 | for m in BYTE_ORDER:
84 | newState = b & m != 0
85 | if newState == self.currentState:
86 | yield 0
87 | yield lstate
88 | self.currentState = newState
89 | if i == len(data)-1:
90 | counter -= 1
91 | if counter <= 0:
92 | break
93 |
94 | def pause(self, milliseconds):
95 | if milliseconds > 0:
96 | if not self.currentState:
97 | yield 0
98 | self.currentState = False
99 | yield milliseconds * 1000000
100 |
101 | def tStatesToNs(self, tstates):
102 | return tstates * 1000000000 // self.cpufreq
103 |
--------------------------------------------------------------------------------
/tzxlib/tapfile.py:
--------------------------------------------------------------------------------
1 | #
2 | # tzxtools - a collection for processing tzx files
3 | #
4 | # Copyright (C) 2016 Richard "Shred" Körber
5 | # https://codeberg.org/shred/tzxtools
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 | #
20 |
21 | from struct import pack, unpack
22 |
23 | from tzxlib.convert import convert
24 |
25 | class TapFile():
26 | def create(data):
27 | if len(data) == 19 and data[0] == 0x00:
28 | return TapHeader(data)
29 | else:
30 | return TapData(data)
31 |
32 | def valid(self):
33 | val = 0;
34 | for b in self.data:
35 | val ^= b
36 | return val == 0
37 |
38 | def body(self):
39 | return self.data[1:-1]
40 |
41 | def leaderCycles(self):
42 | return 3223
43 |
44 | def writeBody(self, out):
45 | out.write(self.body())
46 |
47 | def write(self, tzx):
48 | tzx.write(self.data)
49 |
50 | def writeFragment(self, tzx):
51 | tzx.write(pack('.
19 | #
20 |
21 | from struct import pack, unpack
22 | import os
23 |
24 | from tzxlib.tapfile import TapFile
25 | from tzxlib.saver import TapeSaver
26 |
27 | class TzxbBlock():
28 | blockTypes = {
29 | 0x10: lambda: TzxbData(),
30 | 0x11: lambda: TzxbTurboData(),
31 | 0x12: lambda: TzxbPureTone(),
32 | 0x13: lambda: TzxbPulseSequence(),
33 | 0x14: lambda: TzxbPureData(),
34 | 0x15: lambda: TzxbDirectRecording(),
35 | 0x16: lambda: TzxbC64Data(),
36 | 0x17: lambda: TzxbC64TurboData(),
37 | 0x18: lambda: TzxbCswRecording(),
38 | 0x19: lambda: TzxbGeneralizedData(),
39 | 0x20: lambda: TzxbPause(),
40 | 0x21: lambda: TzxbGroupStart(),
41 | 0x22: lambda: TzxbGroupEnd(),
42 | 0x23: lambda: TzxbJumpTo(),
43 | 0x24: lambda: TzxbLoopStart(),
44 | 0x25: lambda: TzxbLoopEnd(),
45 | 0x26: lambda: TzxbCallSequence(),
46 | 0x27: lambda: TzxbReturn(),
47 | 0x28: lambda: TzxbSelect(),
48 | 0x2A: lambda: TzxbStopTape48k(),
49 | 0x2B: lambda: TzxbSetSignalLevel(),
50 | 0x30: lambda: TzxbTextDescription(),
51 | 0x31: lambda: TzxbMessage(),
52 | 0x32: lambda: TzxbArchiveInfo(),
53 | 0x33: lambda: TzxbHardwareType(),
54 | 0x34: lambda: TzxbEmulationInfo(),
55 | 0x35: lambda: TzxbCustomInfo(),
56 | 0x40: lambda: TzxbSnapshot(),
57 | 0x4B: lambda: TzxbKansasCityStandard(),
58 | 0x5A: lambda: TzxbGlue(),
59 | }
60 |
61 | def createBlock(type):
62 | if not type in TzxbBlock.blockTypes:
63 | raise IOError('Unknown block type %02x' % (type))
64 | clazz = TzxbBlock.blockTypes[type]
65 | return clazz()
66 |
67 | def __init__(self):
68 | self.data = bytearray()
69 |
70 | def read(self, tzx):
71 | self.data = tzx.read(0x04)
72 | len = unpack(' 2000
160 | and bits == 8):
161 | # Standard size and standard timing, convert to Standard Speed Data Block
162 | result = TzxbData()
163 | result.data = self.data[0x0D:0x11]
164 | result.tap = self.tap
165 | return result
166 | return self
167 |
168 | def dump(self):
169 | return self.tap.body()
170 |
171 | def playback(self, saver:TapeSaver):
172 | (pilot, sync1, sync2, zerobit, onebit, tone, bits) = unpack('.
19 | #
20 |
21 | import io
22 | from struct import unpack
23 | import sys
24 |
25 | from tzxlib.tapfile import TapFile
26 | from tzxlib.tzxblocks import TzxbBlock, TzxbData
27 |
28 | class TzxFile():
29 | MAJOR = 1
30 | MINOR = 20
31 |
32 | def __init__(self):
33 | self._reset()
34 |
35 | def _reset(self):
36 | self.version = (TzxFile.MAJOR, TzxFile.MINOR)
37 | self.blocks = list()
38 |
39 | def read(self, input):
40 | self._reset()
41 | inf = input
42 | if isinstance(inf, io.TextIOWrapper):
43 | inf = inf.buffer
44 | with io.BufferedReader(inf) if isinstance(inf, io.IOBase) else open(inf, 'rb') as tzx:
45 | identifier = tzx.peek(8)
46 | if identifier[0:7].decode('ascii') != 'ZXTape!' or identifier[7] != 0x1A:
47 | self._readTap(tzx)
48 | else:
49 | self._readTzx(tzx)
50 |
51 | def write(self, output):
52 | outf = output
53 | if isinstance(outf, io.TextIOWrapper):
54 | outf = outf.buffer
55 | with outf if isinstance(outf, io.IOBase) else open(outf, 'wb') as tzx:
56 | self._writeHeader(tzx)
57 | for b in self.blocks:
58 | b.write(tzx)
59 |
60 | def _readTap(self, tap):
61 | self.version = (self.MAJOR, self.MINOR)
62 | while True:
63 | blockLen = tap.read(2)
64 | if not blockLen: break
65 | len = unpack('.
20 | #
21 |
22 | from struct import unpack
23 |
24 | def disassemble(data, pc, org=0):
25 | step = 0
26 | ix = False
27 | iy = False
28 | iindex = None
29 |
30 | while pc + step < len(data):
31 | op = data[pc + step]
32 | step += 1
33 | if op == 0xDD:
34 | op2 = data[pc + step]
35 | if op2 == 0x00:
36 | step += 1
37 | ins = "exit" # cspect emulator pseudo command
38 | break
39 | if op2 == 0x01:
40 | step += 1
41 | ins = "break" # cspect emulator pseudo command
42 | break
43 | ix = True
44 | iy = False
45 | elif op == 0xFD:
46 | iy = True
47 | ix = False
48 | elif op == 0xED:
49 | ix = False
50 | iy = False
51 | op = data[pc + step]
52 | step += 1
53 | ins = decodeEd(op)
54 | break
55 | elif op == 0xCB:
56 | if ix or iy:
57 | iindex = unpack('b', data[pc + step:pc + step + 1])[0]
58 | step += 1
59 | op = data[pc + step]
60 | step += 1
61 | if ix or iy:
62 | ins = decodeCbWithIndex(op)
63 | else:
64 | ins = decodeCb(op)
65 | break
66 | else:
67 | if op == 0xEB:
68 | ix = False
69 | iy = False
70 | ins = INSTRUCTIONS[op]
71 | break
72 |
73 | if ix:
74 | if '(HL)' in ins and ins != 'jp (HL)':
75 | if iindex is None:
76 | iindex = unpack('b', data[pc + step:pc + step + 1])[0]
77 | step += 1
78 | ins = ins.replace('(HL)', '(IX%+d)' % (iindex))
79 | else:
80 | ins = ins.replace('HL', 'IX').replace('H', 'IXH').replace('L', 'IXL')
81 | ins = ins.replace('##', '**')
82 |
83 | if iy:
84 | if '(HL)' in ins and ins != 'jp (HL)':
85 | if iindex is None:
86 | iindex = unpack('b', data[pc + step:pc + step + 1])[0]
87 | step += 1
88 | ins = ins.replace('(HL)', '(IY%+d)' % (iindex))
89 | else:
90 | ins = ins.replace('HL', 'IY').replace('H', 'IYH').replace('L', 'IYL')
91 | ins = ins.replace('##', '**')
92 |
93 | ins = ins.lower()
94 |
95 | if '$' in ins:
96 | val = unpack('B', data[pc + step:pc + step + 1])[0]
97 | ins = ins.replace('$', '$%02X' % (val))
98 | step += 1
99 |
100 | if '^^' in ins:
101 | raw = data[pc + step:pc + step + 2]
102 | if -2048 <= unpack('>h', raw)[0] <= 2048:
103 | ins = ins.replace('^^', '%d' % (unpack('>h', raw)[0]))
104 | else:
105 | ins = ins.replace('^^', '$%04X' % (unpack('>H', raw)[0]))
106 | step += 2
107 |
108 | if '##' in ins:
109 | raw = data[pc + step:pc + step + 2]
110 | if -2048 <= unpack(' 16 bit signed decimal
191 | # # -> 8 bit signed decimal
192 | # ** -> 16 bit unsigned hex
193 | # * -> 8 bit unsigned hex
194 | # % -> 8 bit relative address
195 | # $ -> 8 bit ZX Spectrum Next register address
196 | # ^^ -> 16 bit signed decimal, big endian (ZX Spectrum Next proprietary)
197 |
198 | INSTRUCTIONS = [
199 | 'nop', # 00
200 | 'ld BC,##', # 01
201 | 'ld (BC),A', # 02
202 | 'inc BC', # 03
203 | 'inc B', # 04
204 | 'dec B', # 05
205 | 'ld B,#', # 06
206 | 'rlca', # 07
207 | "ex AF,AF'", # 08
208 | 'add HL,BC', # 09
209 | 'ld A,(BC)', # 0A
210 | 'dec BC', # 0B
211 | 'inc C', # 0C
212 | 'dec C', # 0D
213 | 'ld C,#', # 0E
214 | 'rrca', # 0F
215 | 'djnz %', # 10
216 | 'ld DE,##', # 11
217 | 'ld (DE),A', # 12
218 | 'inc DE', # 13
219 | 'inc D', # 14
220 | 'dec D', # 15
221 | 'ld D,#', # 16
222 | 'rla', # 17
223 | 'jr %', # 18
224 | 'add HL,DE', # 19
225 | 'ld A,(DE)', # 1A
226 | 'dec DE', # 1B
227 | 'inc E', # 1C
228 | 'dec E', # 1D
229 | 'ld E,#', # 1E
230 | 'rra', # 1F
231 | 'jr nz,%', # 20
232 | 'ld HL,##', # 21
233 | 'ld (**),HL', # 22
234 | 'inc HL', # 23
235 | 'inc H', # 24
236 | 'dec H', # 25
237 | 'ld H,#', # 26
238 | 'daa', # 27
239 | 'jr z,%', # 28
240 | 'add HL,HL', # 29
241 | 'ld HL,(**)', # 2A
242 | 'dec HL', # 2B
243 | 'inc L', # 2C
244 | 'dec L', # 2D
245 | 'ld L,#', # 2E
246 | 'cpl', # 2F
247 | 'jr nc,%', # 30
248 | 'ld SP,**', # 31
249 | 'ld (**),A', # 32
250 | 'inc SP', # 33
251 | 'inc (HL)', # 34
252 | 'dec (HL)', # 35
253 | 'ld (HL),#', # 36
254 | 'scf', # 37
255 | 'jr c,%', # 38
256 | 'add HL,SP', # 39
257 | 'ld A,(**)', # 3A
258 | 'dec SP', # 3B
259 | 'inc A', # 3C
260 | 'dec A', # 3D
261 | 'ld A,#', # 3E
262 | 'ccf', # 3F
263 | 'ld B,B', # 40
264 | 'ld B,C', # 41
265 | 'ld B,D', # 42
266 | 'ld B,E', # 43
267 | 'ld B,H', # 44
268 | 'ld B,L', # 45
269 | 'ld B,(HL)', # 46
270 | 'ld B,A', # 47
271 | 'ld C,B', # 48
272 | 'ld C,C', # 49
273 | 'ld C,D', # 4A
274 | 'ld C,E', # 4B
275 | 'ld C,H', # 4C
276 | 'ld C,L', # 4D
277 | 'ld C,(HL)', # 4E
278 | 'ld C,A', # 4F
279 | 'ld D,B', # 50
280 | 'ld D,C', # 51
281 | 'ld D,D', # 52
282 | 'ld D,E', # 53
283 | 'ld D,H', # 54
284 | 'ld D,L', # 55
285 | 'ld D,(HL)', # 56
286 | 'ld D,A', # 57
287 | 'ld E,B', # 58
288 | 'ld E,C', # 59
289 | 'ld E,D', # 5A
290 | 'ld E,E', # 5B
291 | 'ld E,H', # 5C
292 | 'ld E,L', # 5D
293 | 'ld E,(HL)', # 5E
294 | 'ld E,A', # 5F
295 | 'ld H,B', # 60
296 | 'ld H,C', # 61
297 | 'ld H,D', # 62
298 | 'ld H,E', # 63
299 | 'ld H,H', # 64
300 | 'ld H,L', # 65
301 | 'ld H,(HL)', # 66
302 | 'ld H,A', # 67
303 | 'ld L,B', # 68
304 | 'ld L,C', # 69
305 | 'ld L,D', # 6A
306 | 'ld L,E', # 6B
307 | 'ld L,H', # 6C
308 | 'ld L,L', # 6D
309 | 'ld L,(HL)', # 6E
310 | 'ld L,A', # 6F
311 | 'ld (HL),B', # 70
312 | 'ld (HL),C', # 71
313 | 'ld (HL),D', # 72
314 | 'ld (HL),E', # 73
315 | 'ld (HL),H', # 74
316 | 'ld (HL),L', # 75
317 | 'halt', # 76
318 | 'ld (HL),A', # 77
319 | 'ld A,B', # 78
320 | 'ld A,C', # 79
321 | 'ld A,D', # 7A
322 | 'ld A,E', # 7B
323 | 'ld A,H', # 7C
324 | 'ld A,L', # 7D
325 | 'ld A,(HL)', # 7E
326 | 'ld A,A', # 7F
327 | 'add A,B', # 80
328 | 'add A,C', # 81
329 | 'add A,D', # 82
330 | 'add A,E', # 83
331 | 'add A,H', # 84
332 | 'add A,L', # 85
333 | 'add A,(HL)', # 86
334 | 'add A,A', # 87
335 | 'adc A,B', # 88
336 | 'adc A,C', # 89
337 | 'adc A,D', # 8A
338 | 'adc A,E', # 8B
339 | 'adc A,H', # 8C
340 | 'adc A,L', # 8D
341 | 'adc A,(HL)', # 8E
342 | 'adc A,A', # 8F
343 | 'sub B', # 90
344 | 'sub C', # 91
345 | 'sub D', # 92
346 | 'sub E', # 93
347 | 'sub H', # 94
348 | 'sub L', # 95
349 | 'sub (HL)', # 96
350 | 'sub A', # 97
351 | 'sbc A,B', # 98
352 | 'sbc A,C', # 99
353 | 'sbc A,D', # 9A
354 | 'sbc A,E', # 9B
355 | 'sbc A,H', # 9C
356 | 'sbc A,L', # 9D
357 | 'sbc A,(HL)', # 9E
358 | 'sbc A,A', # 9F
359 | 'and B', # A0
360 | 'and C', # A1
361 | 'and D', # A2
362 | 'and E', # A3
363 | 'and H', # A4
364 | 'and L', # A5
365 | 'and (HL)', # A6
366 | 'and A', # A7
367 | 'xor B', # A8
368 | 'xor C', # A9
369 | 'xor D', # AA
370 | 'xor E', # AB
371 | 'xor H', # AC
372 | 'xor L', # AD
373 | 'xor (HL)', # AE
374 | 'xor A', # AF
375 | 'or B', # B0
376 | 'or C', # B1
377 | 'or D', # B2
378 | 'or E', # B3
379 | 'or H', # B4
380 | 'or L', # B5
381 | 'or (HL)', # B6
382 | 'or A', # B7
383 | 'cp B', # B8
384 | 'cp C', # B9
385 | 'cp D', # BA
386 | 'cp E', # BB
387 | 'cp H', # BC
388 | 'cp L', # BD
389 | 'cp (HL)', # BE
390 | 'cp A', # BF
391 | 'ret nz', # C0
392 | 'pop BC', # C1
393 | 'jp nz,**', # C2
394 | 'jp **', # C3
395 | 'call nz,**', # C4
396 | 'push BC', # C5
397 | 'add A,#', # C6
398 | 'rst 00h', # C7
399 | 'ret z', # C8
400 | 'ret', # C9
401 | 'jp z,**', # CA
402 | None, # CB: Bit operations
403 | 'call z,**', # CC
404 | 'call **', # CD
405 | 'adc A,#', # CE
406 | 'rst 08h', # CF
407 | 'ret nc', # D0
408 | 'pop DE', # D1
409 | 'jp nc,**', # D2
410 | 'out (*),A', # D3
411 | 'call nc,**', # D4
412 | 'push DE', # D5
413 | 'sub #', # D6
414 | 'rst 10h', # D7
415 | 'ret c', # D8
416 | 'exx', # D9
417 | 'jp c,**', # DA
418 | 'in A,(*)', # DB
419 | 'call c,**', # DC
420 | None, # DD: IX registers
421 | 'sbc A,#', # DE
422 | 'rst 18h', # DF
423 | 'ret po', # E0
424 | 'pop HL', # E1
425 | 'jp po,**', # E2
426 | 'ex (SP),HL', # E3
427 | 'call po,**', # E4
428 | 'push HL', # E5
429 | 'and *', # E6
430 | 'rst 20h', # E7
431 | 'ret pe', # E8
432 | 'jp (HL)', # E9
433 | 'jp pe,**', # EA
434 | 'ex DE,HL', # EB
435 | 'call pe,**', # EC
436 | None, # ED: Extended instructions
437 | 'xor *', # EE
438 | 'rst 28h', # EF
439 | 'ret p', # F0
440 | 'pop AF', # F1
441 | 'jp p,**', # F2
442 | 'di', # F3
443 | 'call p,**', # F4
444 | 'push AF', # F5
445 | 'or *', # F6
446 | 'rst 30h', # F7
447 | 'ret m', # F8
448 | 'ld SP,HL', # F9
449 | 'jp m,**', # FA
450 | 'ei', # FB
451 | 'call m,**', # FC
452 | None, # FD: IY registers
453 | 'cp #', # FE
454 | 'rst 38h' # FF
455 | ]
456 |
457 | # These are ZX Spectrum Next proprietary op codes!
458 | INSTRUCTIONS_ED_2 = [
459 | None, # 20
460 | None, # 21
461 | None, # 22
462 | 'swapnib', # 23
463 | 'mirror A', # 24
464 | None, # 25
465 | None, # 26
466 | 'test #', # 27
467 | 'bsla DE,B', # 28
468 | 'bsra DE,B', # 29
469 | 'bsrl DE,B', # 2A
470 | 'bsrf DE,B', # 2B
471 | 'brlc DE,B', # 2C
472 | None, # 2D
473 | None, # 2E
474 | None, # 2F
475 | 'mul D,E', # 30
476 | 'add HL,A', # 31
477 | 'add DE,A', # 32
478 | 'add BC,A', # 33
479 | 'add HL,##', # 34
480 | 'add DE,##', # 35
481 | 'add BC,##', # 36
482 | None, # 37
483 | None, # 38
484 | None, # 39
485 | None, # 3A
486 | None, # 3B
487 | None, # 3C
488 | None, # 3D
489 | None, # 3E
490 | None, # 3F
491 | ]
492 |
493 | INSTRUCTIONS_ED_4 = [
494 | 'in B,(C)', # 40
495 | 'out (C),B', # 41
496 | 'sbc HL,BC', # 42
497 | 'ld (**),BC', # 43
498 | 'neg', # 44
499 | 'retn', # 45
500 | 'im 0', # 46
501 | 'ld I,A', # 47
502 | 'in C,(C)', # 48
503 | 'out (C),C', # 49
504 | 'adc HL,BC', # 4A
505 | 'ld BC,(**)', # 4B
506 | 'neg', # 4C Illegal opcode
507 | 'reti', # 4D
508 | None, # 4E
509 | 'ld R,A', # 4F
510 | 'in D,(C)', # 50
511 | 'out (C),D', # 51
512 | 'sbc HL,DE', # 52
513 | 'ld (**),DE', # 53
514 | 'neg', # 54 Illegal opcode
515 | 'retn', # 55
516 | 'im 1', # 56
517 | 'ld A,I', # 57
518 | 'in E,(C)', # 58
519 | 'out (C),E', # 59
520 | 'adc HL,DE', # 5A
521 | 'ld DE,(**)', # 5B
522 | 'neg', # 5C Illegal opcode
523 | 'retn', # 5D
524 | 'im 2', # 5E
525 | 'ld A,R', # 5F
526 | 'in H,(C)', # 60
527 | 'out (C),H', # 61
528 | 'sbc HL,HL', # 62
529 | 'ld (**),HL', # 63 Illegal opcode
530 | 'neg', # 64 Illegal opcode
531 | 'retn', # 65
532 | 'im 0', # 66
533 | 'rrd', # 67
534 | 'in L,(C)', # 68
535 | 'out (C),L', # 69
536 | 'adc HL,HL', # 6A
537 | 'ld HL,(**)', # 6B Illegal opcode
538 | 'neg', # 6C Illegal opcode
539 | 'retn', # 6D
540 | None, # 6E
541 | 'rld', # 6F
542 | 'in (C)', # 70 Illegal opcode
543 | 'out (C),0', # 71 Illegal opcode
544 | 'sbc HL,SP', # 72
545 | 'ld (**),SP', # 73
546 | 'neg', # 74 Illegal opcode
547 | 'retn', # 75
548 | 'im 1', # 76
549 | None, # 77
550 | 'in A,(C)', # 78
551 | 'out (C),A', # 79
552 | 'adc HL,SP', # 7A
553 | 'ld SP,(**)', # 7B
554 | 'neg', # 7C Illegal opcode
555 | 'retn', # 7D
556 | 'im 2', # 7E
557 | None, # 7F
558 | ]
559 |
560 | # These are ZX Spectrum Next proprietary op codes!
561 | INSTRUCTIONS_ED_9 = [
562 | 'outinb', # 90
563 | 'nextreg $,#', # 91
564 | 'nextreg $,A', # 92
565 | 'pixeldn', # 93
566 | 'pixelad', # 94
567 | 'setae', # 95
568 | None, # 96
569 | None, # 97
570 | 'jp (C)', # 98
571 | None, # 99
572 | None, # 9A
573 | None, # 9B
574 | None, # 9C
575 | None, # 9D
576 | None, # 9E
577 | None, # 9F
578 | ]
579 |
580 | INSTRUCTIONS_ED_A = [
581 | 'ldi', # A0
582 | 'cpi', # A1
583 | 'ini', # A2
584 | 'outi', # A3
585 | 'ldix', # A4 - ZX Spectrum Next op code
586 | 'ldws', # A5 - ZX Spectrum Next op code
587 | None, # A6
588 | None, # A7
589 | 'ldd', # A8
590 | 'cpd', # A9
591 | 'ind', # AA
592 | 'outd', # AB
593 | 'lddx', # AC - ZX Spectrum Next op code
594 | None, # AD
595 | None, # AE
596 | None, # AF
597 | 'ldir', # B0
598 | 'cpir', # B1
599 | 'inir', # B2
600 | 'otir', # B3
601 | 'ldirx', # B4 - ZX Spectrum Next op code
602 | None, # B5
603 | "ldirscale", # B6 - ZX Spectrum Next op code (considered)
604 | 'ldpirx', # B7 - ZX Spectrum Next op code
605 | 'lddr', # B8
606 | 'cpdr', # B9
607 | 'indr', # BA
608 | 'otdr', # BB
609 | 'lddrx', # BC - ZX Spectrum Next op code
610 | None, # BD
611 | None, # BE
612 | None, # BF
613 | ]
614 |
615 | INSTRUCTIONS_CB = [
616 | 'rlc',
617 | 'rrc',
618 | 'rl',
619 | 'rr',
620 | 'sla',
621 | 'sra',
622 | 'sll', # Illegal opcode
623 | 'srl',
624 | ]
625 |
626 | REGISTER = [
627 | 'B', 'C', 'D', 'E', 'H', 'L', '(HL)', 'A'
628 | ]
629 |
--------------------------------------------------------------------------------
/tzxtools/__init__.py:
--------------------------------------------------------------------------------
1 | name = "tzxtools"
2 |
--------------------------------------------------------------------------------
/tzxtools/tzxcat.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2018 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import io
24 | import sys
25 |
26 | from tzxlib.tzxfile import TzxFile
27 | from tzxlib.tapfile import TapHeader
28 | from tzxlib.convert import convertToText
29 | from tzxlib.convert import convertToBasic
30 | from tzxlib.convert import convertToDump
31 | from tzxlib.convert import convertToAssembler
32 | from tzxlib.convert import convertToScreen
33 |
34 | def writeBlock(out, dump, converter, skip, length, org):
35 | if skip:
36 | if 0 <= skip < len(dump):
37 | dump = dump[skip:]
38 | else:
39 | dump = []
40 | if length:
41 | if 0 <= length < len(dump):
42 | dump = dump[:length]
43 | if converter:
44 | dump = converter(dump, out, org)
45 | return dump
46 |
47 | def writeSingleBlock(tzx, out, index, writer, skipNotDumpable=False):
48 | if index < 0 or index >= len(tzx.blocks):
49 | print('Error: Block %d out of range' % (index), file=sys.stderr)
50 | exit(1)
51 | b = tzx.blocks[index]
52 | d = b.dump()
53 | if d is None:
54 | if skipNotDumpable:
55 | return
56 | else:
57 | print('Error: Block %d has no data content' % (index), file=sys.stderr)
58 | exit(1)
59 | if hasattr(b, 'tap') and not b.tap.valid():
60 | print('Warning: Block %d has bad CRC' % (index), file=sys.stderr)
61 | writer(out, d, findOrg(tzx, index))
62 |
63 | def writeAllBlocks(tzx, out, writer):
64 | for i in range(len(tzx.blocks)):
65 | writeSingleBlock(tzx, out, i, writer, True)
66 |
67 | def findOrg(tzx, index):
68 | if index > 1:
69 | b = tzx.blocks[index - 1]
70 | if hasattr(b, 'tap'):
71 | if isinstance(b.tap, TapHeader) and b.tap.typeId() == 3:
72 | return b.tap.param1()
73 | return None
74 |
75 | def main():
76 | parser = argparse.ArgumentParser(description='Write data block content')
77 | parser.add_argument('file',
78 | nargs='?',
79 | type=argparse.FileType('rb'),
80 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
81 | help='TZX file, stdin if omitted')
82 | parser.add_argument('-b', '--block',
83 | dest='block',
84 | type=int,
85 | metavar='NR',
86 | help='block number to cat')
87 | parser.add_argument('-o', '--to',
88 | dest='to',
89 | metavar='TARGET',
90 | type=argparse.FileType('wb'),
91 | default=sys.stdout.buffer,
92 | help='target file, stdout if omitted')
93 | parser.add_argument('-s', '--skip',
94 | dest='skip',
95 | type=int,
96 | metavar='BYTES',
97 | help='skip the given number of bytes before output')
98 | parser.add_argument('-l', '--length',
99 | dest='length',
100 | type=int,
101 | metavar='BYTES',
102 | help='limit output to the given number of bytes')
103 | parser.add_argument('-t', '--text',
104 | dest='text',
105 | action='store_true',
106 | help='convert ZX Spectrum text to plain text')
107 | parser.add_argument('-B', '--basic',
108 | dest='basic',
109 | action='store_true',
110 | help='convert ZX Spectrum BASIC to plain text')
111 | parser.add_argument('-A', '--assembler',
112 | dest='assembler',
113 | action='store_true',
114 | help='disassemble Z80 code')
115 | parser.add_argument('-S', '--screen',
116 | dest='screen',
117 | action='store_true',
118 | help='convert a ZX Spectrum SCREEN$ to PNG')
119 | parser.add_argument('-d', '--dump',
120 | dest='dump',
121 | action='store_true',
122 | help='convert to a hex dump')
123 | parser.add_argument('-O', '--org',
124 | dest='org',
125 | type=int,
126 | metavar='BASE',
127 | help='base address for disassembled code')
128 | args = parser.parse_args()
129 |
130 | if args.file is None:
131 | parser.print_help(sys.stderr)
132 | sys.exit(1)
133 |
134 | file = TzxFile()
135 | file.read(args.file)
136 |
137 | converter = lambda data, out, org: out.write(data) # default binary output
138 | if args.basic:
139 | converter = convertToBasic
140 | elif args.assembler:
141 | converter = convertToAssembler
142 | elif args.screen:
143 | converter = convertToScreen
144 | elif args.text:
145 | converter = convertToText
146 | elif args.dump:
147 | converter = convertToDump
148 |
149 | writer = lambda out, dump, org : writeBlock(out, dump, converter, args.skip, args.length, args.org or org or 0)
150 |
151 | outf = args.to if args.to != '-' else sys.stdout.buffer
152 | with outf if isinstance(outf, io.IOBase) else open(outf, 'wb') as out:
153 | if args.block != None:
154 | writeSingleBlock(file, out, args.block, writer)
155 | else:
156 | writeAllBlocks(file, out, writer)
157 |
--------------------------------------------------------------------------------
/tzxtools/tzxcleanup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import sys
24 |
25 | from tzxlib.tzxfile import TzxFile
26 | from tzxlib.tapfile import TapHeader
27 |
28 | def main():
29 | parser = argparse.ArgumentParser(description='Remove all noise, idealize the data')
30 | parser.add_argument('file',
31 | nargs='?',
32 | type=argparse.FileType('rb'),
33 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
34 | help='TZX file, stdin if omitted')
35 | parser.add_argument('-o', '--to',
36 | dest='to',
37 | metavar='TARGET',
38 | type=argparse.FileType('wb'),
39 | default=sys.stdout.buffer,
40 | help='target TZX file, stdout if omitted')
41 | parser.add_argument('-c', '--stripcrc',
42 | dest='stripcrc',
43 | action='store_true',
44 | help='also remove blocks with bad CRC')
45 | parser.add_argument('-H', '--headermustmatch',
46 | dest='headermustmatch',
47 | action='store_true',
48 | help='Remove blocks not preceeded by matching header (keep only matching header-block pairs)')
49 | args = parser.parse_args()
50 |
51 | if args.file is None:
52 | parser.print_help(sys.stderr)
53 | sys.exit(1)
54 |
55 | fout = TzxFile()
56 | crcCnt = 0
57 | noiseCnt = 0
58 | headerlessCnt = 0
59 |
60 | file = TzxFile()
61 | file.read(args.file)
62 | blocklengthfromheader = 0
63 | for b in file.blocks:
64 | # Convert Turbo blocks to standard timed blocks if possible
65 | if b.id == 0x11:
66 | b = b.asData()
67 |
68 | # when args.headermustmatch keep last header found
69 | if args.headermustmatch and b.id == 0x10 and b.valid() and isinstance(b.tap, TapHeader):
70 | if blocklengthfromheader != 0:
71 | # header after header makes the first one a orphan header
72 | print("Orphan header: {} ({})".format(lastheader.tap.name(), blocklengthfromheader), file=sys.stderr)
73 | headerlessCnt = headerlessCnt + 1
74 | lastheader = b
75 | blocklengthfromheader = lastheader.tap.length()
76 | continue
77 |
78 | # Use all data blocks for the output
79 | if b.id in [0x10, 0x11, 0x14]:
80 | if not b.valid():
81 | crcCnt += 1
82 | if b.valid() or not args.stripcrc:
83 | if args.headermustmatch:
84 | if blocklengthfromheader == len(b.tap.data) - 2 and not isinstance(b.tap, TapHeader):
85 | # this is a datablock with matching header
86 | fout.blocks.append(lastheader) # write header only now
87 | fout.blocks.append(b)
88 | blocklengthfromheader = 0
89 | else:
90 | # as before.
91 | fout.blocks.append(b)
92 | if blocklengthfromheader != 0:
93 | print("Orphan header: {} ({})".format(lastheader.tap.name().strip(), blocklengthfromheader), file=sys.stderr)
94 | headerlessCnt = headerlessCnt + 1
95 | blocklengthfromheader = 0
96 | continue
97 |
98 | blocklengthfromheader = 0
99 |
100 | # Use all pause blocks if they mean "stop the tape"
101 | if b.id in [0x20, 0x2A]:
102 | if b.id != 0x20 or b.length() == 0:
103 | fout.blocks.append(b)
104 | continue
105 |
106 | # Use all meta blocks
107 | if b.id not in [0x12, 0x13, 0x15, 0x18, 0x19]:
108 | fout.blocks.append(b)
109 | continue
110 |
111 | noiseCnt += 1
112 |
113 | fout.write(args.to)
114 |
115 | print('Blocks found: %3d' % (len(file.blocks)), file=sys.stderr)
116 | print('Noise blocks removed: %3d' % (noiseCnt), file=sys.stderr)
117 | print('Blocks with CRC errors: %3d' % (crcCnt), file=sys.stderr)
118 | if args.headermustmatch:
119 | print('Skipped headerless blocks: %3d' % (headerlessCnt), file=sys.stderr)
120 | print('Blocks written: %3d' % (len(fout.blocks)), file=sys.stderr)
121 |
--------------------------------------------------------------------------------
/tzxtools/tzxcut.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import os.path
24 | import re
25 | import sys
26 |
27 | from tzxlib.tapfile import TapHeader
28 | from tzxlib.tzxfile import TzxFile
29 |
30 | def appendRange(ranges, v1, v2, lastBlock):
31 | if v1 < 0: v1 += lastBlock
32 | if v1 < 0: v1 = 0
33 | if v2 < 0: v2 += lastBlock
34 | if v2 < 0: v2 = 0
35 | ranges.append((v1, v2))
36 |
37 | def isInRange(ranges, num):
38 | for rng in ranges:
39 | if num >= rng[0] and num <= rng[1]:
40 | return True
41 | return False
42 |
43 | def main():
44 | parser = argparse.ArgumentParser(description='Split into separate programs')
45 | parser.add_argument('blocks',
46 | nargs='*',
47 | help='block numbers or ranges to keep (range limits are separated by colon)')
48 | parser.add_argument('-i', '--from',
49 | dest='file',
50 | metavar='SOURCE',
51 | type=argparse.FileType('rb'),
52 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
53 | help='source TZX file, stdin if omitted')
54 | parser.add_argument('-o', '--to',
55 | dest='to',
56 | metavar='TARGET',
57 | type=argparse.FileType('wb'),
58 | default=sys.stdout.buffer,
59 | help='target TZX file, stdout if omitted')
60 | parser.add_argument('-v', '--invert',
61 | dest='invert',
62 | action='store_true',
63 | help='do not keep, but remove the blocks')
64 | args = parser.parse_args()
65 |
66 | if args.file is None:
67 | parser.print_help(sys.stderr)
68 | sys.exit(1)
69 |
70 | file = TzxFile()
71 | file.read(args.file)
72 | lastBlock = len(file.blocks)
73 |
74 | ranges = []
75 | for rng in args.blocks:
76 | m = re.match(r'^(-?\d+)$', rng)
77 | if m:
78 | v1 = int(m.group(1))
79 | appendRange(ranges, v1, v1, lastBlock)
80 | continue
81 | m = re.match(r'^(-?\d+):(-?\d+)$', rng)
82 | if m:
83 | v1 = int(m.group(1))
84 | v2 = int(m.group(2))
85 | appendRange(ranges, v1, v2, lastBlock)
86 | continue
87 | m = re.match(r'^(-?\d+):$', rng)
88 | if m:
89 | v1 = int(m.group(1))
90 | appendRange(ranges, v1, lastBlock, lastBlock)
91 | continue
92 | m = re.match(r'^:(-?\d+)$', rng)
93 | if m:
94 | v2 = int(m.group(1))
95 | appendRange(ranges, 0, v2, lastBlock)
96 | continue
97 | print('Illegal range: %s' % (rng), file=sys.stderr)
98 | exit(1)
99 |
100 | fout = TzxFile()
101 |
102 | count = 0
103 | for b in file.blocks:
104 | if isInRange(ranges, count) != args.invert:
105 | fout.blocks.append(b)
106 | count += 1
107 |
108 | fout.write(args.to)
109 |
--------------------------------------------------------------------------------
/tzxtools/tzxls.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import io
24 | import sys
25 | import textwrap
26 |
27 | from tzxlib.tapfile import TapHeader
28 | from tzxlib.tzxfile import TzxFile
29 |
30 | def main():
31 | parser = argparse.ArgumentParser(description='List the contents of a TZX file')
32 | parser.add_argument('file',
33 | nargs=argparse.REMAINDER,
34 | type=argparse.FileType('rb'),
35 | help='TZX files, stdin if omitted')
36 | parser.add_argument('-s', '--short',
37 | dest='short',
38 | action='store_true',
39 | help='list only the ZX Spectrum header names')
40 | parser.add_argument('-v', '--verbose',
41 | dest='verbose',
42 | action='store_true',
43 | help='show content of information blocks')
44 | args = parser.parse_args()
45 |
46 | files = list(args.file)
47 | if not sys.stdin.isatty() and len(files) == 0:
48 | files.append(sys.stdin.buffer)
49 |
50 | if len(files) == 0:
51 | parser.print_help(sys.stderr)
52 | sys.exit(1)
53 |
54 | for f in files:
55 | if len(files) > 1:
56 | name = f.name if hasattr(f, 'name') else f
57 | print('\n%s:' % (name))
58 | tzx = TzxFile()
59 | tzx.read(f)
60 |
61 | cnt = 0
62 | for b in tzx.blocks:
63 | if args.short:
64 | if hasattr(b, 'tap') and isinstance(b.tap, TapHeader):
65 | print('%s: %s' % (b.tap.type(), b.tap.name()))
66 | else:
67 | print('%3d %-27s %s' % (cnt, b.type, str(b)))
68 | if args.verbose:
69 | info = b.info()
70 | if info is not None:
71 | print(textwrap.indent(info.strip(), '\t'))
72 | cnt += 1
73 |
--------------------------------------------------------------------------------
/tzxtools/tzxmerge.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import sys
24 |
25 | from tzxlib.tzxfile import TzxFile
26 |
27 | def main():
28 | parser = argparse.ArgumentParser(description='Merges TZX files')
29 | parser.add_argument('files',
30 | nargs='+',
31 | type=argparse.FileType('rb'),
32 | default=sys.stdin.buffer,
33 | help='TZX files to merge')
34 | parser.add_argument('-o', '--to',
35 | metavar='TARGET',
36 | type=argparse.FileType('wb'),
37 | default=sys.stdout.buffer,
38 | help='target TZX file, stdout if omitted')
39 | args = parser.parse_args()
40 |
41 | file = TzxFile()
42 |
43 | for f in args.files:
44 | mergeFile = TzxFile()
45 | mergeFile.read(f)
46 | file.blocks.extend(mergeFile.blocks)
47 |
48 | file.write(args.to)
49 |
--------------------------------------------------------------------------------
/tzxtools/tzxplay.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2021 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | from math import sin, pi
24 | import numpy
25 | import sounddevice as sd
26 | import struct
27 | import sys
28 | import time
29 | import wave
30 |
31 | from tzxlib.tapfile import TapHeader
32 | from tzxlib.tzxfile import TzxFile
33 | from tzxlib.tzxblocks import TzxbLoopStart, TzxbLoopEnd, TzxbJumpTo, TzxbPause, TzxbStopTape48k
34 | from tzxlib.saver import TapeSaver
35 |
36 |
37 | wavelets = {}
38 | silence = bytes(2048)
39 | numpySilence = numpy.zeros(1024, dtype=numpy.float32)
40 |
41 |
42 | def wavelet(length, level, sine=False, npy=False):
43 | type = (length, level)
44 | if type in wavelets:
45 | return wavelets[type]
46 |
47 | sign = 1 if level else -1
48 |
49 | if npy:
50 | amp = sign * (min(32767 * (length + 10) / 25, 32767) if sine else 32000) / 32767
51 | wave = numpy.empty(length, dtype=numpy.float32)
52 | for pos in range(length):
53 | wave[pos] = amp * sin(pos * pi / length) if sine else amp
54 | wavelets[type] = wave
55 |
56 | else:
57 | amp = sign * (min(32767 * (length + 10) / 25, 32767) if sine else 32000)
58 | wave = bytearray(length*2)
59 | for pos in range(length):
60 | value = int(amp * sin(pos * pi / length) if sine else amp)
61 | wave[pos*2:pos*2+2] = struct.pack(' 0:
91 | block = repeatBlock
92 | if verbose:
93 | print(' - returning to block %d (remaining %d)' % (block, repeatCount))
94 | else:
95 | repeatBlock = None
96 | repeatCount = None
97 | if verbose:
98 | print(' - loop is finished')
99 | continue
100 | elif isinstance(b, TzxbJumpTo):
101 | block += b.relative()-1
102 | if block < 0 or block > len(tzx.blocks)-1:
103 | raise IndexError('Jump to non-existing block')
104 | if verbose:
105 | print(' - jumping to block %d' % (block))
106 | continue
107 | elif isinstance(b, TzxbPause) and b.stopTheTape() and stopAlways:
108 | if verbose:
109 | print(' - tape stopped')
110 | break
111 | elif isinstance(b, TzxbStopTape48k) and stop48k:
112 | if verbose:
113 | print(' - tape stopped (48k mode)')
114 | break
115 |
116 | currentLevel = False
117 | lastLevel = False
118 | for ns in b.playback(saver):
119 | currentLevel = not currentLevel
120 | if ns > 0:
121 | realTimeNs += ns
122 | newSampleTime = ((realTimeNs * rate) + 500000000) // 1000000000
123 | wavelen = newSampleTime - currentSampleTime
124 | if wavelen <= 0:
125 | continue
126 | if currentLevel != lastLevel:
127 | yield wavelet(wavelen, currentLevel, sine, npy)
128 | else:
129 | while wavelen > 0:
130 | if wavelen >= len(silence)//2:
131 | yield numpySilence if npy else silence
132 | wavelen -= len(silence)//2
133 | else:
134 | yield numpy.zeros(wavelen, dtype=numpy.float32) if npy else silence[0:wavelen*2]
135 | wavelen = 0
136 | lastLevel = currentLevel
137 | currentSampleTime = newSampleTime
138 | if verbose:
139 | millis = realTimeNs // 1000000
140 | seconds = millis // 1000
141 | minutes = seconds // 60
142 | print('%02d:%02d.%03d End of Recording' % (minutes, seconds%60, millis%1000))
143 |
144 |
145 | def main():
146 | parser = argparse.ArgumentParser(description='Playback a tzx file')
147 | parser.add_argument('file',
148 | nargs='?',
149 | type=argparse.FileType('rb'),
150 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
151 | help='TZX file, stdin if omitted')
152 | parser.add_argument('-o', '--to',
153 | dest='to',
154 | metavar='TARGET',
155 | type=argparse.FileType('wb'),
156 | default=None,
157 | help='Create WAV file instead of playing audio')
158 | parser.add_argument('-v', '--verbose',
159 | dest='verbose',
160 | action='store_true',
161 | help='Be verbose about what you are doing')
162 | parser.add_argument('-s', '--stop',
163 | dest='stop',
164 | action='store_true',
165 | help='Execute Stop-The-Tape commands')
166 | parser.add_argument('-K', '--48k',
167 | dest='mode48k',
168 | action='store_true',
169 | help='Enable ZX Spectrum 48K mode')
170 | parser.add_argument('-r', '--rate',
171 | dest='rate',
172 | default=44100,
173 | type=int,
174 | help='Output sample rate')
175 | parser.add_argument('-c', '--clock',
176 | dest='clock',
177 | default=3500000,
178 | type=int,
179 | help='Reference Z80 CPU clock, in Hz')
180 | parser.add_argument('-S', '--sine',
181 | dest='sine',
182 | action='store_true',
183 | help='Generate soft sine pulses (square pulses otherwise)')
184 | args = parser.parse_args()
185 |
186 | if args.file is None:
187 | parser.print_help(sys.stderr)
188 | sys.exit(1)
189 |
190 | tzx = TzxFile()
191 | tzx.read(args.file)
192 | stream = streamAudio(tzx, rate=args.rate, stopAlways=args.stop, stop48k=args.mode48k,
193 | sine=args.sine, cpufreq=args.clock, verbose=args.verbose, npy=args.to is None)
194 |
195 | audiostream = audio = wav = None
196 |
197 | try:
198 | if args.to is not None:
199 | # Generate WAV file
200 | wav = wave.open(args.to, mode='wb')
201 | wav.setnchannels(1)
202 | wav.setsampwidth(2)
203 | wav.setframerate(args.rate)
204 | for b in stream:
205 | wav.writeframesraw(b)
206 | wav.writeframesraw(silence[0:16])
207 | else:
208 | # Audio Playback
209 | with sd.Stream(samplerate=args.rate, channels=1, latency='high') as out:
210 | for b in stream:
211 | out.write(b)
212 | except KeyboardInterrupt:
213 | print('', file=sys.stderr)
214 | print("D BREAK - CONT repeats, 0:1", file=sys.stderr)
215 | finally:
216 | if wav is not None:
217 | wav.close()
218 | if audiostream is not None:
219 | audiostream.stop_stream()
220 | audiostream.close()
221 | if audio is not None:
222 | audio.terminate()
223 |
--------------------------------------------------------------------------------
/tzxtools/tzxsplit.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import os.path
24 | import re
25 | import sys
26 |
27 | from tzxlib.tapfile import TapHeader
28 | from tzxlib.tzxfile import TzxFile
29 |
30 | unwanted = re.compile(r'[^a-zA-Z0-9 #$%,;=@_{}()+-]')
31 |
32 | def sanitize(name):
33 | if len(name) == 0:
34 | return 'no-name'
35 | return unwanted.sub('_', name)
36 |
37 | def writeTzx(tzx, name, dir):
38 | if tzx is None or len(tzx.blocks) == 0: return # do not write empty TZX files
39 | count = 1
40 | while True:
41 | fn = '%s%s-%03d.tzx' % (dir, sanitize(name), count)
42 | if not os.path.isfile(fn): break
43 | count += 1
44 | tzx.write(fn)
45 |
46 | def main():
47 | parser = argparse.ArgumentParser(description='Split into separate programs')
48 | parser.add_argument('file',
49 | nargs='?',
50 | type=argparse.FileType('rb'),
51 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
52 | help='TZX file, stdin if omitted')
53 | parser.add_argument('-d', '--dir',
54 | dest='dir',
55 | metavar='TARGET',
56 | default='./',
57 | help='target directory, default is cwd')
58 | parser.add_argument('-1', '--single',
59 | dest='single',
60 | action='store_true',
61 | help='split into single loadable files')
62 | parser.add_argument('-s', '--skip',
63 | dest='skip',
64 | action='store_true',
65 | help='skip all blocks before first Program')
66 | args = parser.parse_args()
67 |
68 | if args.file is None:
69 | parser.print_help(sys.stderr)
70 | sys.exit(1)
71 |
72 | file = TzxFile()
73 | file.read(args.file)
74 |
75 | dir = args.dir
76 | if dir[-1] != '/': dir += '/'
77 |
78 | fname = 'preamble'
79 | fout = TzxFile() if not args.skip else None
80 |
81 | for b in file.blocks:
82 | if hasattr(b, 'tap') and isinstance(b.tap, TapHeader) and (b.tap.typeId() == 0 or args.single):
83 | writeTzx(fout, fname, dir)
84 | fout = TzxFile()
85 | fname = b.tap.name().strip()
86 | if not fout is None:
87 | fout.blocks.append(b)
88 |
89 | writeTzx(fout, fname, dir)
90 |
--------------------------------------------------------------------------------
/tzxtools/tzxtap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2018 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import io
24 | import sys
25 |
26 | from tzxlib.tzxfile import TzxFile
27 | from tzxlib.tzxblocks import TapNotSupportedError
28 |
29 | def writeBlock(block, out, ignore, index):
30 | try:
31 | if block.writeTap(out):
32 | if not block.tap.valid():
33 | print('Block %3d: Warning: Bad CRC, may cause tape loading error.' % (index), file=sys.stderr)
34 | else:
35 | print('Block %3d: Comment block was ignored.' % (index), file=sys.stderr)
36 | except TapNotSupportedError:
37 | if ignore:
38 | print('Block %3d: Warning: Block is not supported by TAP format.' % (index), file=sys.stderr)
39 | else:
40 | print('Block %3d: Error: Block is not supported by TAP format.' % (index), file=sys.stderr)
41 | print('Use --ignore option to enforce conversion, but TAP file will be faulty.', file=sys.stderr)
42 | exit(1)
43 |
44 | def writeAllBlocks(tzx, out, ignore):
45 | index = 0
46 | for block in tzx.blocks:
47 | writeBlock(block, out, ignore, index)
48 | index += 1
49 |
50 | def main():
51 | parser = argparse.ArgumentParser(description='Convert to TAP file format')
52 | parser.add_argument('file',
53 | nargs='?',
54 | type=argparse.FileType('rb'),
55 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
56 | help='TZX file, stdin if omitted')
57 | parser.add_argument('-o', '--to',
58 | dest='to',
59 | metavar='TARGET',
60 | type=argparse.FileType('wb'),
61 | default=sys.stdout.buffer,
62 | help='TAP file, stdout if omitted')
63 | parser.add_argument('-i', '--ignore',
64 | dest='ignore',
65 | action='store_true',
66 | help='ignore blocks that cannot be stored in a TAP file')
67 | args = parser.parse_args()
68 |
69 | if args.file is None:
70 | parser.print_help(sys.stderr)
71 | sys.exit(1)
72 |
73 | file = TzxFile()
74 | file.read(args.file)
75 |
76 | outf = args.to if args.to != '-' else sys.stdout.buffer
77 | with outf if isinstance(outf, io.IOBase) else open(outf, 'wb') as tap:
78 | writeAllBlocks(file, tap, args.ignore)
79 |
--------------------------------------------------------------------------------
/tzxtools/tzxwav.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # tzxtools - a collection for processing tzx files
4 | #
5 | # Copyright (C) 2016 Richard "Shred" Körber
6 | # https://codeberg.org/shred/tzxtools
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 |
22 | import argparse
23 | import io
24 | import sys
25 | from time import time
26 | import wave
27 |
28 | from tzxlib.loader import TapeLoader
29 |
30 | tresholds = { 'low': 500, 'med': 2500, 'high':5000 }
31 | tolerances = { 'low': 1.1, 'med': 1.2, 'high': 1.4 }
32 | leaderMins = { 'none': 2, 'short': 10, 'normal': 40, 'long': 100 }
33 | leftChMix = { 'left': 1, 'mix': 0.5, 'right': 0 }
34 |
35 | lastPercent = None
36 | startTime = None
37 |
38 | def showProgress(current, max):
39 | global lastPercent, startTime
40 | if startTime is None:
41 | startTime = time()
42 | percent = int(current * 100 / max)
43 | if lastPercent is None or percent != lastPercent:
44 | lastPercent = percent
45 | halfPercent = int(percent / 2)
46 | if lastPercent > 3:
47 | now = time()
48 | remainSecs = ((now - startTime) * 100 / lastPercent) + startTime - now
49 | print('%3d%% |%s%s| %2d:%02d' % (percent, '#'*halfPercent, '-'*(50-halfPercent), remainSecs // 60 , remainSecs % 60), end='\r', file=sys.stderr)
50 | else:
51 | print('%3d%% |%s%s|' % (percent, '#'*halfPercent, '-'*(50-halfPercent)), end='\r', file=sys.stderr)
52 |
53 | def main():
54 | parser = argparse.ArgumentParser(description='Generates TZX from WAV file')
55 | parser.add_argument('file',
56 | nargs='?',
57 | type=argparse.FileType('rb'),
58 | default=(None if sys.stdin.isatty() else sys.stdin.buffer),
59 | help='WAV file')
60 | parser.add_argument('-o', '--to',
61 | dest='to',
62 | metavar='TARGET',
63 | type=argparse.FileType('wb'),
64 | default=sys.stdout.buffer,
65 | help='target file, stdout if omitted')
66 | parser.add_argument('-p', '--progress',
67 | dest='progress',
68 | action='store_true',
69 | help='show progress bar')
70 | parser.add_argument('-v', '--verbose',
71 | dest='verbose',
72 | action='store_true',
73 | help='show blocks as they are found')
74 | parser.add_argument('-t', '--treshold',
75 | choices=['low', 'med', 'high'],
76 | default='med',
77 | dest='treshold',
78 | help='sound/noise ratio treshold')
79 | parser.add_argument('-T', '--tolerance',
80 | choices=['low', 'med', 'high'],
81 | default='med',
82 | dest='tolerance',
83 | help='tape speed flutter tolerance')
84 | parser.add_argument('-l', '--leader',
85 | choices=['none', 'short', 'normal', 'long'],
86 | default='normal',
87 | dest='leader',
88 | help='accepted minimal length of leader signal')
89 | parser.add_argument('-c', '--clock',
90 | dest='clock',
91 | default=3500000,
92 | type=int,
93 | help='Reference Z80 CPU clock, in Hz')
94 | parser.add_argument('-s', '--start',
95 | dest='start',
96 | type=int,
97 | help='Start at WAV frame number')
98 | parser.add_argument('-e', '--end',
99 | dest='end',
100 | type=int,
101 | help='End at WAV frame number')
102 | parser.add_argument('-S', '--stereo',
103 | choices=['left', 'mix', 'right'],
104 | default='mix',
105 | dest='leftChMix',
106 | help='channel selection (works only for stereo WAV files)')
107 | parser.add_argument('-D', '--debug',
108 | dest='debug',
109 | action='count',
110 | help='enable debug output, give multiple times to increase verbosity')
111 |
112 | args = parser.parse_args()
113 |
114 | if args.file is None:
115 | parser.print_help(sys.stderr)
116 | sys.exit(1)
117 |
118 | loader = TapeLoader(debug=args.debug,
119 | treshold=tresholds[args.treshold],
120 | tolerance=tolerances[args.tolerance],
121 | leaderMin=leaderMins[args.leader],
122 | leftChMix=leftChMix[args.leftChMix],
123 | cpufreq=args.clock,
124 | progress=showProgress if args.progress else None,
125 | verbose=args.verbose)
126 |
127 | try:
128 | tzx = loader.load(args.file, startFrame=args.start, endFrame=args.end)
129 | file = args.to
130 | if not isinstance(file, io.IOBase) and not file.lower().endswith('.tzx'):
131 | file += '.tzx'
132 | tzx.write(file)
133 | except KeyboardInterrupt:
134 | print('', file=sys.stderr)
135 | print("D BREAK - CONT repeats, 0:1", file=sys.stderr)
136 | exit(1)
137 |
138 | if args.progress:
139 | print('', file=sys.stderr)
140 |
--------------------------------------------------------------------------------