root/branches/libffado-2.0/src/libstreaming/motu/MotuTransmitStreamProcessor.cpp

Revision 1194, 27.4 kB (checked in by jwoithe, 14 years ago)

* MOTU: remove test tone for 2.0 branch.
* MOTU: in 2.0 branch, remove commented-out code related to ongoing debugging.

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