1from test.support import findfile
2from test.support.os_helper import TESTFN, unlink
3from test.support.warnings_helper import check_no_resource_warning, import_deprecated
4import unittest
5from unittest import mock
6from test import audiotests
7import io
8import sys
9import struct
10
11
12aifc = import_deprecated("aifc")
13audioop = import_deprecated("audioop")
14
15
16class AifcTest(audiotests.AudioWriteTests,
17               audiotests.AudioTestsWithSourceFile):
18    module = aifc
19    close_fd = True
20    test_unseekable_read = None
21
22
23class AifcPCM8Test(AifcTest, unittest.TestCase):
24    sndfilename = 'pluck-pcm8.aiff'
25    sndfilenframes = 3307
26    nchannels = 2
27    sampwidth = 1
28    framerate = 11025
29    nframes = 48
30    comptype = b'NONE'
31    compname = b'not compressed'
32    frames = bytes.fromhex("""\
33      02FF 4B00 3104 8008 CB06 4803 BF01 03FE B8FA B4F3 29EB 1AE6 \
34      EDE4 C6E2 0EE0 EFE0 57E2 FBE8 13EF D8F7 97FB F5FC 08FB DFFB \
35      11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F14 8012 \
36      490E 520D EF0F CE0F E40C 630A 080A 2B0B 510E 8B11 B60E 440A \
37      """)
38
39
40class AifcPCM16Test(AifcTest, unittest.TestCase):
41    sndfilename = 'pluck-pcm16.aiff'
42    sndfilenframes = 3307
43    nchannels = 2
44    sampwidth = 2
45    framerate = 11025
46    nframes = 48
47    comptype = b'NONE'
48    compname = b'not compressed'
49    frames = bytes.fromhex("""\
50      022EFFEA 4B5D00F6 311804EA 80E10840 CBE106B1 48A903F5 BFE601B2 036CFE7B \
51      B858FA3E B4B1F34F 299AEBCA 1A5DE6DA EDFAE491 C628E275 0E09E0B5 EF2AE029 \
52      5758E271 FB35E83F 1376EF86 D82BF727 9790FB76 F5FAFC0F 0867FB9C DF30FB43 \
53      117EFA36 3EE5FB5B BC79FCB1 66D9FF5D CF150412 431D097C C1BA0EC8 512112A1 \
54      EEE21753 82071665 7FFF1443 8004128F 49A20EAF 52BB0DBA EFB40F60 CE3C0FBF \
55      E4B30CEC 63430A5C 08C80A20 2BBB0B08 514A0E43 8BCF1139 B6F60EEB 44120A5E \
56      """)
57
58
59class AifcPCM24Test(AifcTest, unittest.TestCase):
60    sndfilename = 'pluck-pcm24.aiff'
61    sndfilenframes = 3307
62    nchannels = 2
63    sampwidth = 3
64    framerate = 11025
65    nframes = 48
66    comptype = b'NONE'
67    compname = b'not compressed'
68    frames = bytes.fromhex("""\
69      022D65FFEB9D 4B5A0F00FA54 3113C304EE2B 80DCD6084303 \
70      CBDEC006B261 48A99803F2F8 BFE82401B07D 036BFBFE7B5D \
71      B85756FA3EC9 B4B055F3502B 299830EBCB62 1A5CA7E6D99A \
72      EDFA3EE491BD C625EBE27884 0E05A9E0B6CF EF2929E02922 \
73      5758D8E27067 FB3557E83E16 1377BFEF8402 D82C5BF7272A \
74      978F16FB7745 F5F865FC1013 086635FB9C4E DF30FCFB40EE \
75      117FE0FA3438 3EE6B8FB5AC3 BC77A3FCB2F4 66D6DAFF5F32 \
76      CF13B9041275 431D69097A8C C1BB600EC74E 5120B912A2BA \
77      EEDF641754C0 8207001664B7 7FFFFF14453F 8000001294E6 \
78      499C1B0EB3B2 52B73E0DBCA0 EFB2B20F5FD8 CE3CDB0FBE12 \
79      E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0E \
80      51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48 \
81      """)
82
83
84class AifcPCM32Test(AifcTest, unittest.TestCase):
85    sndfilename = 'pluck-pcm32.aiff'
86    sndfilenframes = 3307
87    nchannels = 2
88    sampwidth = 4
89    framerate = 11025
90    nframes = 48
91    comptype = b'NONE'
92    compname = b'not compressed'
93    frames = bytes.fromhex("""\
94      022D65BCFFEB9D92 4B5A0F8000FA549C 3113C34004EE2BC0 80DCD680084303E0 \
95      CBDEC0C006B26140 48A9980003F2F8FC BFE8248001B07D92 036BFB60FE7B5D34 \
96      B8575600FA3EC920 B4B05500F3502BC0 29983000EBCB6240 1A5CA7A0E6D99A60 \
97      EDFA3E80E491BD40 C625EB80E27884A0 0E05A9A0E0B6CFE0 EF292940E0292280 \
98      5758D800E2706700 FB3557D8E83E1640 1377BF00EF840280 D82C5B80F7272A80 \
99      978F1600FB774560 F5F86510FC101364 086635A0FB9C4E20 DF30FC40FB40EE28 \
100      117FE0A0FA3438B0 3EE6B840FB5AC3F0 BC77A380FCB2F454 66D6DA80FF5F32B4 \
101      CF13B980041275B0 431D6980097A8C00 C1BB60000EC74E00 5120B98012A2BAA0 \
102      EEDF64C01754C060 820700001664B780 7FFFFFFF14453F40 800000001294E6E0 \
103      499C1B000EB3B270 52B73E000DBCA020 EFB2B2E00F5FD880 CE3CDB400FBE1270 \
104      E4B49CC00CEA2D90 6344A8800A5A7CA0 08C8FE800A1FFEE0 2BB986C00B0A0E00 \
105      51486F800E44E190 8BCC6480113B0580 B6F4EC000EEB3630 441317800A5B48A0 \
106      """)
107
108
109class AifcULAWTest(AifcTest, unittest.TestCase):
110    sndfilename = 'pluck-ulaw.aifc'
111    sndfilenframes = 3307
112    nchannels = 2
113    sampwidth = 2
114    framerate = 11025
115    nframes = 48
116    comptype = b'ulaw'
117    compname = b''
118    frames = bytes.fromhex("""\
119      022CFFE8 497C0104 307C04DC 8284083C CB84069C 497C03DC BE8401AC 036CFE74 \
120      B684FA24 B684F344 2A7CEC04 19FCE704 EE04E504 C584E204 0E3CE104 EF04DF84 \
121      557CE204 FB24E804 12FCEF04 D784F744 9684FB64 F5C4FC24 083CFBA4 DF84FB24 \
122      11FCFA24 3E7CFB64 BA84FCB4 657CFF5C CF84041C 417C093C C1840EBC 517C12FC \
123      EF0416FC 828415FC 7D7C13FC 828412FC 497C0EBC 517C0DBC F0040F3C CD840FFC \
124      E5040CBC 617C0A3C 08BC0A3C 2C7C0B3C 517C0E3C 8A8410FC B6840EBC 457C0A3C \
125      """)
126    if sys.byteorder != 'big':
127        frames = audioop.byteswap(frames, 2)
128
129
130class AifcALAWTest(AifcTest, unittest.TestCase):
131    sndfilename = 'pluck-alaw.aifc'
132    sndfilenframes = 3307
133    nchannels = 2
134    sampwidth = 2
135    framerate = 11025
136    nframes = 48
137    comptype = b'alaw'
138    compname = b''
139    frames = bytes.fromhex("""\
140      0230FFE8 4A0000F8 310004E0 82000840 CB0006A0 4A0003F0 BE0001A8 0370FE78 \
141      BA00FA20 B600F340 2900EB80 1A80E680 ED80E480 C700E280 0E40E080 EF80E080 \
142      5600E280 FB20E880 1380EF80 D900F740 9600FB60 F5C0FC10 0840FBA0 DF00FB20 \
143      1180FA20 3F00FB60 BE00FCB0 6600FF58 CF000420 42000940 C1000EC0 52001280 \
144      EE801780 82001680 7E001480 82001280 4A000EC0 52000DC0 EF800F40 CF000FC0 \
145      E4800CC0 62000A40 08C00A40 2B000B40 52000E40 8A001180 B6000EC0 46000A40 \
146      """)
147    if sys.byteorder != 'big':
148        frames = audioop.byteswap(frames, 2)
149
150
151class AifcMiscTest(unittest.TestCase):
152    def test_skipunknown(self):
153        #Issue 2245
154        #This file contains chunk types aifc doesn't recognize.
155        f = aifc.open(findfile('Sine-1000Hz-300ms.aif'))
156        f.close()
157
158    def test_close_opened_files_on_error(self):
159        non_aifc_file = findfile('pluck-pcm8.wav', subdir='audiodata')
160        with check_no_resource_warning(self):
161            with self.assertRaises(aifc.Error):
162                # Try opening a non-AIFC file, with the expectation that
163                # `aifc.open` will fail (without raising a ResourceWarning)
164                self.f = aifc.open(non_aifc_file, 'rb')
165
166            # Aifc_write.initfp() won't raise in normal case.  But some errors
167            # (e.g. MemoryError, KeyboardInterrupt, etc..) can happen.
168            with mock.patch.object(aifc.Aifc_write, 'initfp',
169                                   side_effect=RuntimeError):
170                with self.assertRaises(RuntimeError):
171                    self.fout = aifc.open(TESTFN, 'wb')
172
173    def test_params_added(self):
174        f = self.f = aifc.open(TESTFN, 'wb')
175        f.aiff()
176        f.setparams((1, 1, 1, 1, b'NONE', b''))
177        f.close()
178
179        f = aifc.open(TESTFN, 'rb')
180        self.addCleanup(f.close)
181        params = f.getparams()
182        self.assertEqual(params.nchannels, f.getnchannels())
183        self.assertEqual(params.sampwidth, f.getsampwidth())
184        self.assertEqual(params.framerate, f.getframerate())
185        self.assertEqual(params.nframes, f.getnframes())
186        self.assertEqual(params.comptype, f.getcomptype())
187        self.assertEqual(params.compname, f.getcompname())
188
189    def test_write_header_comptype_sampwidth(self):
190        for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
191            fout = aifc.open(io.BytesIO(), 'wb')
192            fout.setnchannels(1)
193            fout.setframerate(1)
194            fout.setcomptype(comptype, b'')
195            fout.close()
196            self.assertEqual(fout.getsampwidth(), 2)
197            fout.initfp(None)
198
199    def test_write_markers_values(self):
200        fout = aifc.open(io.BytesIO(), 'wb')
201        self.assertEqual(fout.getmarkers(), None)
202        fout.setmark(1, 0, b'foo1')
203        fout.setmark(1, 1, b'foo2')
204        self.assertEqual(fout.getmark(1), (1, 1, b'foo2'))
205        self.assertEqual(fout.getmarkers(), [(1, 1, b'foo2')])
206        fout.initfp(None)
207
208    def test_read_markers(self):
209        fout = self.fout = aifc.open(TESTFN, 'wb')
210        fout.aiff()
211        fout.setparams((1, 1, 1, 1, b'NONE', b''))
212        fout.setmark(1, 0, b'odd')
213        fout.setmark(2, 0, b'even')
214        fout.writeframes(b'\x00')
215        fout.close()
216        f = aifc.open(TESTFN, 'rb')
217        self.addCleanup(f.close)
218        self.assertEqual(f.getmarkers(), [(1, 0, b'odd'), (2, 0, b'even')])
219        self.assertEqual(f.getmark(1), (1, 0, b'odd'))
220        self.assertEqual(f.getmark(2), (2, 0, b'even'))
221        self.assertRaises(aifc.Error, f.getmark, 3)
222
223
224class AIFCLowLevelTest(unittest.TestCase):
225
226    def test_read_written(self):
227        def read_written(self, what):
228            f = io.BytesIO()
229            getattr(aifc, '_write_' + what)(f, x)
230            f.seek(0)
231            return getattr(aifc, '_read_' + what)(f)
232        for x in (-1, 0, 0.1, 1):
233            self.assertEqual(read_written(x, 'float'), x)
234        for x in (float('NaN'), float('Inf')):
235            self.assertEqual(read_written(x, 'float'), aifc._HUGE_VAL)
236        for x in (b'', b'foo', b'a' * 255):
237            self.assertEqual(read_written(x, 'string'), x)
238        for x in (-0x7FFFFFFF, -1, 0, 1, 0x7FFFFFFF):
239            self.assertEqual(read_written(x, 'long'), x)
240        for x in (0, 1, 0xFFFFFFFF):
241            self.assertEqual(read_written(x, 'ulong'), x)
242        for x in (-0x7FFF, -1, 0, 1, 0x7FFF):
243            self.assertEqual(read_written(x, 'short'), x)
244        for x in (0, 1, 0xFFFF):
245            self.assertEqual(read_written(x, 'ushort'), x)
246
247    def test_read_raises(self):
248        f = io.BytesIO(b'\x00')
249        self.assertRaises(EOFError, aifc._read_ulong, f)
250        self.assertRaises(EOFError, aifc._read_long, f)
251        self.assertRaises(EOFError, aifc._read_ushort, f)
252        self.assertRaises(EOFError, aifc._read_short, f)
253
254    def test_write_long_string_raises(self):
255        f = io.BytesIO()
256        with self.assertRaises(ValueError):
257            aifc._write_string(f, b'too long' * 255)
258
259    def test_wrong_open_mode(self):
260        with self.assertRaises(aifc.Error):
261            aifc.open(TESTFN, 'wrong_mode')
262
263    def test_read_wrong_form(self):
264        b1 = io.BytesIO(b'WRNG' + struct.pack('>L', 0))
265        b2 = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'WRNG')
266        self.assertRaises(aifc.Error, aifc.open, b1)
267        self.assertRaises(aifc.Error, aifc.open, b2)
268
269    def test_read_no_comm_chunk(self):
270        b = io.BytesIO(b'FORM' + struct.pack('>L', 4) + b'AIFF')
271        self.assertRaises(aifc.Error, aifc.open, b)
272
273    def test_read_no_ssnd_chunk(self):
274        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
275        b += b'COMM' + struct.pack('>LhlhhLL', 38, 1, 0, 8,
276                                   0x4000 | 12, 11025<<18, 0)
277        b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
278        with self.assertRaisesRegex(aifc.Error, 'COMM chunk and/or SSND chunk'
279                                                ' missing'):
280            aifc.open(io.BytesIO(b))
281
282    def test_read_wrong_compression_type(self):
283        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
284        b += b'COMM' + struct.pack('>LhlhhLL', 23, 1, 0, 8,
285                                   0x4000 | 12, 11025<<18, 0)
286        b += b'WRNG' + struct.pack('B', 0)
287        self.assertRaises(aifc.Error, aifc.open, io.BytesIO(b))
288
289    def test_read_wrong_number_of_channels(self):
290        for nchannels in 0, -1:
291            b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
292            b += b'COMM' + struct.pack('>LhlhhLL', 38, nchannels, 0, 8,
293                                       0x4000 | 12, 11025<<18, 0)
294            b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
295            b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
296            with self.assertRaisesRegex(aifc.Error, 'bad # of channels'):
297                aifc.open(io.BytesIO(b))
298
299    def test_read_wrong_sample_width(self):
300        for sampwidth in 0, -1:
301            b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
302            b += b'COMM' + struct.pack('>LhlhhLL', 38, 1, 0, sampwidth,
303                                       0x4000 | 12, 11025<<18, 0)
304            b += b'NONE' + struct.pack('B', 14) + b'not compressed' + b'\x00'
305            b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
306            with self.assertRaisesRegex(aifc.Error, 'bad sample width'):
307                aifc.open(io.BytesIO(b))
308
309    def test_read_wrong_marks(self):
310        b = b'FORM' + struct.pack('>L', 4) + b'AIFF'
311        b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8,
312                                   0x4000 | 12, 11025<<18, 0)
313        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
314        b += b'MARK' + struct.pack('>LhB', 3, 1, 1)
315        with self.assertWarns(UserWarning) as cm:
316            f = aifc.open(io.BytesIO(b))
317        self.assertEqual(str(cm.warning), 'Warning: MARK chunk contains '
318                                          'only 0 markers instead of 1')
319        self.assertEqual(f.getmarkers(), None)
320
321    def test_read_comm_kludge_compname_even(self):
322        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
323        b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8,
324                                   0x4000 | 12, 11025<<18, 0)
325        b += b'NONE' + struct.pack('B', 4) + b'even' + b'\x00'
326        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
327        with self.assertWarns(UserWarning) as cm:
328            f = aifc.open(io.BytesIO(b))
329        self.assertEqual(str(cm.warning), 'Warning: bad COMM chunk size')
330        self.assertEqual(f.getcompname(), b'even')
331
332    def test_read_comm_kludge_compname_odd(self):
333        b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
334        b += b'COMM' + struct.pack('>LhlhhLL', 18, 1, 0, 8,
335                                   0x4000 | 12, 11025<<18, 0)
336        b += b'NONE' + struct.pack('B', 3) + b'odd'
337        b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
338        with self.assertWarns(UserWarning) as cm:
339            f = aifc.open(io.BytesIO(b))
340        self.assertEqual(str(cm.warning), 'Warning: bad COMM chunk size')
341        self.assertEqual(f.getcompname(), b'odd')
342
343    def test_write_params_raises(self):
344        fout = aifc.open(io.BytesIO(), 'wb')
345        wrong_params = (0, 0, 0, 0, b'WRNG', '')
346        self.assertRaises(aifc.Error, fout.setparams, wrong_params)
347        self.assertRaises(aifc.Error, fout.getparams)
348        self.assertRaises(aifc.Error, fout.setnchannels, 0)
349        self.assertRaises(aifc.Error, fout.getnchannels)
350        self.assertRaises(aifc.Error, fout.setsampwidth, 0)
351        self.assertRaises(aifc.Error, fout.getsampwidth)
352        self.assertRaises(aifc.Error, fout.setframerate, 0)
353        self.assertRaises(aifc.Error, fout.getframerate)
354        self.assertRaises(aifc.Error, fout.setcomptype, b'WRNG', '')
355        fout.aiff()
356        fout.setnchannels(1)
357        fout.setsampwidth(1)
358        fout.setframerate(1)
359        fout.setnframes(1)
360        fout.writeframes(b'\x00')
361        self.assertRaises(aifc.Error, fout.setparams, (1, 1, 1, 1, 1, 1))
362        self.assertRaises(aifc.Error, fout.setnchannels, 1)
363        self.assertRaises(aifc.Error, fout.setsampwidth, 1)
364        self.assertRaises(aifc.Error, fout.setframerate, 1)
365        self.assertRaises(aifc.Error, fout.setnframes, 1)
366        self.assertRaises(aifc.Error, fout.setcomptype, b'NONE', '')
367        self.assertRaises(aifc.Error, fout.aiff)
368        self.assertRaises(aifc.Error, fout.aifc)
369
370    def test_write_params_singles(self):
371        fout = aifc.open(io.BytesIO(), 'wb')
372        fout.aifc()
373        fout.setnchannels(1)
374        fout.setsampwidth(2)
375        fout.setframerate(3)
376        fout.setnframes(4)
377        fout.setcomptype(b'NONE', b'name')
378        self.assertEqual(fout.getnchannels(), 1)
379        self.assertEqual(fout.getsampwidth(), 2)
380        self.assertEqual(fout.getframerate(), 3)
381        self.assertEqual(fout.getnframes(), 0)
382        self.assertEqual(fout.tell(), 0)
383        self.assertEqual(fout.getcomptype(), b'NONE')
384        self.assertEqual(fout.getcompname(), b'name')
385        fout.writeframes(b'\x00' * 4 * fout.getsampwidth() * fout.getnchannels())
386        self.assertEqual(fout.getnframes(), 4)
387        self.assertEqual(fout.tell(), 4)
388
389    def test_write_params_bunch(self):
390        fout = aifc.open(io.BytesIO(), 'wb')
391        fout.aifc()
392        p = (1, 2, 3, 4, b'NONE', b'name')
393        fout.setparams(p)
394        self.assertEqual(fout.getparams(), p)
395        fout.initfp(None)
396
397    def test_write_header_raises(self):
398        fout = aifc.open(io.BytesIO(), 'wb')
399        self.assertRaises(aifc.Error, fout.close)
400        fout = aifc.open(io.BytesIO(), 'wb')
401        fout.setnchannels(1)
402        self.assertRaises(aifc.Error, fout.close)
403        fout = aifc.open(io.BytesIO(), 'wb')
404        fout.setnchannels(1)
405        fout.setsampwidth(1)
406        self.assertRaises(aifc.Error, fout.close)
407
408    def test_write_header_comptype_raises(self):
409        for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
410            fout = aifc.open(io.BytesIO(), 'wb')
411            fout.setsampwidth(1)
412            fout.setcomptype(comptype, b'')
413            self.assertRaises(aifc.Error, fout.close)
414            fout.initfp(None)
415
416    def test_write_markers_raises(self):
417        fout = aifc.open(io.BytesIO(), 'wb')
418        self.assertRaises(aifc.Error, fout.setmark, 0, 0, b'')
419        self.assertRaises(aifc.Error, fout.setmark, 1, -1, b'')
420        self.assertRaises(aifc.Error, fout.setmark, 1, 0, None)
421        self.assertRaises(aifc.Error, fout.getmark, 1)
422        fout.initfp(None)
423
424    def test_write_aiff_by_extension(self):
425        sampwidth = 2
426        filename = TESTFN + '.aiff'
427        fout = self.fout = aifc.open(filename, 'wb')
428        self.addCleanup(unlink, filename)
429        fout.setparams((1, sampwidth, 1, 1, b'ULAW', b''))
430        frames = b'\x00' * fout.getnchannels() * sampwidth
431        fout.writeframes(frames)
432        fout.close()
433        f = self.f = aifc.open(filename, 'rb')
434        self.assertEqual(f.getcomptype(), b'NONE')
435        f.close()
436
437
438if __name__ == "__main__":
439    unittest.main()
440