]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2s/pd.py
license: remove FSF postal address from boiler plate license text
[libsigrokdecode.git] / decoders / i2s / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
18 ##
19
20 import sigrokdecode as srd
21
22 '''
23 OUTPUT_PYTHON format:
24
25 Packet:
26 [<ptype>, <pdata>]
27
28 <ptype>, <pdata>:
29  - 'DATA', [<channel>, <value>]
30
31 <channel>: 'L' or 'R'
32 <value>: integer
33 '''
34
35 class SamplerateError(Exception):
36     pass
37
38 class Decoder(srd.Decoder):
39     api_version = 3
40     id = 'i2s'
41     name = 'I²S'
42     longname = 'Integrated Interchip Sound'
43     desc = 'Serial bus for connecting digital audio devices.'
44     license = 'gplv2+'
45     inputs = ['logic']
46     outputs = ['i2s']
47     channels = (
48         {'id': 'sck', 'name': 'SCK', 'desc': 'Bit clock line'},
49         {'id': 'ws', 'name': 'WS', 'desc': 'Word select line'},
50         {'id': 'sd', 'name': 'SD', 'desc': 'Serial data line'},
51     )
52     annotations = (
53         ('left', 'Left channel'),
54         ('right', 'Right channel'),
55         ('warnings', 'Warnings'),
56     )
57     binary = (
58         ('wav', 'WAV file'),
59     )
60
61     def __init__(self):
62         self.samplerate = None
63         self.oldws = 1
64         self.bitcount = 0
65         self.data = 0
66         self.samplesreceived = 0
67         self.first_sample = None
68         self.ss_block = None
69         self.wordlength = -1
70         self.wrote_wav_header = False
71
72     def start(self):
73         self.out_python = self.register(srd.OUTPUT_PYTHON)
74         self.out_binary = self.register(srd.OUTPUT_BINARY)
75         self.out_ann = self.register(srd.OUTPUT_ANN)
76
77     def metadata(self, key, value):
78         if key == srd.SRD_CONF_SAMPLERATE:
79             self.samplerate = value
80
81     def putpb(self, data):
82         self.put(self.ss_block, self.samplenum, self.out_python, data)
83
84     def putbin(self, data):
85         self.put(self.ss_block, self.samplenum, self.out_binary, data)
86
87     def putb(self, data):
88         self.put(self.ss_block, self.samplenum, self.out_ann, data)
89
90     def report(self):
91
92         # Calculate the sample rate.
93         samplerate = '?'
94         if self.ss_block is not None and \
95             self.first_sample is not None and \
96             self.ss_block > self.first_sample:
97             samplerate = '%d' % (self.samplesreceived *
98                 self.samplerate / (self.ss_block -
99                 self.first_sample))
100
101         return 'I²S: %d %d-bit samples received at %sHz' % \
102             (self.samplesreceived, self.wordlength, samplerate)
103
104     def wav_header(self):
105         # Chunk descriptor
106         h  = b'RIFF'
107         h += b'\x24\x80\x00\x00' # Chunk size (2084)
108         h += b'WAVE'
109         # Fmt subchunk
110         h += b'fmt '
111         h += b'\x10\x00\x00\x00' # Subchunk size (16 bytes)
112         h += b'\x01\x00'         # Audio format (0x0001 == PCM)
113         h += b'\x02\x00'         # Number of channels (2)
114         h += b'\x80\x3e\x00\x00' # Samplerate (16000)
115         h += b'\x00\x7d\x00\x00' # Byterate (32000)
116         h += b'\x04\x00'         # Blockalign (4)
117         h += b'\x10\x00'         # Bits per sample (16)
118         # Data subchunk
119         h += b'data'
120         h += b'\xff\xff\x00\x00' # Subchunk size (65535 bytes) TODO
121         return h
122
123     def wav_sample(self, sample):
124         # TODO: This currently assumes U32 samples, and converts to S16.
125         s = sample >> 16
126         if s >= 0x8000:
127             s -= 0x10000
128         lo, hi = s & 0xff, (s >> 8) & 0xff
129         return bytes([lo, hi])
130
131     def decode(self):
132         if not self.samplerate:
133             raise SamplerateError('Cannot decode without samplerate.')
134         while True:
135             # Wait for a rising edge on the SCK pin.
136             sck, ws, sd = self.wait({0: 'r'})
137
138             self.data = (self.data << 1) | sd
139             self.bitcount += 1
140
141             # This was not the LSB unless WS has flipped.
142             if ws == self.oldws:
143                 continue
144
145             # Only submit the sample, if we received the beginning of it.
146             if self.ss_block is not None:
147
148                 if not self.wrote_wav_header:
149                     self.put(0, 0, self.out_binary, [0, self.wav_header()])
150                     self.wrote_wav_header = True
151
152                 self.samplesreceived += 1
153
154                 idx = 0 if self.oldws else 1
155                 c1 = 'Left channel' if self.oldws else 'Right channel'
156                 c2 = 'Left' if self.oldws else 'Right'
157                 c3 = 'L' if self.oldws else 'R'
158                 v = '%08x' % self.data
159                 self.putpb(['DATA', [c3, self.data]])
160                 self.putb([idx, ['%s: %s' % (c1, v), '%s: %s' % (c2, v),
161                                  '%s: %s' % (c3, v), c3]])
162                 self.putbin([0, self.wav_sample(self.data)])
163
164                 # Check that the data word was the correct length.
165                 if self.wordlength != -1 and self.wordlength != self.bitcount:
166                     self.putb([2, ['Received %d-bit word, expected %d-bit '
167                                    'word' % (self.bitcount, self.wordlength)]])
168
169                 self.wordlength = self.bitcount
170
171             # Reset decoder state.
172             self.data = 0
173             self.bitcount = 0
174             self.ss_block = self.samplenum
175
176             # Save the first sample position.
177             if self.first_sample is None:
178                 self.first_sample = self.samplenum
179
180             self.oldws = ws