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

Revision 1194, 20.9 kB (checked in by jwoithe, 14 years ago)

* MOTU: remove test tone for 2.0 branch.
* MOTU: in 2.0 branch, remove commented-out code related to ongoing debugging.

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