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

Revision 1763, 29.7 kB (checked in by ppalmers, 12 years ago)

Merged revisions 1536,1541,1544-1546,1549,1554-1562,1571,1579-1581,1618,1632,1634-1635,1661,1677-1679,1703-1704,1715,1720-1723,1743-1745,1755 via svnmerge from
svn+ssh://ffadosvn@ffado.org/ffado/branches/libffado-2.0

Also fix remaining format string warnings.

Line 
1 /*
2  * Copyright (C) 2005-2008 by Jonathan Woithe
3  * Copyright (C) 2005-2008 by Pieter Palmers
4  *
5  * This file is part of FFADO
6  * FFADO = Free Firewire (pro-)audio drivers for linux
7  *
8  * FFADO is based upon FreeBoB.
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 2 of the License, or
13  * (at your option) version 3 of the License.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include "config.h"
26
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 "libutil/ByteSwap.h"
39
40 #include <cstring>
41 #include <assert.h>
42
43 // Set to 1 to enable the generation of a 1 kHz test tone in analog output 1.  Even with
44 // this defined to 1 the test tone will now only be produced if run with a non-zero
45 // debug level.
46 #define TESTTONE 1
47
48 #if TESTTONE
49 #include <math.h>
50 #endif
51
52 /* Provide more intuitive access to GCC's branch predition built-ins */
53 #define likely(x)   __builtin_expect((x),1)
54 #define unlikely(x) __builtin_expect((x),0)
55
56 namespace Streaming
57 {
58
59 // A macro to extract specific bits from a native endian quadlet
60 #define get_bits(_d,_start,_len) (((_d)>>((_start)-(_len)+1)) & ((1<<(_len))-1))
61
62 // Convert a full timestamp into an SPH timestamp as required by the MOTU
63 static inline uint32_t fullTicksToSph(int64_t timestamp) {
64     return TICKS_TO_CYCLE_TIMER(timestamp) & 0x1ffffff;
65 }
66
67 /* transmit */
68 MotuTransmitStreamProcessor::MotuTransmitStreamProcessor(FFADODevice &parent, unsigned int event_size )
69         : StreamProcessor(parent, ePT_Transmit )
70         , m_event_size( event_size )
71         , m_tx_dbc( 0 )
72         , mb_head( 0 )
73         , mb_tail( 0 )
74         , midi_lock( 0 )
75 {
76   int srate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
77   /* Work out how many audio samples should be left between MIDI data bytes in order
78    * to stay under the MIDI hardware baud rate of 31250.  MIDI data is transmitted
79    * using 10 bits per byte (including the start/stop bit) so this gives us 3125 bytes
80    * per second.  If we send to the MOTU at a faster rate than this, some MIDI bytes
81    * will be dropped or corrupted in interesting ways.
82    */
83   midi_tx_period = lrintf(ceil((float)srate / 3125));
84 }
85
86 unsigned int
87 MotuTransmitStreamProcessor::getMaxPacketSize() {
88     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
89     return framerate<=48000?616:(framerate<=96000?1032:1160);
90 }
91
92 unsigned int
93 MotuTransmitStreamProcessor::getNominalFramesPerPacket() {
94     int framerate = m_Parent.getDeviceManager().getStreamProcessorManager().getNominalRate();
95     return framerate<=48000?8:(framerate<=96000?16:32);
96 }
97
98 enum StreamProcessor::eChildReturnValue
99 MotuTransmitStreamProcessor::generatePacketHeader (
100     unsigned char *data, unsigned int *length,
101     unsigned char *tag, unsigned char *sy,
102     uint32_t pkt_ctr )
103 {
104     unsigned int cycle = CYCLE_TIMER_GET_CYCLES(pkt_ctr);
105
106     // The number of events per packet expected by the MOTU is solely
107     // dependent on the current sample rate.  An 'event' is one sample from
108     // all channels plus possibly other midi and control data.
109     signed n_events = getNominalFramesPerPacket();
110
111     // Do housekeeping expected for all packets sent to the MOTU, even
112     // for packets containing no audio data.
113     *sy = 0x00;
114     *tag = 1;      // All MOTU packets have a CIP-like header
115     *length = n_events*m_event_size + 8;
116
117     signed int fc;
118     uint64_t presentation_time;
119     unsigned int presentation_cycle;
120     int cycles_until_presentation;
121
122     uint64_t transmit_at_time;
123     unsigned int transmit_at_cycle;
124     int cycles_until_transmit;
125
126     debugOutput ( DEBUG_LEVEL_ULTRA_VERBOSE, "Try for cycle %d\n", cycle );
127     // check whether the packet buffer has packets for us to send.
128     // the base timestamp is the one of the next sample in the buffer
129     ffado_timestamp_t ts_head_tmp;
130     m_data_buffer->getBufferHeadTimestamp ( &ts_head_tmp, &fc ); // thread safe
131
132     // the timestamp gives us the time at which we want the sample block
133     // to be output by the device
134     presentation_time = ( uint64_t ) ts_head_tmp;
135
136     // now we calculate the time when we have to transmit the sample block
137     transmit_at_time = substractTicks ( presentation_time, MOTU_TRANSMIT_TRANSFER_DELAY );
138
139     // calculate the cycle this block should be presented in
140     // (this is just a virtual calculation since at that time it should
141     //  already be in the device's buffer)
142     presentation_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( presentation_time ) );
143
144     // calculate the cycle this block should be transmitted in
145     transmit_at_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( transmit_at_time ) );
146
147     // we can check whether this cycle is within the 'window' we have
148     // to send this packet.
149     // first calculate the number of cycles left before presentation time
150     cycles_until_presentation = diffCycles ( presentation_cycle, cycle );
151
152     // we can check whether this cycle is within the 'window' we have
153     // to send this packet.
154     // first calculate the number of cycles left before presentation time
155     cycles_until_transmit = diffCycles ( transmit_at_cycle, cycle );
156
157     // two different options:
158     // 1) there are not enough frames for one packet
159     //      => determine wether this is a problem, since we might still
160     //         have some time to send it
161     // 2) there are enough packets
162     //      => determine whether we have to send them in this packet
163     if ( fc < ( signed int ) getNominalFramesPerPacket() )
164     {
165         // not enough frames in the buffer,
166
167         // we can still postpone the queueing of the packets
168         // if we are far enough ahead of the presentation time
169         if ( cycles_until_presentation <= MOTU_MIN_CYCLES_BEFORE_PRESENTATION )
170         {
171             debugOutput ( DEBUG_LEVEL_VERBOSE,
172                         "Insufficient frames (P): N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
173                         fc, cycle, transmit_at_cycle, cycles_until_transmit );
174             // we are too late
175             return eCRV_XRun;
176         }
177         else
178         {
179             debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
180                         "Insufficient frames (NP): N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
181                         fc, cycle, transmit_at_cycle, cycles_until_transmit );
182             // there is still time left to send the packet
183             // we want the system to give this packet another go at a later time instant
184             return eCRV_Again;
185         }
186     }
187     else
188     {
189         // there are enough frames, so check the time they are intended for
190         // all frames have a certain 'time window' in which they can be sent
191         // this corresponds to the range of the timestamp mechanism:
192         // we can send a packet 15 cycles in advance of the 'presentation time'
193         // in theory we can send the packet up till one cycle before the presentation time,
194         // however this is not very smart.
195
196         // There are 3 options:
197         // 1) the frame block is too early
198         //      => send an empty packet
199         // 2) the frame block is within the window
200         //      => send it
201         // 3) the frame block is too late
202         //      => discard (and raise xrun?)
203         //         get next block of frames and repeat
204
205         if(cycles_until_transmit < 0)
206         {
207             // we are too late
208             debugOutput(DEBUG_LEVEL_VERBOSE,
209                         "Too late: CY=%04u, TC=%04u, CUT=%04d, TSP=%011"PRIu64" (%04u)\n",
210                         cycle,
211                         transmit_at_cycle, cycles_until_transmit,
212                         presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time) );
213
214             // however, if we can send this sufficiently before the presentation
215             // time, it could be harmless.
216             // NOTE: dangerous since the device has no way of reporting that it didn't get
217             //       this packet on time.
218             if(cycles_until_presentation >= MOTU_MIN_CYCLES_BEFORE_PRESENTATION)
219             {
220                 // we are not that late and can still try to transmit the packet
221                 m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, presentation_time);
222                 m_last_timestamp = presentation_time;
223                 if (m_tx_dbc > 0xff)
224                     m_tx_dbc -= 0x100;
225                 return eCRV_Packet;
226             }
227             else   // definitely too late
228             {
229                 return eCRV_XRun;
230             }
231         }
232         else if(cycles_until_transmit <= MOTU_MAX_CYCLES_TO_TRANSMIT_EARLY)
233         {
234             // it's time send the packet
235             m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, presentation_time);
236             m_last_timestamp = presentation_time;
237             if (m_tx_dbc > 0xff)
238                 m_tx_dbc -= 0x100;
239             return eCRV_Packet;
240         }
241         else
242         {
243             debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
244                         "Too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011"PRIu64" (%04u), TSP=%011"PRIu64" (%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 #ifdef DEBUG
250             if ( cycles_until_transmit > MOTU_MAX_CYCLES_TO_TRANSMIT_EARLY + 1 )
251             {
252                 debugOutput ( DEBUG_LEVEL_VERY_VERBOSE,
253                             "Way too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011"PRIu64" (%04u), TSP=%011"PRIu64" (%04u)\n",
254                             cycle,
255                             transmit_at_cycle, cycles_until_transmit,
256                             transmit_at_time, ( unsigned int ) TICKS_TO_CYCLES ( transmit_at_time ),
257                             presentation_time, ( unsigned int ) TICKS_TO_CYCLES ( presentation_time ) );
258             }
259 #endif
260             // we are too early, send only an empty packet
261             return eCRV_EmptyPacket;
262         }
263     }
264     return eCRV_Invalid;
265 }
266
267 enum StreamProcessor::eChildReturnValue
268 MotuTransmitStreamProcessor::generatePacketData (
269     unsigned char *data, unsigned int *length)
270 {
271     quadlet_t *quadlet = (quadlet_t *)data;
272     quadlet += 2; // skip the header
273     // Size of a single data frame in quadlets
274     unsigned dbs = m_event_size / 4;
275
276     // The number of events per packet expected by the MOTU is solely
277     // dependent on the current sample rate.  An 'event' is one sample from
278     // all channels plus possibly other midi and control data.
279     signed n_events = getNominalFramesPerPacket();
280
281     if (m_data_buffer->readFrames(n_events, (char *)(data + 8))) {
282         float ticks_per_frame = m_Parent.getDeviceManager().getStreamProcessorManager().getSyncSource().getTicksPerFrame();
283
284 #if TESTTONE
285     /* Now things are beginning to stabilise, make things easier for others by only playing
286      * the test tone when run with a non-zero debug level.
287      */
288     if (getDebugLevel() > 0) {
289         // FIXME: remove this hacked in 1 kHz test signal to
290         // analog-1 when testing is complete.
291         signed int i, int_tpf = lrintf(ticks_per_frame);
292         unsigned char *sample = data+8+16;
293         for (i=0; i<n_events; i++, sample+=m_event_size) {
294             static signed int a_cx = 0;
295             // Each sample is 3 bytes with MSB in lowest address (ie:
296             // network byte order).  After byte order swap, the 24-bit
297             // MSB is in the second byte of val.
298             signed int val = CondSwapToBus32(lrintf(0x7fffff*sin((1000.0*2.0*M_PI/24576000.0)*a_cx)));
299             memcpy(sample,((char *)&val)+1,3);
300             if ((a_cx+=int_tpf) >= 24576000) {
301                 a_cx -= 24576000;
302             }
303         }
304     }
305 #endif
306
307 //fprintf(stderr,"tx: %d/%d\n",
308 //  TICKS_TO_CYCLES(fullTicksToSph(m_last_timestamp)),
309 //  TICKS_TO_OFFSET(fullTicksToSph(m_last_timestamp)));
310         // Set up each frames's SPH.
311 //fprintf(stderr,"tpf=%f\n", ticks_per_frame);
312         for (int i=0; i < n_events; i++, quadlet += dbs) {
313             int64_t ts_frame = addTicks(m_last_timestamp, (unsigned int)lrintf(i * ticks_per_frame));
314             *quadlet = CondSwapToBus32(fullTicksToSph(ts_frame));
315 //fprintf(stderr,"tx: %d/%d\n",
316 //  CYCLE_TIMER_GET_CYCLES(fullTicksToSph(ts_frame)),
317 //  CYCLE_TIMER_GET_OFFSET(fullTicksToSph(ts_frame)));
318         }
319
320         return eCRV_OK;
321     }
322     else return eCRV_XRun;
323
324 }
325
326 enum StreamProcessor::eChildReturnValue
327 MotuTransmitStreamProcessor::generateEmptyPacketHeader (
328     unsigned char *data, unsigned int *length,
329     unsigned char *tag, unsigned char *sy,
330     uint32_t pkt_ctr )
331 {
332     debugOutput ( DEBUG_LEVEL_VERY_VERBOSE, "XMIT EMPTY: CY=%04d, TSP=%011"PRIu64" (%04u)\n",
333                 (int)CYCLE_TIMER_GET_CYCLES(pkt_ctr), m_last_timestamp,
334                 ( unsigned int ) TICKS_TO_CYCLES ( m_last_timestamp ) );
335
336     // Do housekeeping expected for all packets sent to the MOTU, even
337     // for packets containing no audio data.
338     *sy = 0x00;
339     *tag = 1;      // All MOTU packets have a CIP-like header
340     *length = 8;
341
342     m_tx_dbc += fillNoDataPacketHeader ( (quadlet_t *)data, length );
343     return eCRV_OK;
344 }
345
346 enum StreamProcessor::eChildReturnValue
347 MotuTransmitStreamProcessor::generateEmptyPacketData (
348     unsigned char *data, unsigned int *length)
349 {
350     return eCRV_OK; // no need to do anything
351 }
352
353 enum StreamProcessor::eChildReturnValue
354 MotuTransmitStreamProcessor::generateSilentPacketHeader (
355     unsigned char *data, unsigned int *length,
356     unsigned char *tag, unsigned char *sy,
357     uint32_t pkt_ctr )
358 {
359     unsigned int cycle = CYCLE_TIMER_GET_CYCLES(pkt_ctr);
360
361     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "XMIT SILENT: CY=%04u, TSP=%011"PRIu64" (%04u)\n",
362                  cycle, m_last_timestamp,
363                  ( unsigned int ) TICKS_TO_CYCLES ( m_last_timestamp ) );
364
365     // A "silent" packet is identical to a regular data packet except all
366     // audio data is set to zero.  The MOTU expects valid timestamps and
367     // rate control in silent packets, so much of the timing logic from
368     // generatePacketHeader() is needed here too - the main difference being
369     // the source of the packet timestamp.
370
371     // The number of events per packet expected by the MOTU is solely
372     // dependent on the current sample rate.  An 'event' is one sample from
373     // all channels plus possibly other midi and control data.
374     signed n_events = getNominalFramesPerPacket();
375
376     // Do housekeeping expected for all packets sent to the MOTU, even
377     // for packets containing no audio data.
378     *sy = 0x00;
379     *tag = 1;      // All MOTU packets have a CIP-like header
380
381     /* Assume the packet will have audio data.  If it turns out we need an empty packet
382      * the length will be overridden by fillNoDataPacketHeader().
383      */
384     *length = n_events*m_event_size + 8;
385
386     uint64_t presentation_time;
387     unsigned int presentation_cycle;
388     int cycles_until_presentation;
389            
390     uint64_t transmit_at_time;
391     unsigned int transmit_at_cycle;
392     int cycles_until_transmit;
393
394     /* The sample buffer is not necessarily running when silent packets are
395      * needed, so use m_last_timestamp (the timestamp of the previously sent
396      * data packet) as the basis for the presentation time of the next
397      * packet.  Since we're only writing zeros we don't have to deal with
398      * buffer xruns.
399      */
400     float ticks_per_frame = m_Parent.getDeviceManager().getStreamProcessorManager().getSyncSource().getTicksPerFrame();
401     presentation_time = addTicks(m_last_timestamp, (unsigned int)lrintf(n_events * ticks_per_frame));
402
403     transmit_at_time = substractTicks(presentation_time, MOTU_TRANSMIT_TRANSFER_DELAY);
404     presentation_cycle = (unsigned int)(TICKS_TO_CYCLES(presentation_time));
405     transmit_at_cycle = (unsigned int)(TICKS_TO_CYCLES(transmit_at_time));
406     cycles_until_presentation = diffCycles(presentation_cycle, cycle);
407     cycles_until_transmit = diffCycles(transmit_at_cycle, cycle);
408
409     if (cycles_until_transmit < 0)
410     {
411         if (cycles_until_presentation >= MOTU_MIN_CYCLES_BEFORE_PRESENTATION)
412         {
413             m_last_timestamp = presentation_time;
414             m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, m_last_timestamp);
415             if (m_tx_dbc > 0xff)
416                 m_tx_dbc -= 0x100;
417             return eCRV_Packet;
418         }
419         else
420         {
421             return eCRV_XRun;
422         }
423     }
424     else if (cycles_until_transmit <= MOTU_MAX_CYCLES_TO_TRANSMIT_EARLY)
425     {
426         m_last_timestamp = presentation_time;
427         m_tx_dbc += fillDataPacketHeader((quadlet_t *)data, length, m_last_timestamp);
428         if (m_tx_dbc > 0xff)
429             m_tx_dbc -= 0x100;
430         return eCRV_Packet;
431     }
432     else
433     {
434         return eCRV_EmptyPacket;
435     }
436     return eCRV_Invalid;
437 }
438
439 enum StreamProcessor::eChildReturnValue
440 MotuTransmitStreamProcessor::generateSilentPacketData (
441     unsigned char *data, unsigned int *length )
442 {
443     // Simply set all audio data to zero since that's what's meant by
444     // a "silent" packet.  Note that m_event_size is in bytes for MOTU.
445
446     quadlet_t *quadlet = (quadlet_t *)data;
447     quadlet += 2; // skip the header
448     // Size of a single data frame in quadlets
449     unsigned dbs = m_event_size / 4;
450
451     // The number of events per packet expected by the MOTU is solely
452     // dependent on the current sample rate.  An 'event' is one sample from
453     // all channels plus possibly other midi and control data.
454     signed n_events = getNominalFramesPerPacket();
455
456     memset(quadlet, 0, n_events*m_event_size);
457     float ticks_per_frame = m_Parent.getDeviceManager().getStreamProcessorManager().getSyncSource().getTicksPerFrame();
458
459     // Set up each frames's SPH.
460     for (int i=0; i < n_events; i++, quadlet += dbs) {
461         int64_t ts_frame = addTicks(m_last_timestamp, (unsigned int)lrintf(i * ticks_per_frame));
462         *quadlet = CondSwapToBus32(fullTicksToSph(ts_frame));
463     }
464     return eCRV_OK;
465 }
466
467 unsigned int MotuTransmitStreamProcessor::fillDataPacketHeader (
468     quadlet_t *data, unsigned int* length,
469     uint32_t ts )
470 {
471     quadlet_t *quadlet = (quadlet_t *)data;
472     // Size of a single data frame in quadlets.  For data sent TO the
473     // Ultralite this is not strictly true (with m_event_size 52, dbs is set
474     // to 13, even though data sent by the Ultralite uses 19 as one would
475     // expect from a 52-byte event).  Even so, we'll run with the assumption
476     // that a different dbs will be fine unless proven otherwise.
477     unsigned dbs = m_event_size / 4;
478
479     // The number of events per packet expected by the MOTU is solely
480     // dependent on the current sample rate.  An 'event' is one sample from
481     // all channels plus possibly other midi and control data.
482     signed n_events = getNominalFramesPerPacket();
483
484     // construct the packet CIP-like header.  Even if this is a data-less
485     // packet the dbs field is still set as if there were data blocks
486     // present.  For data-less packets the dbc is the same as the previously
487     // transmitted block.
488     *quadlet = CondSwapToBus32(0x00000400 | ((m_Parent.get1394Service().getLocalNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
489     quadlet++;
490     *quadlet = CondSwapToBus32(0x8222ffff);
491     quadlet++;
492     return n_events;
493 }
494
495 unsigned int MotuTransmitStreamProcessor::fillNoDataPacketHeader (
496     quadlet_t *data, unsigned int* length )
497 {
498     quadlet_t *quadlet = (quadlet_t *)data;
499     // Size of a single data frame in quadlets.  See comment in
500     // fillDataPacketHeader() regarding the Ultralite.
501     unsigned dbs = m_event_size / 4;
502     // construct the packet CIP-like header.  Even if this is a data-less
503     // packet the dbs field is still set as if there were data blocks
504     // present.  For data-less packets the dbc is the same as the previously
505     // transmitted block.
506     *quadlet = CondSwapToBus32(0x00000400 | ((m_Parent.get1394Service().getLocalNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
507     quadlet++;
508     *quadlet = CondSwapToBus32(0x8222ffff);
509     quadlet++;
510     *length = 8;
511     return 0;
512 }
513
514 bool MotuTransmitStreamProcessor::prepareChild()
515 {
516     debugOutput ( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this );
517     return true;
518 }
519
520 /*
521 * compose the event streams for the packets from the port buffers
522 */
523 bool MotuTransmitStreamProcessor::processWriteBlock(char *data,
524                        unsigned int nevents, unsigned int offset) {
525     bool no_problem=true;
526     unsigned int i;
527
528     // Start with MIDI and control streams all zeroed.  Due to the sparce nature
529     // of these streams it is best to simply fill them in on an as-needs basis.
530     for (i=0; i<nevents; i++) {
531         memset(data+4+i*m_event_size, 0x00, 6);
532     }
533
534     for ( PortVectorIterator it = m_Ports.begin();
535       it != m_Ports.end();
536       ++it ) {
537         // If this port is disabled, unconditionally send it silence.
538         if((*it)->isDisabled()) {
539           if (encodeSilencePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
540             debugWarning("Could not encode silence for disabled port %s to Motu events\n",(*it)->getName().c_str());
541             // Don't treat this as a fatal error at this point
542           }
543           continue;
544         }
545
546         Port *port=(*it);
547
548         switch(port->getPortType()) {
549
550         case Port::E_Audio:
551             if (encodePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
552                 debugWarning("Could not encode port %s to Motu events\n",(*it)->getName().c_str());
553                 no_problem=false;
554             }
555             break;
556         case Port::E_Midi:
557              if (encodePortToMotuMidiEvents(static_cast<MotuMidiPort *>(*it), (quadlet_t *)data, offset, nevents)) {
558                  debugWarning("Could not encode port %s to Midi events\n",(*it)->getName().c_str());
559                  no_problem=false;
560              }
561             break;
562         default: // ignore
563             break;
564         }
565     }
566     return no_problem;
567 }
568
569 bool
570 MotuTransmitStreamProcessor::transmitSilenceBlock(char *data,
571                        unsigned int nevents, unsigned int offset) {
572     // This is the same as the non-silence version, except that is
573     // doesn't read from the port buffers.
574     bool no_problem = true;
575     for ( PortVectorIterator it = m_Ports.begin();
576       it != m_Ports.end();
577       ++it ) {
578         Port *port=(*it);
579
580         switch(port->getPortType()) {
581
582         case Port::E_Audio:
583             if (encodeSilencePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
584                 debugWarning("Could not encode port %s to MBLA events\n",(*it)->getName().c_str());
585                 no_problem = false;
586             }
587             break;
588         case Port::E_Midi:
589             if (encodeSilencePortToMotuMidiEvents(static_cast<MotuMidiPort *>(*it), (quadlet_t *)data, offset, nevents)) {
590                 debugWarning("Could not encode port %s to Midi events\n",(*it)->getName().c_str());
591                 no_problem = false;
592             }
593             break;
594         default: // ignore
595             break;
596         }
597     }
598     return no_problem;
599 }
600
601 int MotuTransmitStreamProcessor::encodePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
602                        unsigned int offset, unsigned int nevents) {
603 // Encodes nevents worth of data from the given port into the given buffer.  The
604 // format of the buffer is precisely that which will be sent to the MOTU.
605 // The basic idea:
606 //   iterate over the ports
607 //     * get port buffer address
608 //     * loop over events
609 //         - pick right sample in event based upon PortInfo
610 //         - convert sample from Port format (E_Int24, E_Float, ..) to MOTU
611 //           native format
612 //
613 // We include the ability to start the transfer from the given offset within
614 // the port (expressed in frames) so the 'efficient' transfer method can be
615 // utilised.
616
617     unsigned int j=0;
618
619     // Use char here since the target address won't necessarily be
620     // aligned; use of an unaligned quadlet_t may cause issues on certain
621     // architectures.  Besides, the target (data going directly to the MOTU)
622     // isn't structured in quadlets anyway; it mainly consists of packed
623     // 24-bit integers.
624     unsigned char *target;
625     target = (unsigned char *)data + p->getPosition();
626
627     switch(m_StreamProcessorManager.getAudioDataType()) {
628         default:
629         case StreamProcessorManager::eADT_Int24:
630             {
631                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
632
633                 assert(nevents + offset <= p->getBufferSize());
634
635                 // Offset is in frames, but each port is only a single
636                 // channel, so the number of frames is the same as the
637                 // number of quadlets to offset (assuming the port buffer
638                 // uses one quadlet per sample, which is the case currently).
639                 buffer+=offset;
640
641                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
642                     *target = (*buffer >> 16) & 0xff;
643                     *(target+1) = (*buffer >> 8) & 0xff;
644                     *(target+2) = (*buffer) & 0xff;
645
646                     buffer++;
647                     target+=m_event_size;
648                 }
649             }
650             break;
651         case StreamProcessorManager::eADT_Float:
652             {
653                 const float multiplier = (float)(0x7FFFFF);
654                 float *buffer=(float *)(p->getBufferAddress());
655
656                 assert(nevents + offset <= p->getBufferSize());
657
658                 buffer+=offset;
659
660                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
661                     float in = *buffer;
662 #if MOTU_CLIP_FLOATS
663                     if (unlikely(in > 1.0)) in = 1.0;
664                     if (unlikely(in < -1.0)) in = -1.0;
665 #endif
666                     unsigned int v = lrintf(in * multiplier);
667                     *target = (v >> 16) & 0xff;
668                     *(target+1) = (v >> 8) & 0xff;
669                     *(target+2) = v & 0xff;
670
671                     buffer++;
672                     target+=m_event_size;
673                 }
674             }
675             break;
676     }
677
678     return 0;
679 }
680
681 int MotuTransmitStreamProcessor::encodeSilencePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
682                        unsigned int offset, unsigned int nevents) {
683     unsigned int j=0;
684     unsigned char *target = (unsigned char *)data + p->getPosition();
685
686     switch (m_StreamProcessorManager.getAudioDataType()) {
687     default:
688         case StreamProcessorManager::eADT_Int24:
689         case StreamProcessorManager::eADT_Float:
690         for (j = 0; j < nevents; j++) {
691             *target = *(target+1) = *(target+2) = 0;
692             target += m_event_size;
693         }
694         break;
695     }
696
697     return 0;
698 }
699
700 int MotuTransmitStreamProcessor::encodePortToMotuMidiEvents(
701                        MotuMidiPort *p, quadlet_t *data,
702                        unsigned int offset, unsigned int nevents) {
703
704     unsigned int j;
705     quadlet_t *src = (quadlet_t *)p->getBufferAddress();
706     src += offset;
707     unsigned char *target = (unsigned char *)data + p->getPosition();
708
709     // Send a MIDI byte if there is one to send.  MOTU MIDI data is sent using
710     // a 3-byte sequence within a frame starting at the port's position.
711     // A non-zero MSB indicates there is MIDI data to send.
712
713     for (j=0; j<nevents; j++, src++, target+=m_event_size) {
714         if (midi_lock)
715             midi_lock--;
716
717         /* FFADO's MIDI subsystem dictates that at the most there will be one
718          * MIDI byte every 8th's sample, making a MIDI byte "unlikely".
719          */
720         if (unlikely(*src & 0xff000000)) {
721             /* A MIDI byte is ready to send - buffer it */
722             midibuffer[mb_head++] = *src;
723             mb_head &= MIDIBUFFER_SIZE-1;
724             if (unlikely(mb_head == mb_tail)) {
725             /* Buffer overflow - dump oldest byte. */
726             /* Ideally this would dump an entire MIDI message, but this is only
727              * feasible if it's possible to determine the message size easily.
728              */
729                 mb_tail = (mb_tail+1) & (MIDIBUFFER_SIZE-1);
730                 debugWarning("MOTU MIDI buffer overflow\n");
731             }
732             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"Buffered MIDI byte %d\n", *src & 0xff);
733         }
734
735         /* Send the MIDI byte at the tail of the buffer if enough time has elapsed
736          * since the last MIDI byte was sent.  For most iterations through the loop
737          * this condition will be false.
738          */
739         if (unlikely(mb_head!=mb_tail && !midi_lock)) {
740             *(target) = 0x01;
741             *(target+1) = 0x00;
742             *(target+2) = midibuffer[mb_tail] & 0xff;
743             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"Sent MIDI byte %d (j=%d)\n", midibuffer[mb_tail], j);
744             mb_tail = (mb_tail+1) & (MIDIBUFFER_SIZE-1);
745             midi_lock = midi_tx_period;
746         }
747     }
748
749     return 0;
750 }
751
752 int MotuTransmitStreamProcessor::encodeSilencePortToMotuMidiEvents(
753                        MotuMidiPort *p, quadlet_t *data,
754                        unsigned int offset, unsigned int nevents) {
755
756     unsigned int j;
757     unsigned char *target = (unsigned char *)data + p->getPosition();
758
759     // For now, a "silent" MIDI event contains nothing but zeroes.  This
760     // may have to change if we find this isn't for some reason appropriate.
761     for (j=0; j<nevents; j++, target+=m_event_size) {
762        memset(target, 0, 3);
763     }
764
765     return 0;
766 }
767
768 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.