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

Revision 1348, 21.5 kB (checked in by ppalmers, 16 years ago)

merge 2.0 branch changes to trunk. svn merge -r 1337:HEAD svn+ssh://ffadosvn@ffado.org/ffado/branches/libffado-2.0

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