root/trunk/libffado/src/libstreaming/rme/RmeTransmitStreamProcessor.cpp

Revision 2074, 27.9 kB (checked in by jwoithe, 12 years ago)

Maybe improve streaming restart reliability by ensuring IsoHandler? fields are reset during enable. Move RME run/dryrun flags into transmit streaming object so they can be reset. Add new device method resetForStreaming() which is called just before streaming is started; devices can use this to initialise streaming related details. RME uses new resetForStreaming() method to ensure the run/dryrun transmit stream flags are set up correctly. Despite these changes, attempts to make the RME driver restart after jack freewheels have been unsuccessful so far.

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