root/branches/libffado-2.0/src/libstreaming/motu/MotuReceiveStreamProcessor.cpp

Revision 1721, 20.5 kB (checked in by ppalmers, 14 years ago)

fix all format string warnings

Line 
1 /*
2  * Copyright (C) 2005-2008 by Jonathan Woithe
3  * Copyright (C) 2005-2008 by Pieter Palmers
4  *
5  * This file is part of FFADO
6  * FFADO = Free Firewire (pro-)audio drivers for linux
7  *
8  * FFADO is based upon FreeBoB.
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 2 of the License, or
13  * (at your option) version 3 of the License.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include "config.h"
26 #include "libutil/float_cast.h"
27
28 #include "MotuReceiveStreamProcessor.h"
29 #include "MotuPort.h"
30 #include "../StreamProcessorManager.h"
31 #include "devicemanager.h"
32
33 #include "libieee1394/ieee1394service.h"
34 #include "libieee1394/IsoHandlerManager.h"
35 #include "libieee1394/cycletimer.h"
36
37 #include "libutil/ByteSwap.h"
38
39 #include <cstring>
40 #include <math.h>
41 #include <assert.h>
42
43 /* Provide more intuitive access to GCC's branch predition built-ins */
44 #define likely(x)   __builtin_expect((x),1)
45 #define unlikely(x) __builtin_expect((x),0)
46
47
48 namespace Streaming {
49
50 // A macro to extract specific bits from a native endian quadlet
51 #define get_bits(_d,_start,_len) (((_d)>>((_start)-(_len)+1)) & ((1<<(_len))-1))
52
53 // Convert an SPH timestamp as received from the MOTU to a full timestamp in ticks.
54 static inline uint32_t sphRecvToFullTicks(uint32_t sph, uint32_t ct_now) {
55
56 uint32_t timestamp = CYCLE_TIMER_TO_TICKS(sph & 0x1ffffff);
57 uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(ct_now);
58
59 uint32_t ts_sec = CYCLE_TIMER_GET_SECS(ct_now);
60     // If the cycles have wrapped, correct ts_sec so it represents when timestamp
61     // was received.  The timestamps sent by the MOTU are always 1 or two cycles
62     // in advance of the cycle timer (reasons unknown at this stage).  In addition,
63     // iso buffering can delay the arrival of packets for quite a number of cycles
64     // (have seen a delay >12 cycles).
65     // Every so often we also see sph wrapping ahead of ct_now, so deal with that
66     // too.
67     if (unlikely(CYCLE_TIMER_GET_CYCLES(sph) > now_cycles + 1000)) {
68         if (likely(ts_sec))
69             ts_sec--;
70         else
71             ts_sec = 127;
72     } else
73     if (unlikely(now_cycles > CYCLE_TIMER_GET_CYCLES(sph) + 1000)) {
74         if (unlikely(ts_sec == 127))
75             ts_sec = 0;
76         else
77             ts_sec++;
78     }
79     return timestamp + ts_sec*TICKS_PER_SECOND;
80 }
81
82 MotuReceiveStreamProcessor::MotuReceiveStreamProcessor(FFADODevice &parent, unsigned int event_size)
83     : StreamProcessor(parent, ePT_Receive)
84     , m_event_size( event_size )
85     , mb_head ( 0 )
86     , mb_tail ( 0 )
87 {
88     memset(&m_devctrls, 0, sizeof(m_devctrls));
89 }
90
91 unsigned int
92 MotuReceiveStreamProcessor::getMaxPacketSize() {
93     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
94     return framerate<=48000?616:(framerate<=96000?1032:1160);
95 }
96
97 unsigned int
98 MotuReceiveStreamProcessor::getNominalFramesPerPacket() {
99     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
100     return framerate<=48000?8:(framerate<=96000?16:32);
101 }
102
103 bool
104 MotuReceiveStreamProcessor::prepareChild() {
105     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this);
106     return true;
107 }
108
109
110 /**
111  * Processes packet header to extract timestamps and check if the packet is valid
112  * @param data
113  * @param length
114  * @param channel
115  * @param tag
116  * @param sy
117  * @param cycle
118  * @return
119  */
120 enum StreamProcessor::eChildReturnValue
121 MotuReceiveStreamProcessor::processPacketHeader(unsigned char *data, unsigned int length,
122                                                 unsigned char tag, unsigned char sy,
123                                                 uint32_t pkt_ctr)
124 {
125     if (length > 8) {
126         // The iso data blocks from the MOTUs comprise a CIP-like
127         // header followed by a number of events (8 for 1x rates, 16
128         // for 2x rates, 32 for 4x rates).
129         quadlet_t *quadlet = (quadlet_t *)data;
130         unsigned int dbs = get_bits(CondSwapFromBus32(quadlet[0]), 23, 8);  // Size of one event in terms of fdf_size
131         unsigned int fdf_size = get_bits(CondSwapFromBus32(quadlet[1]), 23, 8) == 0x22 ? 32:0; // Event unit size in bits
132
133         // Don't even attempt to process a packet if it isn't what we expect
134         // from a MOTU.  Yes, an FDF value of 32 bears little relationship
135         // to the actual data (24 bit integer) sent by the MOTU - it's one
136         // of those areas where MOTU have taken a curious detour around the
137         // standards.  Do this check early on because for invalid packets
138         // dbs may not be what we expect, potentially causing issues later
139         // on.
140         if (tag!=1 || fdf_size!=32 || dbs==0) {
141             return eCRV_Invalid;
142         }
143
144         // m_event_size is the event size in bytes
145         unsigned int n_events = (length-8) / m_event_size;
146
147         // Acquire the timestamp of the last frame in the packet just
148         // received.  Since every frame from the MOTU has its own timestamp
149         // we can just pick it straight from the packet.
150         uint32_t last_sph = CondSwapFromBus32(*(quadlet_t *)(data+8+(n_events-1)*m_event_size));
151         m_last_timestamp = sphRecvToFullTicks(last_sph, m_Parent.get1394Service().getCycleTimer());
152
153         return eCRV_OK;
154     } else {
155         return eCRV_Invalid;
156     }
157 }
158
159 /**
160  * extract the data from the packet
161  * @pre the IEC61883 packet is valid according to isValidPacket
162  * @param data
163  * @param length
164  * @param channel
165  * @param tag
166  * @param sy
167  * @param pkt_ctr
168  * @return
169  */
170 enum StreamProcessor::eChildReturnValue
171 MotuReceiveStreamProcessor::processPacketData(unsigned char *data, unsigned int length) {
172     // m_event_size should never be zero
173     unsigned int n_events = (length-8) / m_event_size;
174
175     // we have to keep in mind that there are also
176     // some packets buffered by the ISO layer,
177     // at most x=m_handler->getWakeupInterval()
178     // these contain at most x*syt_interval
179     // frames, meaning that we might receive
180     // this packet x*syt_interval*ticks_per_frame
181     // later than expected (the real receive time)
182     #ifdef DEBUG
183     if(isRunning()) {
184         debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"STMP: %luticks | tpf=%f\n",
185             m_last_timestamp, getTicksPerFrame());
186     }
187     #endif
188
189     if(m_data_buffer->writeFrames(n_events, (char *)(data+8), m_last_timestamp)) {
190         return eCRV_OK;
191     } else {
192         return eCRV_XRun;
193     }
194 }
195
196 /***********************************************
197  * Encoding/Decoding API                       *
198  ***********************************************/
199 /**
200  * \brief write received events to the port ringbuffers.
201  */
202 bool MotuReceiveStreamProcessor::processReadBlock(char *data,
203                        unsigned int nevents, unsigned int offset)
204 {
205     bool no_problem=true;
206
207     /* Scan incoming block for device control events */
208     decodeMotuCtrlEvents(data, nevents);
209
210     for ( PortVectorIterator it = m_Ports.begin();
211           it != m_Ports.end();
212           ++it ) {
213         if((*it)->isDisabled()) {continue;};
214
215         Port *port=(*it);
216
217         switch(port->getPortType()) {
218
219         case Port::E_Audio:
220             if(decodeMotuEventsToPort(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
221                 debugWarning("Could not decode packet data to port %s\n",(*it)->getName().c_str());
222                 no_problem=false;
223             }
224             break;
225         case Port::E_Midi:
226              if(decodeMotuMidiEventsToPort(static_cast<MotuMidiPort *>(*it), (quadlet_t *)data, offset, nevents)) {
227                  debugWarning("Could not decode packet midi data to port %s\n",(*it)->getName().c_str());
228                  no_problem=false;
229              }
230             break;
231
232         default: // ignore
233             break;
234         }
235     }
236     return no_problem;
237 }
238
239 signed int MotuReceiveStreamProcessor::decodeMotuEventsToPort(MotuAudioPort *p,
240         quadlet_t *data, unsigned int offset, unsigned int nevents)
241 {
242     unsigned int j=0;
243
244     // Use char here since a port's source address won't necessarily be
245     // aligned; use of an unaligned quadlet_t may cause issues on
246     // certain architectures.  Besides, the source (data coming directly
247     // from the MOTU) isn't structured in quadlets anyway; it mainly
248     // consists of packed 24-bit integers.
249
250     unsigned char *src_data;
251     src_data = (unsigned char *)data + p->getPosition();
252
253     switch(m_StreamProcessorManager.getAudioDataType()) {
254         default:
255         case StreamProcessorManager::eADT_Int24:
256             {
257                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
258
259                 assert(nevents + offset <= p->getBufferSize());
260
261                 // Offset is in frames, but each port is only a single
262                 // channel, so the number of frames is the same as the
263                 // number of quadlets to offset (assuming the port buffer
264                 // uses one quadlet per sample, which is the case currently).
265                 buffer+=offset;
266
267                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
268                     *buffer = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
269                     // Sign-extend highest bit of 24-bit int.
270                     // This isn't strictly needed since E_Int24 is a 24-bit,
271                     // but doing so shouldn't break anything and makes the data
272                     // easier to deal with during debugging.
273                     if (*src_data & 0x80)
274                         *buffer |= 0xff000000;
275
276                     buffer++;
277                     src_data+=m_event_size;
278                 }
279             }
280             break;
281         case StreamProcessorManager::eADT_Float:
282             {
283                 const float multiplier = 1.0f / (float)(0x7FFFFF);
284                 float *buffer=(float *)(p->getBufferAddress());
285
286                 assert(nevents + offset <= p->getBufferSize());
287
288                 buffer+=offset;
289
290                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
291
292                     signed int v = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
293                     /* Sign-extend highest bit of incoming 24-bit integer */
294                     if (*src_data & 0x80)
295                       v |= 0xff000000;
296                     *buffer = v * multiplier;
297                     buffer++;
298                     src_data+=m_event_size;
299                 }
300             }
301             break;
302     }
303
304     return 0;
305 }
306
307 int
308 MotuReceiveStreamProcessor::decodeMotuMidiEventsToPort(
309                       MotuMidiPort *p, quadlet_t *data,
310                       unsigned int offset, unsigned int nevents)
311 {
312     unsigned int j = 0;
313     unsigned char *src = NULL;
314
315     quadlet_t *buffer = (quadlet_t *)(p->getBufferAddress());
316     assert(nevents + offset <= p->getBufferSize());
317     buffer += offset;
318
319     // Zero the buffer
320     memset(buffer, 0, nevents*sizeof(*buffer));
321
322     // Get MIDI bytes if present in any frames within the packet.  MOTU MIDI
323     // data is sent as part of a 3-byte sequence starting at the port's
324     // position.  Some MOTUs (eg: the 828MkII) send more than one MIDI byte
325     // in some packets.  Since the FFADO MIDI layer requires a MIDI byte in
326     // only every 8th buffer position we allow for this by buffering the
327     // incoming data.  The buffer is small since it only has to cover for
328     // short-term excursions in the data rate.  Since the MIDI data
329     // originates on a physical MIDI bus the overall data rate is limited by
330     // the baud rate of that bus (31250), which is no more than one byte in
331     // 8 even for 1x sample rates.
332     src = (unsigned char *)data + p->getPosition();
333     // We assume that the buffer has been set up in such a way that the first
334     // element is correctly aligned for FFADOs MIDI layer.  The requirement
335     // is that actual MIDI bytes must be aligned to multiples of 8 samples. 
336
337     while (j < nevents) {
338         /* Most events don't have MIDI data bytes */
339         if (unlikely((*src & MOTU_KEY_MASK_MIDI) == MOTU_KEY_MASK_MIDI)) {
340             // A MIDI byte is in *(src+2).  Bit 24 is used to flag MIDI data
341             // as present once the data makes it to the output buffer.
342             midibuffer[mb_head++] = 0x01000000 | *(src+2);
343             mb_head &= RX_MIDIBUFFER_SIZE-1;
344             if (unlikely(mb_head == mb_tail)) {
345                 debugWarning("MOTU rx MIDI buffer overflow\n");
346                 /* Dump oldest byte.  This overflow can only happen if the
347                  * rate coming in from the hardware MIDI port grossly
348                  * exceeds the official MIDI baud rate of 31250 bps, so it
349                  * should never occur in practice.
350                  */
351                 mb_tail = (mb_tail + 1) & (RX_MIDIBUFFER_SIZE-1);
352             }
353         }
354         /* Write to the buffer if we're at an 8-sample boundary */
355         if (unlikely(!(j & 0x07))) {
356             if (mb_head != mb_tail) {
357                 *buffer = midibuffer[mb_tail++];
358                 mb_tail &= RX_MIDIBUFFER_SIZE-1;
359             }
360             buffer += 8;
361         }
362         j++;
363         src += m_event_size;
364     }
365
366     return 0;   
367 }
368
369 int
370 MotuReceiveStreamProcessor::decodeMotuCtrlEvents(
371                       char *data, unsigned int nevents)
372 {
373     unsigned int j = 0;
374     unsigned char *src = NULL;
375     unsigned char *arg = NULL;
376
377     // Get control bytes if present in any frames within the packet.  The
378     // device control messages start at (zero-based) byte 0x04 in the data
379     // stream.
380     src = (unsigned char *)data + 0x04;
381     arg = src+1;
382     while (j < nevents) {
383         unsigned int control_key = *src & ~MOTU_KEY_MASK_MIDI;
384        
385         if (m_devctrls.status == MOTU_DEVCTRL_INVALID) {
386             // Start syncing on reception of the sequence sync key which indicates
387             // mix bus 1 values are pending.  Acquisition will start when we see the
388             // first channel gain key after this.
389             if (control_key==MOTU_KEY_SEQ_SYNC && *arg==MOTU_KEY_SEQ_SYNC_MIXBUS1) {
390                  debugOutput(DEBUG_LEVEL_VERBOSE, "syncing device control status stream\n");
391                  m_devctrls.status = MOTU_DEVCTRL_SYNCING;
392             }
393         } else
394         if (m_devctrls.status == MOTU_DEVCTRL_SYNCING) {
395             // Start acquiring when we see a channel gain key for mixbus 1.
396             if (control_key == MOTU_KEY_SEQ_SYNC) {
397                 // Keep mixbus index updated since we don't execute the main parser until
398                 // we move to the initialising state.  Since we don't dereference this until
399                 // we know it's equal to 0 there's no need for bounds checking here.
400                 m_devctrls.mixbus_index = *arg;
401             } else
402             if (control_key==MOTU_KEY_CHANNEL_GAIN && m_devctrls.mixbus_index==0) {
403               debugOutput(DEBUG_LEVEL_VERBOSE, "initialising device control status\n");
404               m_devctrls.status = MOTU_DEVCTRL_INIT;
405             }
406         } else
407         if (m_devctrls.status == MOTU_DEVCTRL_INIT) {
408             // Consider ourselves fully initialised when a control sequence sync key
409             // arrives which takes things back to mixbus 1.
410             if (control_key==MOTU_KEY_SEQ_SYNC && *arg==MOTU_KEY_SEQ_SYNC_MIXBUS1 && m_devctrls.mixbus_index>0) {
411                 debugOutput(DEBUG_LEVEL_VERBOSE, "device control status valid: n_mixbuses=%d, n_channels=%d\n",
412                     m_devctrls.n_mixbuses, m_devctrls.n_channels);
413                 m_devctrls.status = MOTU_DEVCTRL_VALID;
414             }
415         }
416
417         if (m_devctrls.status==MOTU_DEVCTRL_INIT || m_devctrls.status==MOTU_DEVCTRL_VALID) {
418             unsigned int i;
419             switch (control_key) {
420                 case MOTU_KEY_SEQ_SYNC:
421                     if (m_devctrls.mixbus_index < MOTUFW_MAX_MIXBUSES) {
422                         if (m_devctrls.n_channels==0 && m_devctrls.mixbus[m_devctrls.mixbus_index].channel_gain_index!=0) {
423                             m_devctrls.n_channels = m_devctrls.mixbus[m_devctrls.mixbus_index].channel_gain_index;
424                         }
425                     }
426                     /* Mix bus to configure next is in bits 5-7 of the argument */
427                     m_devctrls.mixbus_index = (*arg >> 5);
428                     if (m_devctrls.mixbus_index >= MOTUFW_MAX_MIXBUSES) {
429                         debugWarning("MOTU cuemix value parser error: mix bus index %d exceeded maximum %d\n",
430                             m_devctrls.mixbus_index, MOTUFW_MAX_MIXBUSES);
431                     } else {
432                         if (m_devctrls.n_mixbuses < m_devctrls.mixbus_index+1) {
433                             m_devctrls.n_mixbuses = m_devctrls.mixbus_index+1;
434                         }
435                         m_devctrls.mixbus[m_devctrls.mixbus_index].channel_gain_index =
436                             m_devctrls.mixbus[m_devctrls.mixbus_index].channel_pan_index =
437                             m_devctrls.mixbus[m_devctrls.mixbus_index].channel_control_index = 0;
438                         }
439                     break;
440                 case MOTU_KEY_CHANNEL_GAIN:
441                     i = m_devctrls.mixbus[m_devctrls.mixbus_index].channel_gain_index++;
442                     if (m_devctrls.mixbus_index<MOTUFW_MAX_MIXBUSES && i<MOTUFW_MAX_MIXBUS_CHANNELS) {
443                         m_devctrls.mixbus[m_devctrls.mixbus_index].channel_gain[i] = *arg;
444                     }
445                     if (i >= MOTUFW_MAX_MIXBUS_CHANNELS) {
446                         debugWarning("MOTU cuemix value parser error: channel gain index %d exceeded maximum %d\n",
447                             i, MOTUFW_MAX_MIXBUS_CHANNELS);
448                     }
449                     break;
450                 case MOTU_KEY_CHANNEL_PAN:
451                     i = m_devctrls.mixbus[m_devctrls.mixbus_index].channel_pan_index++;
452                     if (m_devctrls.mixbus_index<MOTUFW_MAX_MIXBUSES && i<MOTUFW_MAX_MIXBUS_CHANNELS) {
453                         m_devctrls.mixbus[m_devctrls.mixbus_index].channel_pan[i] = *arg;
454                     }
455                     if (i >= MOTUFW_MAX_MIXBUS_CHANNELS) {
456                         debugWarning("MOTU cuemix value parser error: channel pan index %d exceeded maximum %d\n",
457                             i, MOTUFW_MAX_MIXBUS_CHANNELS);
458                     }
459                     break;
460                 case MOTU_KEY_CHANNEL_CTRL:
461                     i = m_devctrls.mixbus[m_devctrls.mixbus_index].channel_control_index++;
462                     if (m_devctrls.mixbus_index<MOTUFW_MAX_MIXBUSES && i<MOTUFW_MAX_MIXBUS_CHANNELS) {
463                         m_devctrls.mixbus[m_devctrls.mixbus_index].channel_control[i] = *arg;
464                     }
465                     if (i >= MOTUFW_MAX_MIXBUS_CHANNELS) {
466                         debugWarning("MOTU cuemix value parser error: channel control index %d exceeded maximum %d\n",
467                             i, MOTUFW_MAX_MIXBUS_CHANNELS);
468                     }
469                     break;
470                 case MOTU_KEY_MIXBUS_GAIN:
471                     if (m_devctrls.mixbus_index < MOTUFW_MAX_MIXBUSES) {
472                         m_devctrls.mixbus[m_devctrls.mixbus_index].bus_gain = *arg;
473                     }
474                     break;
475                 case MOTU_KEY_MIXBUS_DEST:
476                     if (m_devctrls.mixbus_index < MOTUFW_MAX_MIXBUSES) {
477                         m_devctrls.mixbus[m_devctrls.mixbus_index].bus_dest = *arg;
478                     }
479                     break;
480                 case MOTU_KEY_MAINOUT_VOL:
481                     m_devctrls.main_out_volume = *arg;
482                     break;
483                 case MOTU_KEY_PHONES_VOL:
484                     m_devctrls.phones_volume = *arg;
485                     break;
486                 case MOTU_KEY_PHONES_DEST:
487                     m_devctrls.phones_assign = *arg;
488                     break;
489                 case MOTU_KEY_INPUT_6dB_BOOST:
490                     m_devctrls.input_6dB_boost = *arg;
491                     break;
492                 case MOTU_KEY_INPUT_REF_LEVEL:
493                     m_devctrls.input_ref_level = *arg;
494                     break;
495                 case MOTU_KEY_MIDI:
496                     // MIDI is dealt with elsewhere, so just pass it over
497                     break;
498                 default:
499                     // Ignore any unknown keys or those we don't care about, at
500                     // least for now.
501                     break;
502             }
503         }
504         j++;
505         src += m_event_size;
506         arg += m_event_size;
507     }
508
509     return 0;   
510 }
511
512 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.