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

Revision 1168, 28.9 kB (checked in by jwoithe, 14 years ago)

* MOTU: greatly increase the chances of having a clean shutdown of MOTU interfaces (that is, without the high-pitched squeal).

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