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

Revision 981, 25.7 kB (checked in by jwoithe, 16 years ago)

config.h.in: reworked MOTU_* constants to get "nearly correct" timestamps in outgoing packets. This makes playback at 2x and 4x samplerates work. More fine-tuning may be needed.

motu_avdevice.cpp: account for different port locations in packet data at 4x rates.

motu_avdevice.cpp: MotuDevice::probe(), MotuDevice::createDevice(): remove commented out references to the ConfigRom? ModelID field; with MOTUs this is useless for differentiating models.

motu_avdevice.cpp: MotuDevice::setOpticalMode(): the 896HD doesn't have an SPDIF/TOSLINK optical mode, so don't try to set it.

RME: implemented first cut at sample rate control. This has about a 50% chance of working as it currently stands.

MOTU: minor whitespace fixes for consistency.

MOTU: start implementation of device status tracking.

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
27 #include "libutil/float_cast.h"
28
29 #include "MotuTransmitStreamProcessor.h"
30 #include "MotuPort.h"
31 #include "../StreamProcessorManager.h"
32 #include "devicemanager.h"
33
34 #include "libieee1394/ieee1394service.h"
35 #include "libieee1394/IsoHandlerManager.h"
36 #include "libieee1394/cycletimer.h"
37
38 #include <netinet/in.h>
39 #include <assert.h>
40
41 // Set to 1 to enable the generation of a 1 kHz test tone in analog output 1.  Even with
42 // this defined to 1 the test tone will now only be produced if run with a non-zero
43 // debug level.
44 #define TESTTONE 1
45
46 #if TESTTONE
47 #include <math.h>
48 #endif
49
50 /* Provide more intuitive access to GCC's branch predition built-ins */
51 #define likely(x)   __builtin_expect((x),1)
52 #define unlikely(x) __builtin_expect((x),0)
53
54 namespace Streaming
55 {
56
57 // A macro to extract specific bits from a native endian quadlet
58 #define get_bits(_d,_start,_len) (((_d)>>((_start)-(_len)+1)) & ((1<<(_len))-1))
59
60 // Convert a full timestamp into an SPH timestamp as required by the MOTU
61 static inline uint32_t fullTicksToSph(int64_t timestamp) {
62     return TICKS_TO_CYCLE_TIMER(timestamp) & 0x1ffffff;
63 }
64
65 /* transmit */
66 MotuTransmitStreamProcessor::MotuTransmitStreamProcessor(FFADODevice &parent, unsigned int event_size )
67         : StreamProcessor(parent, ePT_Transmit )
68         , m_event_size( event_size )
69         , m_tx_dbc( 0 )
70 {}
71
72 unsigned int
73 MotuTransmitStreamProcessor::getMaxPacketSize() {
74     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
75     return framerate<=48000?616:(framerate<=96000?1032:1160);
76 }
77
78 unsigned int
79 MotuTransmitStreamProcessor::getNominalFramesPerPacket() {
80     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
81     return framerate<=48000?8:(framerate<=96000?16:32);
82 }
83
84 enum StreamProcessor::eChildReturnValue
85 MotuTransmitStreamProcessor::generatePacketHeader (
86     unsigned char *data, unsigned int *length,
87     unsigned char *tag, unsigned char *sy,
88     int cycle, unsigned int dropped, unsigned int max_length )
89 {
90     // The number of events per packet expected by the MOTU is solely
91     // dependent on the current sample rate.  An 'event' is one sample from
92     // all channels plus possibly other midi and control data.
93     signed n_events = getNominalFramesPerPacket();
94
95     // Do housekeeping expected for all packets sent to the MOTU, even
96     // for packets containing no audio data.
97     *sy = 0x00;
98     *tag = 1;      // All MOTU packets have a CIP-like header
99     *length = n_events*m_event_size + 8;
100
101     signed int fc;
102     uint64_t presentation_time;
103     unsigned int presentation_cycle;
104     int cycles_until_presentation;
105
106     uint64_t transmit_at_time;
107     unsigned int transmit_at_cycle;
108     int cycles_until_transmit;
109
110     debugOutput ( DEBUG_LEVEL_ULTRA_VERBOSE, "Try for cycle %d\n", cycle );
111     // check whether the packet buffer has packets for us to send.
112     // the base timestamp is the one of the next sample in the buffer
113     ffado_timestamp_t ts_head_tmp;
114     m_data_buffer->getBufferHeadTimestamp ( &ts_head_tmp, &fc ); // thread safe
115
116     // the timestamp gives us the time at which we want the sample block
117     // to be output by the device
118     presentation_time = ( uint64_t ) ts_head_tmp;
119     m_last_timestamp = presentation_time;
120
121     // now we calculate the time when we have to transmit the sample block
122     transmit_at_time = substractTicks ( presentation_time, MOTU_TRANSMIT_TRANSFER_DELAY );
123
124     // calculate the cycle this block should be presented in
125     // (this is just a virtual calculation since at that time it should
126     //  already be in the device's buffer)
127     presentation_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( presentation_time ) );
128
129     // calculate the cycle this block should be transmitted in
130     transmit_at_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( transmit_at_time ) );
131
132     // we can check whether this cycle is within the 'window' we have
133     // to send this packet.
134     // first calculate the number of cycles left before presentation time
135     cycles_until_presentation = diffCycles ( presentation_cycle, cycle );
136
137     // we can check whether this cycle is within the 'window' we have
138     // to send this packet.
139     // first calculate the number of cycles left before presentation time
140     cycles_until_transmit = diffCycles ( transmit_at_cycle, cycle );
141
142     if (dropped) {
143         debugOutput ( DEBUG_LEVEL_VERBOSE,
144                     "Gen HDR: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
145                     cycle,
146                     transmit_at_cycle, cycles_until_transmit,
147                     transmit_at_time, ( unsigned int ) TICKS_TO_CYCLES ( transmit_at_time ),
148                     presentation_time, ( unsigned int ) TICKS_TO_CYCLES ( presentation_time ) );
149     }
150     // two different options:
151     // 1) there are not enough frames for one packet
152     //      => determine wether this is a problem, since we might still
153     //         have some time to send it
154     // 2) there are enough packets
155     //      => determine whether we have to send them in this packet
156     if ( fc < ( signed int ) getNominalFramesPerPacket() )
157     {
158         // not enough frames in the buffer,
159
160         // we can still postpone the queueing of the packets
161         // if we are far enough ahead of the presentation time
162         if ( cycles_until_presentation <= MOTU_MIN_CYCLES_BEFORE_PRESENTATION )
163         {
164             debugOutput ( DEBUG_LEVEL_VERBOSE,
165                         "Insufficient frames (P): N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
166                         fc, cycle, transmit_at_cycle, cycles_until_transmit );
167             // we are too late
168             return eCRV_XRun;
169         }
170         else
171         {
172             debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
173                         "Insufficient frames (NP): N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
174                         fc, cycle, transmit_at_cycle, cycles_until_transmit );
175             // there is still time left to send the packet
176             // we want the system to give this packet another go at a later time instant
177             return eCRV_Again;
178         }
179     }
180     else
181     {
182         // there are enough frames, so check the time they are intended for
183         // all frames have a certain 'time window' in which they can be sent
184         // this corresponds to the range of the timestamp mechanism:
185         // we can send a packet 15 cycles in advance of the 'presentation time'
186         // in theory we can send the packet up till one cycle before the presentation time,
187         // however this is not very smart.
188
189         // There are 3 options:
190         // 1) the frame block is too early
191         //      => send an empty packet
192         // 2) the frame block is within the window
193         //      => send it
194         // 3) the frame block is too late
195         //      => discard (and raise xrun?)
196         //         get next block of frames and repeat
197
198         if(cycles_until_transmit < 0)
199         {
200             // we are too late
201             debugOutput(DEBUG_LEVEL_VERBOSE,
202                         "Too late: CY=%04u, TC=%04u, CUT=%04d, TSP=%011llu (%04u)\n",
203                         cycle,
204                         transmit_at_cycle, cycles_until_transmit,
205                         presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time) );
206
207             // however, if we can send this sufficiently before the presentation
208             // time, it could be harmless.
209             // NOTE: dangerous since the device has no way of reporting that it didn't get
210             //       this packet on time.
211             if(cycles_until_presentation >= MOTU_MIN_CYCLES_BEFORE_PRESENTATION)
212             {
213                 // we are not that late and can still try to transmit the packet
214                 m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, m_last_timestamp);
215                 if (m_tx_dbc > 0xff)
216                     m_tx_dbc -= 0x100;
217                 return eCRV_Packet;
218             }
219             else   // definitely too late
220             {
221                 return eCRV_XRun;
222             }
223         }
224         else if(cycles_until_transmit <= MOTU_MAX_CYCLES_TO_TRANSMIT_EARLY)
225         {
226             // it's time send the packet
227             m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, m_last_timestamp);
228             if (m_tx_dbc > 0xff)
229                 m_tx_dbc -= 0x100;
230             return eCRV_Packet;
231         }
232         else
233         {
234             debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
235                         "Too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
236                         cycle,
237                         transmit_at_cycle, cycles_until_transmit,
238                         transmit_at_time, ( unsigned int ) TICKS_TO_CYCLES ( transmit_at_time ),
239                         presentation_time, ( unsigned int ) TICKS_TO_CYCLES ( presentation_time ) );
240 #ifdef DEBUG
241             if ( cycles_until_transmit > MOTU_MAX_CYCLES_TO_TRANSMIT_EARLY + 1 )
242             {
243                 debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
244                             "Way too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
245                             cycle,
246                             transmit_at_cycle, cycles_until_transmit,
247                             transmit_at_time, ( unsigned int ) TICKS_TO_CYCLES ( transmit_at_time ),
248                             presentation_time, ( unsigned int ) TICKS_TO_CYCLES ( presentation_time ) );
249             }
250 #endif
251             // we are too early, send only an empty packet
252             return eCRV_EmptyPacket;
253         }
254     }
255     return eCRV_Invalid;
256 }
257
258 enum StreamProcessor::eChildReturnValue
259 MotuTransmitStreamProcessor::generatePacketData (
260     unsigned char *data, unsigned int *length,
261     unsigned char *tag, unsigned char *sy,
262     int cycle, unsigned int dropped, unsigned int max_length )
263 {
264     quadlet_t *quadlet = (quadlet_t *)data;
265     quadlet += 2; // skip the header
266     // Size of a single data frame in quadlets
267     unsigned dbs = m_event_size / 4;
268
269     // The number of events per packet expected by the MOTU is solely
270     // dependent on the current sample rate.  An 'event' is one sample from
271     // all channels plus possibly other midi and control data.
272     signed n_events = getNominalFramesPerPacket();
273
274     if (m_data_buffer->readFrames(n_events, (char *)(data + 8))) {
275         float ticks_per_frame = m_Parent.getDeviceManager().getStreamProcessorManager().getSyncSource().getActualRate();
276
277 #if TESTTONE
278     /* Now things are beginning to stabilise, make things easier for others by only playing
279      * the test tone when run with a non-zero debug level.
280      */
281     if (getDebugLevel() > 0) {
282         // FIXME: remove this hacked in 1 kHz test signal to
283         // analog-1 when testing is complete.
284         signed int i, int_tpf = lrintf(ticks_per_frame);
285         unsigned char *sample = data+8+16;
286         for (i=0; i<n_events; i++, sample+=m_event_size) {
287             static signed int a_cx = 0;
288             // Each sample is 3 bytes with MSB in lowest address (ie:
289             // network byte order).  After byte order swap, the 24-bit
290             // MSB is in the second byte of val.
291             signed int val = htonl(lrintf(0x7fffff*sin((1000.0*2.0*M_PI/24576000.0)*a_cx)));
292             memcpy(sample,((char *)&val)+1,3);
293             if ((a_cx+=int_tpf) >= 24576000) {
294                 a_cx -= 24576000;
295             }
296         }
297     }
298 #endif
299
300 //fprintf(stderr,"tx: %d/%d\n",
301 //  TICKS_TO_CYCLES(fullTicksToSph(m_last_timestamp)),
302 //  TICKS_TO_OFFSET(fullTicksToSph(m_last_timestamp)));
303         // Set up each frames's SPH.
304 //fprintf(stderr,"tpf=%f\n", ticks_per_frame);
305         for (int i=0; i < n_events; i++, quadlet += dbs) {
306             int64_t ts_frame = addTicks(m_last_timestamp, (unsigned int)lrintf(i * ticks_per_frame));
307             *quadlet = htonl(fullTicksToSph(ts_frame));
308 //fprintf(stderr,"tx: %d/%d\n",
309 //  CYCLE_TIMER_GET_CYCLES(fullTicksToSph(ts_frame)),
310 //  CYCLE_TIMER_GET_OFFSET(fullTicksToSph(ts_frame)));
311         }
312
313         return eCRV_OK;
314     }
315     else return eCRV_XRun;
316
317 }
318
319 enum StreamProcessor::eChildReturnValue
320 MotuTransmitStreamProcessor::generateEmptyPacketHeader (
321     unsigned char *data, unsigned int *length,
322     unsigned char *tag, unsigned char *sy,
323     int cycle, unsigned int dropped, unsigned int max_length )
324 {
325     debugOutput ( DEBUG_LEVEL_VERY_VERBOSE, "XMIT EMPTY: CY=%04u, TSP=%011llu (%04u)\n",
326                 cycle, m_last_timestamp, ( unsigned int ) TICKS_TO_CYCLES ( m_last_timestamp ) );
327
328     // Do housekeeping expected for all packets sent to the MOTU, even
329     // for packets containing no audio data.
330     *sy = 0x00;
331     *tag = 1;      // All MOTU packets have a CIP-like header
332     *length = 8;
333
334     m_tx_dbc += fillNoDataPacketHeader ( (quadlet_t *)data, length );
335     return eCRV_OK;
336 }
337
338 enum StreamProcessor::eChildReturnValue
339 MotuTransmitStreamProcessor::generateEmptyPacketData (
340     unsigned char *data, unsigned int *length,
341     unsigned char *tag, unsigned char *sy,
342     int cycle, unsigned int dropped, unsigned int max_length )
343 {
344     return eCRV_OK; // no need to do anything
345 }
346
347 enum StreamProcessor::eChildReturnValue
348 MotuTransmitStreamProcessor::generateSilentPacketHeader (
349     unsigned char *data, unsigned int *length,
350     unsigned char *tag, unsigned char *sy,
351     int cycle, unsigned int dropped, unsigned int max_length )
352 {
353     debugOutput ( DEBUG_LEVEL_VERY_VERBOSE, "XMIT SILENT: CY=%04u, TSP=%011llu (%04u)\n",
354                 cycle, m_last_timestamp, ( unsigned int ) TICKS_TO_CYCLES ( m_last_timestamp ) );
355
356     // A "silent" packet is identical to a regular data packet except
357     // all audio data is set to zero.
358
359     // The number of events per packet expected by the MOTU is solely
360     // dependent on the current sample rate.  An 'event' is one sample from
361     // all channels plus possibly other midi and control data.
362     signed n_events = getNominalFramesPerPacket();
363
364     // Do housekeeping expected for all packets sent to the MOTU, even
365     // for packets containing no audio data.
366     *sy = 0x00;
367     *tag = 1;      // All MOTU packets have a CIP-like header
368
369     /* Assume the packet will have audio data.  This is not strictly valid
370      * but seems to work most of the time.  The MOTU data packets have
371      * either 8, 16 or 32 samples in them.  This is more than would normally
372      * be required in each cycle period and so every so often an empty
373      * packet must be sent to allow things to "catch up".
374      */
375     *length = n_events*m_event_size + 8;
376
377     return eCRV_Packet;
378     //generatePacketHeader(data, length, tag, sy, cycle, dropped, max_length);
379 }
380
381 enum StreamProcessor::eChildReturnValue
382 MotuTransmitStreamProcessor::generateSilentPacketData (
383     unsigned char *data, unsigned int *length,
384     unsigned char *tag, unsigned char *sy,
385     int cycle, unsigned int dropped, unsigned int max_length )
386 {
387     // Simply set all audio data to zero since that's what's meant by
388     // a "silent" packet.  Note that m_event_size is in bytes for MOTU.
389
390     quadlet_t *quadlet = (quadlet_t *)data;
391     quadlet += 2; // skip the header
392     // Size of a single data frame in quadlets
393     unsigned dbs = m_event_size / 4;
394
395     // The number of events per packet expected by the MOTU is solely
396     // dependent on the current sample rate.  An 'event' is one sample from
397     // all channels plus possibly other midi and control data.
398     signed n_events = getNominalFramesPerPacket();
399
400     memset(quadlet, 0, n_events*m_event_size);
401     float ticks_per_frame = m_Parent.getDeviceManager().getStreamProcessorManager().getSyncSource().getActualRate();
402
403     // Set up each frames's SPH.
404     for (int i=0; i < n_events; i++, quadlet += dbs) {
405         int64_t ts_frame = addTicks(m_last_timestamp, (unsigned int)lrintf(i * ticks_per_frame));
406         *quadlet = htonl(fullTicksToSph(ts_frame));
407     }
408
409     return eCRV_OK;
410 }
411
412 unsigned int MotuTransmitStreamProcessor::fillDataPacketHeader (
413     quadlet_t *data, unsigned int* length,
414     uint32_t ts )
415 {
416     quadlet_t *quadlet = (quadlet_t *)data;
417     // Size of a single data frame in quadlets
418     unsigned dbs = m_event_size / 4;
419
420     // The number of events per packet expected by the MOTU is solely
421     // dependent on the current sample rate.  An 'event' is one sample from
422     // all channels plus possibly other midi and control data.
423     signed n_events = getNominalFramesPerPacket();
424
425     // construct the packet CIP-like header.  Even if this is a data-less
426     // packet the dbs field is still set as if there were data blocks
427     // present.  For data-less packets the dbc is the same as the previously
428     // transmitted block.
429     *quadlet = htonl(0x00000400 | ((m_Parent.get1394Service().getLocalNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
430     quadlet++;
431     *quadlet = htonl(0x8222ffff);
432     quadlet++;
433     return n_events;
434 }
435
436 unsigned int MotuTransmitStreamProcessor::fillNoDataPacketHeader (
437     quadlet_t *data, unsigned int* length )
438 {
439     quadlet_t *quadlet = (quadlet_t *)data;
440     // Size of a single data frame in quadlets
441     unsigned dbs = m_event_size / 4;
442     // construct the packet CIP-like header.  Even if this is a data-less
443     // packet the dbs field is still set as if there were data blocks
444     // present.  For data-less packets the dbc is the same as the previously
445     // transmitted block.
446     *quadlet = htonl(0x00000400 | ((m_Parent.get1394Service().getLocalNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
447     quadlet++;
448     *quadlet = htonl(0x8222ffff);
449     quadlet++;
450     *length = 8;
451     return 0;
452 }
453
454 bool MotuTransmitStreamProcessor::prepareChild()
455 {
456     debugOutput ( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this );
457     return true;
458 }
459
460 /*
461 * compose the event streams for the packets from the port buffers
462 */
463 bool MotuTransmitStreamProcessor::processWriteBlock(char *data,
464                        unsigned int nevents, unsigned int offset) {
465     bool no_problem=true;
466     unsigned int i;
467
468     // FIXME: ensure the MIDI and control streams are all zeroed until
469     // such time as they are fully implemented.
470     for (i=0; i<nevents; i++) {
471         memset(data+4+i*m_event_size, 0x00, 6);
472     }
473
474     for ( PortVectorIterator it = m_Ports.begin();
475       it != m_Ports.end();
476       ++it ) {
477         // If this port is disabled, don't process it
478         if((*it)->isDisabled()) {continue;};
479
480         Port *port=(*it);
481
482         switch(port->getPortType()) {
483
484         case Port::E_Audio:
485             if (encodePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
486                 debugWarning("Could not encode port %s to Motu events",(*it)->getName().c_str());
487                 no_problem=false;
488             }
489             break;
490         case Port::E_Midi:
491              if (encodePortToMotuMidiEvents(static_cast<MotuMidiPort *>(*it), (quadlet_t *)data, offset, nevents)) {
492                  debugWarning("Could not encode port %s to Midi events",(*it)->getName().c_str());
493                  no_problem=false;
494              }
495             break;
496         default: // ignore
497             break;
498         }
499     }
500     return no_problem;
501 }
502
503 bool
504 MotuTransmitStreamProcessor::transmitSilenceBlock(char *data,
505                        unsigned int nevents, unsigned int offset) {
506     // This is the same as the non-silence version, except that is
507     // doesn't read from the port buffers.
508     bool no_problem = true;
509     for ( PortVectorIterator it = m_Ports.begin();
510       it != m_Ports.end();
511       ++it ) {
512         Port *port=(*it);
513
514         switch(port->getPortType()) {
515
516         case Port::E_Audio:
517             if (encodeSilencePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
518                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
519                 no_problem = false;
520             }
521             break;
522         case Port::E_Midi:
523             if (encodeSilencePortToMotuMidiEvents(static_cast<MotuMidiPort *>(*it), (quadlet_t *)data, offset, nevents)) {
524                 debugWarning("Could not encode port %s to Midi events",(*it)->getName().c_str());
525                 no_problem = false;
526             }
527             break;
528         default: // ignore
529             break;
530         }
531     }
532     return no_problem;
533 }
534
535 int MotuTransmitStreamProcessor::encodePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
536                        unsigned int offset, unsigned int nevents) {
537 // Encodes nevents worth of data from the given port into the given buffer.  The
538 // format of the buffer is precisely that which will be sent to the MOTU.
539 // The basic idea:
540 //   iterate over the ports
541 //     * get port buffer address
542 //     * loop over events
543 //         - pick right sample in event based upon PortInfo
544 //         - convert sample from Port format (E_Int24, E_Float, ..) to MOTU
545 //           native format
546 //
547 // We include the ability to start the transfer from the given offset within
548 // the port (expressed in frames) so the 'efficient' transfer method can be
549 // utilised.
550
551     unsigned int j=0;
552
553     // Use char here since the target address won't necessarily be
554     // aligned; use of an unaligned quadlet_t may cause issues on certain
555     // architectures.  Besides, the target (data going directly to the MOTU)
556     // isn't structured in quadlets anyway; it mainly consists of packed
557     // 24-bit integers.
558     unsigned char *target;
559     target = (unsigned char *)data + p->getPosition();
560
561     switch(m_StreamProcessorManager.getAudioDataType()) {
562         default:
563         case StreamProcessorManager::eADT_Int24:
564             {
565                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
566
567                 assert(nevents + offset <= p->getBufferSize());
568
569                 // Offset is in frames, but each port is only a single
570                 // channel, so the number of frames is the same as the
571                 // number of quadlets to offset (assuming the port buffer
572                 // uses one quadlet per sample, which is the case currently).
573                 buffer+=offset;
574
575                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
576                     *target = (*buffer >> 16) & 0xff;
577                     *(target+1) = (*buffer >> 8) & 0xff;
578                     *(target+2) = (*buffer) & 0xff;
579
580                     buffer++;
581                     target+=m_event_size;
582                 }
583             }
584             break;
585         case StreamProcessorManager::eADT_Float:
586             {
587                 const float multiplier = (float)(0x7FFFFF);
588                 float *buffer=(float *)(p->getBufferAddress());
589
590                 assert(nevents + offset <= p->getBufferSize());
591
592                 buffer+=offset;
593
594                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
595                     float in = *buffer;
596 #if MOTU_CLIP_FLOATS
597                     if (unlikely(in > 1.0)) in = 1.0;
598                     if (unlikely(in < -1.0)) in = -1.0;
599 #endif
600                     unsigned int v = lrintf(in * multiplier);
601                     *target = (v >> 16) & 0xff;
602                     *(target+1) = (v >> 8) & 0xff;
603                     *(target+2) = v & 0xff;
604
605                     buffer++;
606                     target+=m_event_size;
607                 }
608             }
609             break;
610     }
611
612     return 0;
613 }
614
615 int MotuTransmitStreamProcessor::encodeSilencePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
616                        unsigned int offset, unsigned int nevents) {
617     unsigned int j=0;
618     unsigned char *target = (unsigned char *)data + p->getPosition();
619
620     switch (m_StreamProcessorManager.getAudioDataType()) {
621     default:
622         case StreamProcessorManager::eADT_Int24:
623         case StreamProcessorManager::eADT_Float:
624         for (j = 0; j < nevents; j++) {
625             *target = *(target+1) = *(target+2) = 0;
626             target += m_event_size;
627         }
628         break;
629     }
630
631     return 0;
632 }
633
634 int MotuTransmitStreamProcessor::encodePortToMotuMidiEvents(
635                        MotuMidiPort *p, quadlet_t *data,
636                        unsigned int offset, unsigned int nevents) {
637
638     unsigned int j;
639     quadlet_t *src = (quadlet_t *)p->getBufferAddress();
640     src += offset;
641
642     unsigned char *target = (unsigned char *)data + p->getPosition();
643
644     // Send a MIDI byte if there is one to send.  MOTU MIDI data is sent using
645     // a 3-byte sequence within a frame starting at the port's position.  For
646     // now we assume that a zero within the port's buffer means there is no
647     // MIDI data for the corresponding frame, but this may need refining.
648
649     for (j=0; j<nevents; j++, src++, target+=m_event_size) {
650         if (*src != 0) {
651             *(target) = 0x01;
652             *(target+1) = 0x00;
653             *(target+2) = (*src & 0xff);
654         } else
655           memset(target, 0, 3);
656     }
657
658     return 0;
659 }
660
661 int MotuTransmitStreamProcessor::encodeSilencePortToMotuMidiEvents(
662                        MotuMidiPort *p, quadlet_t *data,
663                        unsigned int offset, unsigned int nevents) {
664
665     unsigned int j;
666     unsigned char *target = (unsigned char *)data + p->getPosition();
667
668     // For now, a "silent" MIDI event contains nothing but zeroes.  This
669     // may have to change if we find this isn't for some reason appropriate.
670     for (j=0; j<nevents; j++, target+=m_event_size) {
671        memset(target, 0, 3);
672     }
673
674     return 0;
675 }
676
677 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.