root/trunk/libffado/src/libstreaming/motu/MotuReceiveStreamProcessor.cpp

Revision 1254, 21.1 kB (checked in by ppalmers, 16 years ago)

split config.h into config/version/debug_config to allow for faster compilation (splits dependencies)

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