]> sigrok.org Git - libsigrokdecode.git/blobdiff - decoders/i2s/pd.py
license: remove FSF postal address from boiler plate license text
[libsigrokdecode.git] / decoders / i2s / pd.py
index 9f04e1030ec7d66598c3c3acf098235bfa7cc3a8..b0b177f1f007f0687e460db06e49361121af18a3 100644 (file)
 ## GNU General Public License for more details.
 ##
 ## You should have received a copy of the GNU General Public License
-## along with this program; if not, write to the Free Software
-## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
 ##
 
-# I²S protocol decoder
-
 import sigrokdecode as srd
 
 '''
-Protocol output format:
+OUTPUT_PYTHON format:
 
 Packet:
 [<ptype>, <pdata>]
@@ -35,8 +32,11 @@ Packet:
 <value>: integer
 '''
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
-    api_version = 1
+    api_version = 3
     id = 'i2s'
     name = 'I²S'
     longname = 'Integrated Interchip Sound'
@@ -44,32 +44,34 @@ class Decoder(srd.Decoder):
     license = 'gplv2+'
     inputs = ['logic']
     outputs = ['i2s']
-    probes = [
+    channels = (
         {'id': 'sck', 'name': 'SCK', 'desc': 'Bit clock line'},
         {'id': 'ws', 'name': 'WS', 'desc': 'Word select line'},
         {'id': 'sd', 'name': 'SD', 'desc': 'Serial data line'},
-    ]
-    optional_probes = []
-    options = {}
-    annotations = [
-        ['left', 'Left channel'],
-        ['right', 'Right channel'],
-        ['warnings', 'Warnings'],
-    ]
-
-    def __init__(self, **kwargs):
+    )
+    annotations = (
+        ('left', 'Left channel'),
+        ('right', 'Right channel'),
+        ('warnings', 'Warnings'),
+    )
+    binary = (
+        ('wav', 'WAV file'),
+    )
+
+    def __init__(self):
         self.samplerate = None
-        self.oldsck = 1
         self.oldws = 1
         self.bitcount = 0
         self.data = 0
         self.samplesreceived = 0
         self.first_sample = None
-        self.start_sample = None
+        self.ss_block = None
         self.wordlength = -1
+        self.wrote_wav_header = False
 
     def start(self):
-        self.out_proto = self.register(srd.OUTPUT_PYTHON)
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def metadata(self, key, value):
@@ -77,37 +79,61 @@ class Decoder(srd.Decoder):
             self.samplerate = value
 
     def putpb(self, data):
-        self.put(self.start_sample, self.samplenum, self.out_proto, data)
+        self.put(self.ss_block, self.samplenum, self.out_python, data)
+
+    def putbin(self, data):
+        self.put(self.ss_block, self.samplenum, self.out_binary, data)
 
     def putb(self, data):
-        self.put(self.start_sample, self.samplenum, self.out_ann, data)
+        self.put(self.ss_block, self.samplenum, self.out_ann, data)
 
     def report(self):
 
         # Calculate the sample rate.
         samplerate = '?'
-        if self.start_sample != None and \
-            self.first_sample != None and \
-            self.start_sample > self.first_sample:
+        if self.ss_block is not None and \
+            self.first_sample is not None and \
+            self.ss_block > self.first_sample:
             samplerate = '%d' % (self.samplesreceived *
-                self.samplerate / (self.start_sample -
+                self.samplerate / (self.ss_block -
                 self.first_sample))
 
         return 'I²S: %d %d-bit samples received at %sHz' % \
             (self.samplesreceived, self.wordlength, samplerate)
 
-    def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
-        for self.samplenum, (sck, ws, sd) in data:
-
-            # Ignore sample if the bit clock hasn't changed.
-            if sck == self.oldsck:
-                continue
-
-            self.oldsck = sck
-            if sck == 0:   # Ignore the falling clock edge.
-                continue
+    def wav_header(self):
+        # Chunk descriptor
+        h  = b'RIFF'
+        h += b'\x24\x80\x00\x00' # Chunk size (2084)
+        h += b'WAVE'
+        # Fmt subchunk
+        h += b'fmt '
+        h += b'\x10\x00\x00\x00' # Subchunk size (16 bytes)
+        h += b'\x01\x00'         # Audio format (0x0001 == PCM)
+        h += b'\x02\x00'         # Number of channels (2)
+        h += b'\x80\x3e\x00\x00' # Samplerate (16000)
+        h += b'\x00\x7d\x00\x00' # Byterate (32000)
+        h += b'\x04\x00'         # Blockalign (4)
+        h += b'\x10\x00'         # Bits per sample (16)
+        # Data subchunk
+        h += b'data'
+        h += b'\xff\xff\x00\x00' # Subchunk size (65535 bytes) TODO
+        return h
+
+    def wav_sample(self, sample):
+        # TODO: This currently assumes U32 samples, and converts to S16.
+        s = sample >> 16
+        if s >= 0x8000:
+            s -= 0x10000
+        lo, hi = s & 0xff, (s >> 8) & 0xff
+        return bytes([lo, hi])
+
+    def decode(self):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        while True:
+            # Wait for a rising edge on the SCK pin.
+            sck, ws, sd = self.wait({0: 'r'})
 
             self.data = (self.data << 1) | sd
             self.bitcount += 1
@@ -117,7 +143,12 @@ class Decoder(srd.Decoder):
                 continue
 
             # Only submit the sample, if we received the beginning of it.
-            if self.start_sample != None:
+            if self.ss_block is not None:
+
+                if not self.wrote_wav_header:
+                    self.put(0, 0, self.out_binary, [0, self.wav_header()])
+                    self.wrote_wav_header = True
+
                 self.samplesreceived += 1
 
                 idx = 0 if self.oldws else 1
@@ -128,6 +159,7 @@ class Decoder(srd.Decoder):
                 self.putpb(['DATA', [c3, self.data]])
                 self.putb([idx, ['%s: %s' % (c1, v), '%s: %s' % (c2, v),
                                  '%s: %s' % (c3, v), c3]])
+                self.putbin([0, self.wav_sample(self.data)])
 
                 # Check that the data word was the correct length.
                 if self.wordlength != -1 and self.wordlength != self.bitcount:
@@ -139,11 +171,10 @@ class Decoder(srd.Decoder):
             # Reset decoder state.
             self.data = 0
             self.bitcount = 0
-            self.start_sample = self.samplenum
+            self.ss_block = self.samplenum
 
             # Save the first sample position.
-            if self.first_sample == None:
+            if self.first_sample is None:
                 self.first_sample = self.samplenum
 
             self.oldws = ws
-