-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspectrumtape.py
executable file
·3333 lines (2669 loc) · 115 KB
/
spectrumtape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# This file is part of the SpectrumTranslate python module.
#
# It's licenced under GPL version 3 (www.gnu.org/licenses/gpl.html) with
# a few extra stipulations:
# 1) These first lines in this file as far as the line with the date
# needs to be left in so anyone who gets a copy of this file has access
# to the licence, extra stipulations, and disclaimors.
# 2) If this code is used as part of another project, I'd apreciate a
# mention in that project's documentation.
# 3) If you improve on any of the routines, I'd be most grateful if you
# would pass them back to me so that I can have the option to
# incorporate them into the origional module with apropriate attribution
# under this licence and stipulations.
#
# A copy of the licence and stipulations is bundled with the source
# files as licence.txt, or you can go to the GNU website for the terms
# of the GPL licence.
#
# If you try hard enough, I'm sure someone could damage something
# (software, data, system, hardware) useing it. I've put a lot of time
# and effort into this software, and have removed any obvious bugs, but
# nothing is perfect. If you spot any flaws, please let me know so that
# I might be able to fix them. However I reserve the right not to fix
# flaws that I don't have the time, or resources to fix, or that I feel
# that fixing would detriment the software overall. By useing this
# software you accept this, and any potential risk to your own hardware,
# software, data, and/or physical and mental health. This software is
# provided "as is" and any express or implied warranties, including, but
# not limited to, the implied warranties of merchantability and fitness
# for a particular purpose are disclaimed. In no event shall I or any
# contributors be liable for any direct, indirect, incidental, special,
# exemplary, or consequential damages (including, but not limited to,
# procurement of substitute goods or services; loss of use, data, or
# profits; or business interruption) however caused and on any theory of
# liability, whether in contract, strict liability, or tort (including
# negligence or otherwise) arising in any way out of the use of this
# software, even if advised of the possibility of such damage. By using
# this software you agree to these terms.
#
# Author: [email protected]
# Date: 16th April 2024
import spectrumtranslate
import sys
from io import IOBase
from math import ceil, log2
from os.path import isfile
# os.path imported elsewhere so only used for command line
def _isarray(x):
return isinstance(x, (list, tuple))
def _isarrayofint(x):
return _isarray(x) and all(isinstance(val, int) for val in x)
def _bytesarevalid(x):
return isinstance(x, (bytes, bytearray)) or _isarrayofint(x)
def _sourceisvalid(s):
return isinstance(s, IOBase) or _bytesarevalid(s)
def _validateandpreparebytes(x, m=""):
if _bytesarevalid(x):
return bytearray(x)
raise spectrumtranslate.SpectrumTranslateError("{} needs to be a \
list or tuple of ints, or of type 'bytes' or 'bytearray'".format(m))
def _get_word(s):
return int.from_bytes(s, 'little')
def word_to_bytes(w, n, signed=False):
return w.to_bytes(n, 'little', signed=signed)
def _validateandconvertfilename(filename):
# check filename is valid
if _isarray(filename):
# if is list of numbers convert to list of strings
if _isarrayofint(filename):
filename = bytearray(filename)
# if there are only strings in the list then convert list to
# a string
if all(isinstance(x, str) for x in filename):
filename = "".join(filename)
if isinstance(filename, str):
filename = bytearray(filename, "utf8")
if not isinstance(filename, (bytes, bytearray)) or len(filename) > 10:
raise spectrumtranslate.SpectrumTranslateError(
"Filename must be a string, or list of ints or strings, of type \
'bytes' or 'bytearray' and of no more than 10 characters.")
# return filename right padded with spaces
return bytearray(filename) + bytearray([32] * (10 - len(filename)))
class SpectrumTapeBlock:
"""
A class that holds information about a block of data from a Spectrum
Tape file. These can be used to extract data from a tzx or tap file.
"""
def __init__(self, filePosition=0, blockPosition=None):
"""
Creates a new TapeBlock object. filePosition is the offset to the
data from the start of the stream. You can safely put 0 here if
this is of no use to you. blockPosition is the index of this
block in the container file. None if not defined."""
self.filePosition = filePosition
self.blockPosition = blockPosition
def isheader(self):
"""
Is this Block object probably a header block?
Header blocks come before the blocks holding the actual file
data and contain information such as the filename, the file
type, length, and other information depending on the file type.
Returns True if this is probably a header, or False if probably
not.
"""
# default to not being a header
return False
def isdatablock(self):
"""
Is this Block object probably a data block?
Data blocks come after the Header blocks and contain the data
of a file.
Returns True if this is probably a data, or False if probably
not.
"""
# default to not being a datablock
return False
def getpayloadlength(self):
"""
Returns the length of the data described by this block. Note
that the actual length of a block is longer as it often contains
details such as the length of a block, a flag, and a checksum.
"""
# default to no data
return 0
def getpayloadstartoffset(self):
"""
Returns the position in the file of the data described by this
block.
"""
# default to no data
return 0
def getpayload(self):
"""
Returns the actual data that the block this describes would hold
(without flag or checksum).
Returns None if block doesn't have data in it.
"""
return None
def getfilename(self):
"""
This gets the filename from a header block. Note that the
filename is always 10 spectrum characters long and will be
padded with spaces to make the length up to 10 characters. Also
be aware that spectrum characters can contain control codes, or
names of spectrum BASIC commands, so the resultant extracted
string could be more than 10 characters in length. Returns a
String holding the filename, or None if this object isn't a
header.
"""
if not self.isheader():
return None
return spectrumtranslate.getspectrumstring(self.getpayload()[1:11])
def getrawfilename(self):
"""This returns the 10 character file name as a bytearray.
Returns None if not a header."""
if not self.isheader():
return None
return self.getpayload()[1:11]
def getfiletypestring(self):
"""
What type of data does this header block describe.
Return a string holding the file type, or None if it is not a
header block.
"""
if not self.isheader():
return None
filetype = self.getpayload()[0]
if filetype == 0:
return "Program"
elif filetype == 1:
return "Number array"
elif filetype == 2:
return "Character array"
elif filetype == 3:
return "Bytes"
else:
return "Unknown"
def getblockinfo(self):
"""
This gets a String respresentation of the file information.
If the block describes a header, then the format of the returned
string is similar to that displayed by the spectrum as it loads
a file.
For data block, the flag and length are returned.
Other blocks have information about that type of block.
"""
if self.isheader():
# work out any extra details for file
extra = self.getfiletypestring()
# get word at 13, and 14 in the data
x = _get_word(self.getpayload()[13:15])
filetype = self.getpayload()[0]
# code file
if filetype == 3:
extra += " " + str(x) + "," + \
str(_get_word(self.getpayload()[11:13]))
# program
if filetype == 0 and x < 10000:
extra += " Line:" + str(x)
# array
if filetype == 1 or filetype == 2:
extra += " " + self.getheadervariablename()
return "\"" + self.getfilename() + "\" " + extra
if self.isdatablock():
return "Flag:{}, block length:{}".format(
self.flag, self.getpayloadlength())
return ""
def getheaderautostartline(self):
"""
This returns the Autostart line number for a BASIC file header
block. Returns the line number to automatically start at when a
BASIC file is loaded. Returns None if no Autostart line is
specified, or if this object is not a BASIC header block.
"""
if not self.isheader() or self.getpayload()[0] != 0:
return None
start = _get_word(self.getpayload()[13:15])
if start > 9999:
return None
return start
def getheadervariableoffset(self):
"""
This returns the offset to the start of the variable area in a
BASIC file. This is the same as the length in bytes of the
BASIC program. If this is the same as the length of the BASIC
file then there are no variables saved with the program.
Returns the byte offset to the start of the variables in the
file, or None if this object is not a BASIC header block. This
is the same as the length of the BASIC program without any
variables.
"""
if not self.isheader() or self.getpayload()[0] != 0:
return None
return _get_word(self.getpayload()[15:17])
def getheadercodestart(self):
"""
This returns the address where a code file was saved from, and
is the sugested address to load it to. Returns the code address
for a code block, or None if this object is not a code header
block.
"""
if not self.isheader() or self.getpayload()[0] != 3:
return None
return _get_word(self.getpayload()[13:15])
def getheaderdescribeddatalength(self):
"""
This returns the length of the data block that this Header
block details. Returns the data block block length, or None if
this object is not a header block.
"""
if not self.isheader():
return None
return _get_word(self.getpayload()[11:13])
def getheadervariableletter(self):
""""
This returns the character of the variable described by an array
Header block. Returns the character value of a variable
described by a header block, or None if this object is not a
number or character array header block.
"""
if not self.isheader() or (self.getpayload()[0] != 1 and
self.getpayload()[0] != 2):
return None
return chr((self.getpayload()[14] & 127) | 64)
def getheadervariablename(self):
"""
This returns the name of the variable described by an array
Header block. This is the letter name of the array, followed
by '$' if it is a character array. Returns the name of a
variable described by a header block, or None if this object is
not a number or character array header block.
"""
letter = self.getheadervariableletter()
if not letter:
return None
return letter + ("$" if self.getpayload()[0] == 2 else "")
def getheaderarraydescriptor(self):
"""
This returns the array descriptor of an array Header block.
The descriptor is an 8 bit number. The lower 6 bits hold the
ASCII lower 6 bits of the variable name (must be a letter of the
alphabet). Bits 6 and 7 describe what type of array the Header
block describes. They are 64 for a character array, 128 for a
number array, and 192 for a string array. Returns the array
descriptor of the array described by a header block, or None if
this object is not a number or character array header block.
"""
if not self.isheader() or not self.getpayload()[0] in [1, 2]:
return None
return self.getpayload()[14]
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "Tape Block"
def getdetailslist(self):
"""
Returns info list for this block to display in a listing.
"""
details = "{}\t{}\t".format(self.blockPosition, self.blocktype())
if self.isheader():
details += "Header\t{}\t".format(self.getfilename())
filetype = self.getfiletypestring()
if filetype == "Program":
details += "Program\t{}\t{}\t{}".format(
self.getheaderdescribeddatalength(),
"" if self.getheaderautostartline() is None else
self.getheaderautostartline(),
self.getheadervariableoffset())
elif filetype == "Bytes":
details += "Bytes\t{}\t{}".format(
self.getheadercodestart(),
self.getheaderdescribeddatalength())
elif filetype in ["Number array", "Character array"]:
details += "{}\t{}\t{}\t{}\t{}".format(
filetype, self.getheaderdescribeddatalength(),
self.getheadervariableletter(),
self.getheadervariablename(),
self.getheaderarraydescriptor() & 192)
else:
details += "Unknown\t{}\t{}".format(
self.getpayload()[0],
self.getheaderdescribeddatalength())
elif self.isdatablock():
details += "Data\tFlag:{}\tLength:{}".format(
self.flag, self.getpayloadlength())
return details
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "SpectrumTapeBlock"
def getpackagedforfile(self):
"""
returns this TapeBlock packaged up as a bytearray for output to
a file.
"""
raise spectrumtranslate.SpectrumTranslateError("Generic Tape Block \
not useable in file. Use child classes instead")
class SpectrumTapBlock(SpectrumTapeBlock):
"""
A class that holds information about a block of data from a Spectrum
Tap file format. These can be used to extract data from a tap file.
"""
def __init__(self, flag=0, data=[], filePosition=0, blockPosition=None):
"""
Creates a new TapBlock object. filePosition is the offset to the
data from the start of the stream. You can safely put 0 here if
this is of no use to you. data if defined has to be list or
tuple of ints or longs, or of type 'bytes' or 'bytearray'.
"""
super().__init__(filePosition, blockPosition)
"""
The 8 bit data identifier value for the block.
Typically it is 0 for a header and 255 for a data block, but
custom load and save routines can use any value from 0 to 255.
"""
if not isinstance(flag, int) or flag < 0 or flag > 255:
raise spectrumtranslate.SpectrumTranslateError(
"flag needs to be from 0 to 255 inclusive.")
self.flag = flag
# validate and prepare data
"""An array of bytes holding the data for the block."""
self.data = _validateandpreparebytes(data, "data")
def isheader(self):
"""
Is this Block object probably a header block?
Header blocks come before the blocks holding the actual file
data and contain information such as the filename, the file
type, length, and other information depending on the file type.
Returns True if this is probably a header, or False if probably
not.
"""
return (self.flag == 0 and len(self.data) == 17)
def isdatablock(self):
"""
Is this Block object probably a data block?
Data blocks come after the Header blocks and contain the data
of a file.
Returns True if this is probably a data, or False if probably
not.
"""
return len(self.data) > 0 and not self.isheader()
def getpayloadlength(self):
"""
Returns the length of the data described by this block. Note
that the actual length of a block is longer as it often contains
details such as the length of a block, a flag, and a checksum.
"""
return len(self.data)
def getpayload(self):
"""
Returns the actual data that the block this describes would hold
(without flag or checksum).
Returns None if block doesn't have data in it.
"""
return self.data
def getpayloadstartoffset(self):
"""
This returns the offset to the data of a block of a tap file in
the origional stream. This is only as acurate as the offset
value passed in the contructor. Returns the offset to the data
in the origional stream used to create this object.
"""
return self.filePosition + 3
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TAP Block"
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "Tap file block. Flag:{}, block length:{}".format(
self.flag, self.getpayloadlength())
def getpackagedforfile(self):
"""
returns this TapBlock packaged up with length header, flag and
checksum ready for saveing to a file. Will be returned as a
bytearray.
"""
# work out length of data+flag+checksum
length = len(self.data) + 2
# work out checksum
checksum = self.flag
for i in self.data:
checksum = checksum ^ i
# merge it into a list, and return
return word_to_bytes(length, 2) + bytearray([self.flag]) + \
self.data + bytearray([checksum])
class SpectrumTZXStandardSpeedDataBlock(SpectrumTapeBlock):
"""
A class that holds information about a Standard Speed Data Block
from a TZX file. These can be used to extract data from a tzx file.
"""
def __init__(self, endPause=0, data=[], filePosition=0,
blockPosition=None):
"""
Creates a new SpectrumTZXStandardSpeedDataBlock object.
filePosition is the offset to the data from the start of the
stream. You can safely put 0 here if this is of no use to you.
data if defined has to be list or tuple of ints or longs, or of
type 'bytes' or 'bytearray'.
"""
super().__init__(filePosition, blockPosition)
# validate and prepare data
"""An array of bytes holding the data for the block."""
self.data = _validateandpreparebytes(data, "data")
self.endPause = endPause
if len(data) > 0:
self.flag = data[0]
def isheader(self):
"""
Is this Block object probably a header block?
Header blocks come before the blocks holding the actual file
data and contain information such as the filename, the file
type, length, and other information depending on the file type.
Returns True if this is probably a header, or False if probably
not.
"""
return len(self.data) == 19 and self.data[0] == 0
def isdatablock(self):
"""
Is this Block object probably a data block?
Data blocks come after the Header blocks and contain the data
of a file.
Returns True if this is probably a data, or False if probably
not.
"""
return len(self.data) > 0 and not self.isheader()
def getpayload(self):
"""
Returns the actual data that the block this describes would hold
(without flag or checksum).
Returns None if block doesn't have data in it.
"""
return self.data[1: -1]
def getpayloadlength(self):
"""
Returns the length of the data described by this block. Note
that the actual length of a block is longer as it often contains
details such as the length of a block, a flag, and a checksum.
"""
return len(self.data) - 2
def getpayloadstartoffset(self):
"""
This returns the offset to the data of a block of a tzx file in
the origional stream. This is only as acurate as the offset
value passed in the contructor. Returns the offset to the data
in the origional stream used to create this object.
"""
return self.filePosition + 6
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TZX Standard Speed"
def getblockinfo(self):
"""
This gets a String respresentation of the file information.
If the block describes a header, then the format of the returned
string is similar to that displayed by the spectrum as it loads
a file.
For data block, the flag and length are returned.
Other blocks have information about that type of block.
"""
return super().getblockinfo() + \
" pause after:{}ms".format(self.endPause)
def getdetailslist(self):
"""
Returns info list for this block to display in a listing.
"""
return super().getdetailslist() + \
"\tpause after:{}ms".format(self.endPause)
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "TZX Standard Speed Data Block. Flag:{}, block length:{}, \
pause afterwards: {}ms".format(self.flag, self.getpayloadlength(),
self.endPause)
def getpackagedforfile(self):
"""
returns this TzxBlock packaged up ready for saveing to a file.
Will be returned as a bytearray.
"""
return bytearray([0x10]) + \
word_to_bytes(self.endPause, 2) + \
word_to_bytes(len(self.data), 2) + self.data
class SpectrumTZXTurboSpeedDataBlock(SpectrumTapeBlock):
"""
A class that holds information about a Turbo Speed Data Block from
a TZX file. These can be used to extract data from a tzx file.
"""
def __init__(self, endPause=0, data=[], lenPilotPulse=2168,
lenSyncPulse1=667, lenSyncPulse2=735, lenZeroPulse=855,
lenOnePulse=1710, lenPilotTone=3223,
lastByteUsedBits=8, filePosition=0,
blockPosition=None):
"""
Creates a new SpectrumTZXTurboSpeedDataBlock object.
filePosition is the offset to the data from the start of the
stream. You can safely put 0 here if this is of no use to you.
data if defined has to be list or tuple of ints or longs, or of
type 'bytes' or 'bytearray'.
"""
super().__init__(filePosition, blockPosition)
# validate and prepare data
"""An array of bytes holding the data for the block."""
self.data = _validateandpreparebytes(data, "data")
self.endPause = endPause
self.lenPilotPulse = lenPilotPulse
self.lenSyncPulse1 = lenSyncPulse1
self.lenSyncPulse2 = lenSyncPulse2
self.lenZeroPulse = lenZeroPulse
self.lenOnePulse = lenOnePulse
self.lenPilotTone = lenPilotTone
self.lastByteUsedBits = lastByteUsedBits
if len(data) > 0:
self.flag = data[0]
def isheader(self):
"""
Is this Block object probably a header block?
Header blocks come before the blocks holding the actual file
data and contain information such as the filename, the file
type, length, and other information depending on the file type.
Returns True if this is probably a header, or False if probably
not.
"""
return (len(self.data) == 19 and self.data[0] == 0)
def isdatablock(self):
"""
Is this Block object probably a data block?
Data blocks come after the Header blocks and contain the data
of a file.
Returns True if this is probably a data, or False if probably
not.
"""
return len(self.data) > 0 and not self.isheader()
def getpayloadlength(self):
"""
Returns the length of the data described by this block. Note
that the actual length of a block is longer as it often contains
details such as the length of a block, a flag, and a checksum.
"""
return len(self.data) - 2
def getpayload(self):
"""
Returns the actual data that the block this describes would hold
(without flag or checksum).
Returns None if block doesn't have data in it.
"""
return self.data[1: -1]
def getpayloadstartoffset(self):
"""
This returns the offset to the data of a block of a tap file in
the origional stream. This is only as acurate as the offset
value passed in the contructor. Returns the offset to the data
in the origional stream used to create this object.
"""
return self.filePosition + 20
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TZX Turbo Speed"
def getblockinfo(self):
"""
This gets a String respresentation of the file information.
If the block describes a header, then the format of the returned
string is similar to that displayed by the spectrum as it loads
a file.
For data block, the flag and length are returned.
Other blocks have information about that type of block.
"""
return super().getblockinfo() + " pause after:{}ms".format(
self.endPause)
def getdetailslist(self):
"""
Returns info list for this block to display in a listing.
"""
return super().getdetailslist() + "\tpause after:{}ms".format(
self.endPause)
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "TZX Turbo Speed Data Block. Flag:{}, block length:{}, pause \
afterwards: {}ms".format(self.flag, self.getpayloadlength(), self.endPause)
def getpackagedforfile(self):
"""
returns this TzxBlock packaged up ready for saveing to a file.
Will be returned as a bytearray.
"""
return bytearray([0x11]) + \
word_to_bytes(self.lenPilotPulse, 2) + \
word_to_bytes(self.lenSyncPulse1, 2) + \
word_to_bytes(self.lenSyncPulse2, 2) + \
word_to_bytes(self.lenZeroPulse, 2) + \
word_to_bytes(self.lenOnePulse, 2) + \
word_to_bytes(self.lenPilotTone, 2) + \
word_to_bytes(self.lastByteUsedBits, 1) + \
word_to_bytes(self.endPause, 2) + \
word_to_bytes(len(self.data), 3) + self.data
class SpectrumTZXPureToneBlock(SpectrumTapeBlock):
"""
A class that holds information about a Pure Tone Block from a TZX
file. These can be used to extract data from a tzx file.
"""
def __init__(self, lenPulse, numberOfPulses, filePosition=0,
blockPosition=None):
"""
Creates a new SpectrumTZXPureToneBlock object.
filePosition is the offset to the data from the start of the
stream. You can safely put 0 here if this is of no use to you.
"""
super().__init__(filePosition, blockPosition)
self.lenPulse = lenPulse
self.numberOfPulses = numberOfPulses
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TZX Pure Tone"
def getdetailslist(self):
"""
Returns info list for this block to display in a listing.
"""
return super().getdetailslist() + "\tPulse Length:{}\tNumber of \
Pulses:{}".format(self.lenPulse, self.numberOfPulses)
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "TZX Pure Tone Block. Pulse Length:{}, Number of \
Pulses:{}".format(self.lenPulse, self.numberOfPulses)
def getpackagedforfile(self):
"""
returns this TzxBlock packaged up ready for saveing to a file.
Will be returned as a bytearray.
"""
return bytearray([0x12]) + \
word_to_bytes(self.lenPilot, 2) + \
word_to_bytes(self.numberOfPulses, 2)
class SpectrumTZXPulseSequenceBlock(SpectrumTapeBlock):
"""
A class that holds information about a Pulse Sequence Block from a
TZX file. These can be used to extract data from a tzx file.
"""
def __init__(self, pulses, filePosition=0, blockPosition=None):
"""
Creates a new SpectrumTZXPulseSequenceBlock object.
filePosition is the offset to the data from the start of the
stream. You can safely put 0 here if this is of no use to you.
"""
super().__init__(filePosition, blockPosition)
if not _isarrayofint(pulses):
raise spectrumtranslate.SpectrumTranslateError(
"Pulses needs to be a list of numbers.")
self.pulses = pulses
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TZX Pulse Sequence"
def getdetailslist(self):
"""
Returns info list for this block to display in a listing.
"""
return super().getdetailslist() + "\tPulse Sequence Length:{}".format(
self.pulses)
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "TZX Pulse Sequence Block. Pulse Sequence Length:{}".format(
len(self.pulses))
def getpackagedforfile(self):
"""
returns this TzxBlock packaged up ready for saveing to a file.
Will be returned as a bytearray.
"""
return bytearray([0x13]) + \
word_to_bytes(len(self.pulses), 1) + self.pulses
class SpectrumTZXPureDataBlock(SpectrumTapeBlock):
"""
A class that holds information about a Pure Data Block from a TZX
file. These can be used to extract data from a tzx file.
"""
def __init__(self, endPause=0, data=[], lenZeroPulse=855,
lenOnePulse=1710, lastByteUsedBits=8, filePosition=0,
blockPosition=None):
"""
Creates a new SpectrumTZXPureDataBlock object.
filePosition is the offset to the data from the start of the
stream. You can safely put 0 here if this is of no use to you.
"""
super().__init__(filePosition, blockPosition)
# validate and prepare data
"""An array of bytes holding the data for the block."""
self.data = _validateandpreparebytes(data, "data")
self.endPause = endPause
self.lenZeroPulse = lenZeroPulse
self.lenOnePulse = lenOnePulse
self.lastByteUsedBits = lastByteUsedBits
if len(data) > 0:
self.flag = data[0]
def isheader(self):
"""
Is this Block object probably a header block?
Header blocks come before the blocks holding the actual file
data and contain information such as the filename, the file
type, length, and other information depending on the file type.
Returns True if this is probably a header, or False if probably
not.
"""
return (len(self.data) == 19 and self.data[0] == 0)
def isdatablock(self):
"""
Is this Block object probably a data block?
Data blocks come after the Header blocks and contain the data
of a file.
Returns True if this is probably a data, or False if probably
not.
"""
return len(self.data) > 0 and not self.isheader()
def getpayloadlength(self):
"""
Returns the length of the data described by this block. Note
that the actual length of a block is longer as it often contains
details such as the length of a block, a flag, and a checksum.
"""
return len(self.data) - 2
def getpayload(self):
"""
Returns the actual data that the block this describes would hold
(without flag or checksum).
Returns None if block doesn't have data in it.
"""
return self.data[1: -1]
def getpayloadstartoffset(self):
"""
This returns the offset to the data of a block of a tap file in
the origional stream. This is only as acurate as the offset
value passed in the contructor. Returns the offset to the data
in the origional stream used to create this object.
"""
return self.filePosition + 12
def blocktype(self):
"""
This returns the type for this block for use in listing.
"""
return "TZX Pure Data"
def __str__(self):
"""Returns a basic String summary of the Block object."""
return "TZX Pure Data Block. Flag:{}, block length:{}, pause \
afterwards: {}ms".format(self.flag, self.getpayloadlength(), self.endPause)
def getpackagedforfile(self):
"""