root/branches/streaming-rework/src/libstreaming/MotuStreamProcessor.cpp

Revision 430, 49.1 kB (checked in by jwoithe, 17 years ago)

MOTU: more streaming update work. Rx now appears to be working correctly.
Tx makes a noise but there are regular glitches, indicating that things
aren't quite right yet (the tx timestamps are probably not tight enough).

Line 
1 /* $Id$ */
2
3 /*
4  *   FreeBob Streaming API
5  *   FreeBob = Firewire (pro-)audio for linux
6  *
7  *   http://freebob.sf.net
8  *
9  *   Copyright (C) 2005,2006 Pieter Palmers <pieterpalmers@users.sourceforge.net>
10  *   Copyright (C) 2006 Jonathan Woithe <jwoithe@physics.adelaide.edu.au>
11  *
12  *   This program is free software {} you can redistribute it and/or modify
13  *   it under the terms of the GNU General Public License as published by
14  *   the Free Software Foundation {} either version 2 of the License, or
15  *   (at your option) any later version.
16  *
17  *   This program is distributed in the hope that it will be useful,
18  *   but WITHOUT ANY WARRANTY {} without even the implied warranty of
19  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *   GNU General Public License for more details.
21  *
22  *   You should have received a copy of the GNU General Public License
23  *   along with this program {} if not, write to the Free Software
24  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  *
27  *
28  */
29 #include "MotuStreamProcessor.h"
30 #include "Port.h"
31 #include "MotuPort.h"
32
33 #include <math.h>
34
35 #include <netinet/in.h>
36
37 #include "cycletimer.h"
38
39 // in ticks
40 #define TRANSMIT_TRANSFER_DELAY 6000U
41 // the number of cycles to send a packet in advance of it's timestamp
42 #define TRANSMIT_ADVANCE_CYCLES 1U
43
44 namespace Streaming {
45
46 IMPL_DEBUG_MODULE( MotuTransmitStreamProcessor, MotuTransmitStreamProcessor, DEBUG_LEVEL_NORMAL );
47 IMPL_DEBUG_MODULE( MotuReceiveStreamProcessor, MotuReceiveStreamProcessor, DEBUG_LEVEL_NORMAL );
48
49 // Set to 1 to enable the generation of a 1 kHz test tone in analog output 1
50 #define TESTTONE 1
51
52 // A macro to extract specific bits from a native endian quadlet
53 #define get_bits(_d,_start,_len) (((_d)>>((_start)-(_len)+1)) & ((1<<(_len))-1))
54
55 // Convert an SPH timestamp as received from the MOTU to a full timestamp in ticks.
56 static inline uint32_t sphRecvToFullTicks(uint32_t sph, uint32_t ct_now) {
57
58 uint32_t timestamp = CYCLE_TIMER_TO_TICKS(sph & 0x1ffffff);
59 uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(ct_now);
60
61 uint32_t ts_sec = CYCLE_TIMER_GET_SECS(ct_now);
62   // If the cycles have wrapped, correct ts_sec so it represents when timestamp
63   // was received.  The timestamps sent by the MOTU are always 1 or two cycles
64   // in advance of the cycle timer (reasons unknown at this stage).  In addition,
65   // iso buffering can delay the arrival of packets for quite a number of cycles
66   // (have seen a delay >12 cycles).
67   if (abs(CYCLE_TIMER_GET_CYCLES(sph) - now_cycles) > 1000) {
68 debugOutput(DEBUG_LEVEL_VERBOSE, "now=%d, ct=%d\n", now_cycles, CYCLE_TIMER_GET_CYCLES(sph));
69     if (ts_sec)
70       ts_sec--;
71     else
72       ts_sec = 127;
73   }
74   return timestamp + ts_sec*TICKS_PER_SECOND;
75 }
76
77 // Convert a full timestamp into an SPH timestamp as required by the MOTU
78 static inline uint32_t fullTicksToSph(uint32_t timestamp) {
79   return timestamp & 0x1ffffff;
80 }
81
82 /* transmit */
83 MotuTransmitStreamProcessor::MotuTransmitStreamProcessor(int port, int framerate,
84                 unsigned int event_size)
85         : TransmitStreamProcessor(port, framerate), m_event_size(event_size),
86         m_tx_dbc(0),
87         m_closedown_count(-1), m_streaming_active(0) {
88 }
89
90 MotuTransmitStreamProcessor::~MotuTransmitStreamProcessor() {
91
92 }
93
94 bool MotuTransmitStreamProcessor::init() {
95
96         debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing (%p)...\n");
97         // call the parent init
98         // this has to be done before allocating the buffers,
99         // because this sets the buffersizes from the processormanager
100         if(!TransmitStreamProcessor::init()) {
101                 debugFatal("Could not do base class init (%p)\n",this);
102                 return false;
103         }
104
105         return true;
106 }
107
108 void MotuTransmitStreamProcessor::setVerboseLevel(int l) {
109         setDebugLevel(l); // sets the debug level of the current object
110         TransmitStreamProcessor::setVerboseLevel(l); // also set the level of the base class
111 }
112
113
114 enum raw1394_iso_disposition
115 MotuTransmitStreamProcessor::getPacket(unsigned char *data, unsigned int *length,
116                       unsigned char *tag, unsigned char *sy,
117                       int cycle, unsigned int dropped, unsigned int max_length) {
118
119 // FIXME: the actual delays in the system need to be worked out so
120 // we can get this thing synchronised.  For now this seems to work.
121     uint64_t ts_head, fc;
122
123         quadlet_t *quadlet = (quadlet_t *)data;
124         signed int i;
125        
126     m_last_cycle=cycle;
127    
128     // determine if we want to send a packet or not
129     // note that we can't use getCycleTimer directly here,
130     // because packets are queued in advance. This means that
131     // we the packet we are constructing will be sent out
132     // on 'cycle', not 'now'.
133     unsigned int ctr=m_handler->getCycleTimer();
134     int now_cycles = (int)CYCLE_TIMER_GET_CYCLES(ctr);
135    
136     // the difference between the cycle this
137     // packet is intended for and 'now'
138     int cycle_diff = diffCycles(cycle, now_cycles);
139    
140         // Signal that streaming is still active
141         m_streaming_active = 1;
142
143     // as long as the cycle parameter is not in sync with
144     // the current time, the stream is considered not
145     // to be 'running'
146     // NOTE: this works only at startup
147     if (!m_running && cycle_diff >= 0 && cycle >= 0) {
148             debugOutput(DEBUG_LEVEL_VERBOSE, "Xmit StreamProcessor %p started running at cycle %d\n",this, cycle);
149             m_running=true;
150     }
151
152     if (!m_disabled && m_is_disabled) {
153         // this means that we are trying to enable
154         if ((unsigned int)cycle == m_cycle_to_enable_at) {
155             m_is_disabled=false;
156            
157             debugOutput(DEBUG_LEVEL_VERBOSE,"Enabling StreamProcessor %p at %u\n", this, cycle);
158            
159             // initialize the buffer head & tail
160             m_SyncSource->m_data_buffer->getBufferHeadTimestamp(&ts_head, &fc); // thread safe
161            
162             // the number of cycles the sync source lags (> 0)
163             // or leads (< 0)
164             int sync_lag_cycles=diffCycles(cycle, m_SyncSource->getLastCycle());
165            
166             // account for the cycle lag between sync SP and this SP
167             // the last update of the sync source's timestamps was sync_lag_cycles
168             // cycles before the cycle we are calculating the timestamp for.
169             // if we were to use one-frame buffers, you would expect the
170             // frame that is sent on cycle CT to have a timestamp T1.
171             // ts_head however is for cycle CT-sync_lag_cycles, and lies
172             // therefore sync_lag_cycles * TICKS_PER_CYCLE earlier than
173             // T1.
174             ts_head = addTicks(ts_head, sync_lag_cycles * TICKS_PER_CYCLE);
175            
176             m_data_buffer->setBufferTailTimestamp(ts_head);
177            
178             #ifdef DEBUG
179             if ((unsigned int)m_data_buffer->getFrameCounter() != m_data_buffer->getBufferSize()) {
180                 debugWarning("m_data_buffer->getFrameCounter() != m_data_buffer->getBufferSize()\n");
181             }
182             #endif
183             debugOutput(DEBUG_LEVEL_VERBOSE,"XMIT TS SET: TS=%10lld, LAG=%03d, FC=%4d\n",
184                             ts_head, sync_lag_cycles, m_data_buffer->getFrameCounter());
185         } else {
186             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
187                         "will enable StreamProcessor %p at %u, now is %d\n",
188                         this, m_cycle_to_enable_at, cycle);
189         }
190     } else if (m_disabled && !m_is_disabled) {
191         // trying to disable
192         debugOutput(DEBUG_LEVEL_VERBOSE,"disabling StreamProcessor %p at %u\n",
193                     this, cycle);
194         m_is_disabled=true;
195     }
196
197         // Do housekeeping expected for all packets sent to the MOTU, even
198         // for packets containing no audio data.
199         *sy = 0x00;
200         *tag = 1;      // All MOTU packets have a CIP-like header
201
202
203     // the base timestamp is the one of the next sample in the buffer
204     m_data_buffer->getBufferHeadTimestamp(&ts_head, &fc); // thread safe
205    
206     int64_t timestamp = ts_head;
207
208     // we send a packet some cycles in advance, to avoid the
209     // following situation:
210     // suppose we are only a few ticks away from
211     // the moment to send this packet. therefore we decide
212     // not to send the packet, but send it in the next cycle.
213     // This means that the next time point will be 3072 ticks
214     // later, making that the timestamp will be expired when the
215     // packet is sent, unless TRANSFER_DELAY > 3072.
216     // this means that we need at least one cycle of extra buffering.
217     uint64_t ticks_to_advance = TICKS_PER_CYCLE * TRANSMIT_ADVANCE_CYCLES;
218    
219     // if cycle lies cycle_diff cycles in the future, we should
220     // queue this packet cycle_diff * TICKS_PER_CYCLE earlier than
221     // we would if it were to be sent immediately.
222     ticks_to_advance += cycle_diff * TICKS_PER_CYCLE;
223
224     // determine the 'now' time in ticks
225     uint64_t cycle_timer=CYCLE_TIMER_TO_TICKS(ctr);
226    
227     // time until the packet is to be sent (if > 0: send packet)
228     int32_t until_next=diffTicks(timestamp, cycle_timer + ticks_to_advance);
229    
230         // Size of a single data frame in quadlets
231         unsigned dbs = m_event_size / 4;
232        
233     // don't process the stream when it is not enabled, not running
234     // or when the next sample is not due yet.
235     if((until_next>0) || m_is_disabled || !m_running) {
236         // send dummy packet
237        
238         // construct the packet CIP-like header.  Even if this is a data-less
239         // packet the dbs field is still set as if there were data blocks
240         // present.  For data-less packets the dbc is the same as the previously
241         // transmitted block.
242         *quadlet = htonl(0x00000400 | ((getNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
243         quadlet++;
244         *quadlet = htonl(0x8222ffff);
245         quadlet++;
246         *length = 8;
247        
248         #warning high-pitched sound protection removed!
249         // In the disabled state simply zero all data sent to the MOTU.  If
250         // a stream of empty packets are sent once iso streaming is enabled
251         // the MOTU tends to emit high-pitched audio (approx 10 kHz) for
252         // some reason.  This is not completely sufficient, however (zeroed
253         // packets must also be sent on iso closedown).
254    
255         // FIXME: Currently we simply send empty packets to the MOTU when
256         // the stream is disabled so the "m_disabled == 0" code is never
257         // executed.  However, this may change in future so it's left in
258         // for the moment for reference.
259         // FIXME: Currently we don't read the buffer at all during closedown.
260         // We could (and silently junk the contents) if it turned out to be
261         // more helpful.
262
263 //if (!m_is_disabled && m_running)
264 //  return RAW1394_ISO_OK;
265 //else 
266         return RAW1394_ISO_DEFER;
267     }
268
269         // The number of events expected by the MOTU is solely dependent on
270         // the current sample rate.  An 'event' is one sample from all channels
271         // plus possibly other midi and control data.
272         signed n_events = m_framerate<=48000?8:(m_framerate<=96000?16:32);
273
274     // add the transmit transfer delay to construct the playout time
275     uint64_t ts=addTicks(timestamp, TRANSMIT_TRANSFER_DELAY);
276    
277     if (m_data_buffer->readFrames(n_events, (char *)(data + 8))) {
278    
279         // Increment the dbc (data block count).  This is only done if the
280         // packet will contain events - that is, we are due to send some
281         // data.  Otherwise a pad packet is sent which contains the DBC of
282         // the previously sent packet.  This regime also means that the very
283         // first packet containing data will have a DBC of n_events, which
284         // matches what is observed from other systems.
285         m_tx_dbc += n_events;
286         if (m_tx_dbc > 0xff)
287             m_tx_dbc -= 0x100;
288    
289         // construct the packet CIP-like header.  Even if this is a data-less
290         // packet the dbs field is still set as if there were data blocks
291         // present.  For data-less packets the dbc is the same as the previously
292         // transmitted block.
293         *quadlet = htonl(0x00000400 | ((getNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
294         quadlet++;
295         *quadlet = htonl(0x8222ffff);
296         quadlet++;
297
298         *length = n_events*m_event_size + 8;
299
300         // convert the timestamp to Motu format
301         // I assume that it is in ticks, and wraps as the cycle timer
302         #warning syt conversion to be done
303        
304                 // FIXME: if we choose to read the buffer even during closedown,
305                 // here is where the data is silenced.
306                 //   if (m_closedown_count >= 0)
307                 //     memset(data+8, 0, read_size);
308                 if (m_closedown_count > 0)
309                         m_closedown_count--;
310
311                 // Set up each frames's SPH.  Note that the (int) typecast
312                 // appears to do rounding.
313
314 float ticks_per_frame = m_SyncSource->m_data_buffer->getRate();
315                 for (i=0; i<n_events; i++, quadlet += dbs) {
316 //                      unsigned int ts_frame = ts;
317                         unsigned int ts_frame = timestamp;
318                         ts_frame += (unsigned int)((float)i * ticks_per_frame);
319                         *quadlet = htonl( TICKS_TO_CYCLE_TIMER(ts_frame) & 0x1ffffff);
320 if (cycle==0) {
321   debugOutput(DEBUG_LEVEL_VERBOSE,"%d %d %d\n",
322     TICKS_TO_SECS(ts_frame),
323     TICKS_TO_CYCLES(ts_frame),
324     TICKS_TO_OFFSET(ts_frame));
325 }
326 #if TESTTONE
327                         // FIXME: remove this hacked in 1 kHz test signal to
328                         // analog-1 when testing is complete.  Note that the tone is
329                         // *never* added during closedown.
330                         if (m_closedown_count<0) {
331                                 static signed int a_cx = 0;
332                                 signed int val;
333                                 val = (int)(0x7fffff*sin(1000.0*2.0*M_PI*(a_cx/24576000.0)));
334                                 if ((a_cx+=512) >= 24576000) {
335                                         a_cx -= 24576000;
336                                 }
337                                 *(data+8+i*m_event_size+16) = (val >> 16) & 0xff;
338                                 *(data+8+i*m_event_size+17) = (val >> 8) & 0xff;
339                                 *(data+8+i*m_event_size+18) = val & 0xff;
340                         }
341 #endif
342
343                 }
344
345                 // Process all ports that should be handled on a per-packet base
346                 // this is MIDI for AMDTP (due to the need of DBC, which is lost
347                 // when putting the events in the ringbuffer)
348                 // for motu this might also be control data, however as control
349                 // data isn't time specific I would also include it in the period
350                 // based processing
351        
352                 // FIXME: m_tx_dbc probably needs to be initialised to a non-zero
353                 // value somehow so MIDI sync is possible.  For now we ignore
354                 // this issue.
355                 if (!encodePacketPorts((quadlet_t *)(data+8), n_events, m_tx_dbc)) {
356                         debugWarning("Problem encoding Packet Ports\n");
357                 }
358
359         return RAW1394_ISO_OK;
360        
361     } else if (now_cycles<cycle) {
362         // we can still postpone the queueing of the packets
363         return RAW1394_ISO_AGAIN;
364     } else { // there is no more data in the ringbuffer
365
366         debugWarning("Transmit buffer underrun (now %d, queue %d, target %d)\n",
367                  now_cycles, cycle, TICKS_TO_CYCLES(ts));
368
369         // signal underrun
370         m_xruns++;
371
372         // disable the processing, will be re-enabled when
373         // the xrun is handled
374         m_disabled=true;
375         m_is_disabled=true;
376
377         // compose a no-data packet, we should always
378         // send a valid packet
379        
380         // send dummy packet
381        
382         // construct the packet CIP-like header.  Even if this is a data-less
383         // packet the dbs field is still set as if there were data blocks
384         // present.  For data-less packets the dbc is the same as the previously
385         // transmitted block.
386         *quadlet = htonl(0x00000400 | ((getNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
387         quadlet++;
388         *quadlet = htonl(0x8222ffff);
389         quadlet++;
390         *length = 8;
391
392         return RAW1394_ISO_DEFER;
393     }
394
395     // we shouldn't get here
396     return RAW1394_ISO_ERROR;
397
398 }
399
400 int MotuTransmitStreamProcessor::getMinimalSyncDelay() {
401     return 0;
402 }
403
404 bool MotuTransmitStreamProcessor::prefill() {
405         // this is needed because otherwise there is no data to be
406         // sent when the streaming starts
407    
408         int i = m_nb_buffers;
409         while (i--) {
410                 if(!transferSilence(m_period)) {
411                         debugFatal("Could not prefill transmit stream\n");
412                         return false;
413                 }
414         }
415         return true;
416 }
417
418 bool MotuTransmitStreamProcessor::reset() {
419
420         debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
421
422     // we have to make sure that the buffer HEAD timestamp
423     // lies in the future for every possible buffer fill case.
424     int offset=(int)(m_data_buffer->getBufferSize()*m_ticks_per_frame);
425    
426     m_data_buffer->setTickOffset(offset);
427    
428         // reset all non-device specific stuff
429         // i.e. the iso stream and the associated ports
430         if (!TransmitStreamProcessor::reset()) {
431                 debugFatal("Could not do base class reset\n");
432                 return false;
433         }
434
435         // we should prefill the event buffer
436         if (!prefill()) {
437                 debugFatal("Could not prefill buffers\n");
438                 return false;   
439         }
440
441         return true;
442 }
443
444 bool MotuTransmitStreamProcessor::prepare() {
445    
446         debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing...\n");
447    
448         // prepare all non-device specific stuff
449         // i.e. the iso stream and the associated ports
450         if (!TransmitStreamProcessor::prepare()) {
451                 debugFatal("Could not prepare base class\n");
452                 return false;
453         }
454
455         m_PeriodStat.setName("XMT PERIOD");
456         m_PacketStat.setName("XMT PACKET");
457         m_WakeupStat.setName("XMT WAKEUP");
458
459         debugOutput( DEBUG_LEVEL_VERBOSE, "Event size: %d\n", m_event_size);
460    
461         // allocate the event buffer
462         unsigned int ringbuffer_size_frames=m_nb_buffers * m_period;
463
464     // allocate the internal buffer
465     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
466         unsigned int events_per_frame = m_framerate<=48000?8:(m_framerate<=96000?16:32);
467
468     assert(m_data_buffer);   
469     m_data_buffer->setBufferSize(ringbuffer_size_frames);
470     m_data_buffer->setEventSize(m_event_size);
471     m_data_buffer->setEventsPerFrame(1);
472    
473     m_data_buffer->setUpdatePeriod(m_period);
474     m_data_buffer->setNominalRate(m_ticks_per_frame);
475    
476     // FIXME: check if the timestamp wraps at one second
477     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
478    
479     m_data_buffer->prepare();
480
481         // Set the parameters of ports we can: we want the audio ports to be
482         // period buffered, and the midi ports to be packet buffered.
483         for ( PortVectorIterator it = m_Ports.begin();
484           it != m_Ports.end();
485           ++it ) {
486                 debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
487                 if(!(*it)->setBufferSize(m_period)) {
488                         debugFatal("Could not set buffer size to %d\n",m_period);
489                         return false;
490                 }
491
492                 switch ((*it)->getPortType()) {
493                 case Port::E_Audio:
494                         if (!(*it)->setSignalType(Port::E_PeriodSignalled)) {
495                                 debugFatal("Could not set signal type to PeriodSignalling");
496                                 return false;
497                         }
498                         break;
499
500                 case Port::E_Midi:
501                         if (!(*it)->setSignalType(Port::E_PacketSignalled)) {
502                                 debugFatal("Could not set signal type to PacketSignalling");
503                                 return false;
504                         }
505                         if (!(*it)->setBufferType(Port::E_RingBuffer)) {
506                                 debugFatal("Could not set buffer type");
507                                 return false;
508                         }
509                         if (!(*it)->setDataType(Port::E_MidiEvent)) {
510                                 debugFatal("Could not set data type");
511                                 return false;
512                         }
513                         // FIXME: probably need rate control too.  See
514                         // Port::useRateControl() and AmdtpStreamProcessor.
515                         break;
516                
517                 case Port::E_Control:
518                         if (!(*it)->setSignalType(Port::E_PeriodSignalled)) {
519                                 debugFatal("Could not set signal type to PeriodSignalling");
520                                 return false;
521                         }
522                         break;
523
524                 default:
525                         debugWarning("Unsupported port type specified\n");
526                         break;
527                 }
528         }
529
530         // The API specific settings of the ports are already set before
531         // this routine is called, therefore we can init&prepare the ports
532         if (!initPorts()) {
533                 debugFatal("Could not initialize ports!\n");
534                 return false;
535         }
536
537         if(!preparePorts()) {
538                 debugFatal("Could not initialize ports!\n");
539                 return false;
540         }
541
542         return true;
543 }
544
545 bool MotuTransmitStreamProcessor::prepareForStop() {
546
547         // If the stream is disabled or isn't running there's no need to
548         // wait since the MOTU *should* still be in a "zero data" state.
549         //
550         // If the m_streaming_active flag is 0 it indicates that the
551         // transmit callback hasn't been called since a closedown was
552         // requested when this function was last called.  This effectively
553         // signifies that the streaming thread has been exitted due to an
554         // xrun in either the receive or transmit handlers.  In this case
555         // there's no point in waiting for the closedown count to hit zero
556         // because it never will; the zero data will never get to the MOTU.
557         // It's best to allow an immediate stop and let the xrun handler
558         // proceed as best it can.
559         //
560         // The ability to detect the lack of streaming also prevents the
561         // "wait for stop" in the stream processor manager's stop() method
562         // from hitting its timeout which in turn seems to increase the
563         // probability of a successful recovery.
564         if (m_is_disabled || !isRunning() || !m_streaming_active)
565                 return true;
566
567         if (m_closedown_count < 0) {
568                 // No closedown has been initiated, so start one now.  Set
569                 // the closedown count to the number of zero packets which
570                 // will be sent to the MOTU before closing off the iso
571                 // streams.  FIXME: 128 packets (each containing 8 frames at
572                 // 48 kHz) is the experimentally-determined figure for 48
573                 // kHz with a period size of 1024.  It seems that at least
574                 // one period of zero samples need to be sent to allow for
575                 // inter-thread communication occuring on period boundaries.
576                 // This needs to be confirmed for other rates and period
577                 // sizes.
578                 signed n_events = m_framerate<=48000?8:(m_framerate<=96000?16:32);
579                 m_closedown_count = m_period / n_events;
580
581                 // Set up a test to confirm that streaming is still active.
582                 // If the streaming function hasn't been called by the next
583                 // iteration through this function there's no point in
584                 // continuing since it means the zero data will never get to
585                 // the MOTU.
586                 m_streaming_active = 0;
587                 return false;
588         }
589
590         // We are "go" for closedown once all requested zero packets
591         // (initiated by a previous call to this function) have been sent to
592         // the MOTU.
593         return m_closedown_count == 0;
594 }
595
596 bool MotuTransmitStreamProcessor::prepareForStart() {
597 // Reset some critical variables required so the stream starts cleanly. This
598 // method is called once on every stream restart. Initialisations which should
599 // be done once should be placed in the init() method instead.
600         m_running = 0;
601         m_closedown_count = -1;
602         m_streaming_active = 0;
603
604         // At this point we'll also disable the stream processor here.
605         // At this stage stream processors are always explicitly re-enabled
606         // after being started, so by starting in the disabled state we
607         // ensure that every start will be exactly the same.
608         disable();
609
610         return true;
611 }
612
613 bool MotuTransmitStreamProcessor::prepareForEnable(uint64_t time_to_enable_at) {
614
615     debugOutput(DEBUG_LEVEL_VERBOSE,"Preparing to enable...\n");
616
617     // for the transmit SP, we have to initialize the
618     // buffer timestamp to something sane, because this timestamp
619     // is used when it is SyncSource
620    
621     // the time we initialize to will determine the time at which
622     // the first sample in the buffer will be sent, so we should
623     // make it at least 'time_to_enable_at'
624    
625     uint64_t now=m_handler->getCycleTimer();
626     unsigned int now_secs=CYCLE_TIMER_GET_SECS(now);
627    
628     // check if a wraparound on the secs will happen between
629     // now and the time we start
630     if (CYCLE_TIMER_GET_CYCLES(now)>time_to_enable_at) {
631         // the start will happen in the next second
632         now_secs++;
633         if (now_secs>=128) now_secs=0;
634     }
635    
636 //    uint64_t ts_head= now_secs*TICKS_PER_SECOND;
637     uint64_t ts_head = time_to_enable_at*TICKS_PER_CYCLE;
638    
639     // we also add the nb of cycles we transmit in advance
640     ts_head=addTicks(ts_head, TRANSMIT_ADVANCE_CYCLES*TICKS_PER_CYCLE);
641    
642     m_data_buffer->setBufferTailTimestamp(ts_head);
643
644     if (!StreamProcessor::prepareForEnable(time_to_enable_at)) {
645         debugError("StreamProcessor::prepareForEnable failed\n");
646         return false;
647     }
648
649     return true;
650 }
651
652 bool MotuTransmitStreamProcessor::transferSilence(unsigned int size) {
653     bool retval;
654    
655         // This function should tranfer 'size' frames of 'silence' to the event buffer
656         char *dummybuffer=(char *)calloc(size,m_event_size);
657
658         transmitSilenceBlock(dummybuffer, size, 0);
659
660     // add the silence data to the ringbuffer
661     if(m_data_buffer->writeFrames(size, dummybuffer, 0)) {
662         retval=true;
663     } else {
664         debugWarning("Could not write to event buffer\n");
665         retval=false;
666     }
667
668         free(dummybuffer);
669
670         return retval;
671 }
672
673 bool MotuTransmitStreamProcessor::putFrames(unsigned int nbframes, int64_t ts) {
674     m_PeriodStat.mark(m_data_buffer->getBufferFill());
675    
676     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "MotuTransmitStreamProcessor::putFrames(%d, %llu)\n", nbframes, ts);
677    
678     // transfer the data
679     m_data_buffer->blockProcessWriteFrames(nbframes, ts);
680
681     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " New timestamp: %llu\n", ts);
682
683     return true;
684 }
685
686 /*
687  * write received events to the stream ringbuffers.
688  */
689
690 bool MotuTransmitStreamProcessor::processWriteBlock(char *data,
691                        unsigned int nevents, unsigned int offset) {
692         bool no_problem=true;
693         unsigned int i;
694
695         // FIXME: ensure the MIDI and control streams are all zeroed until
696         // such time as they are fully implemented.
697         for (i=0; i<nevents; i++) {
698                 memset(data+4+i*m_event_size, 0x00, 6);
699         }
700
701         for ( PortVectorIterator it = m_PeriodPorts.begin();
702           it != m_PeriodPorts.end();
703           ++it ) {
704                 // If this port is disabled, don't process it
705                 if((*it)->isDisabled()) {continue;};
706        
707                 //FIXME: make this into a static_cast when not DEBUG?
708                 Port *port=dynamic_cast<Port *>(*it);
709                
710                 switch(port->getPortType()) {
711                
712                 case Port::E_Audio:
713                         if (encodePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
714                                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
715                                 no_problem=false;
716                         }
717                         break;
718                 // midi is a packet based port, don't process
719                 //      case MotuPortInfo::E_Midi:
720                 //              break;
721
722                 default: // ignore
723                         break;
724                 }
725         }
726         return no_problem;
727 }
728
729 int MotuTransmitStreamProcessor::transmitSilenceBlock(char *data,
730                        unsigned int nevents, unsigned int offset) {
731         // This is the same as the non-silence version, except that is
732         // doesn't read from the port buffers.
733
734         int problem=0;
735
736         for ( PortVectorIterator it = m_PeriodPorts.begin();
737           it != m_PeriodPorts.end();
738           ++it ) {
739                 //FIXME: make this into a static_cast when not DEBUG?
740                 Port *port=dynamic_cast<Port *>(*it);
741                
742                 switch(port->getPortType()) {
743                
744                 case Port::E_Audio:
745                         if (encodeSilencePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
746                                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
747                                 problem=1;
748                         }
749                         break;
750                 // midi is a packet based port, don't process
751                 //      case MotuPortInfo::E_Midi:
752                 //              break;
753
754                 default: // ignore
755                         break;
756                 }
757         }
758         return problem;
759 }
760
761 /**
762  * @brief decode a packet for the packet-based ports
763  *
764  * @param data Packet data
765  * @param nevents number of events in data (including events of other ports & port types)
766  * @param dbc DataBlockCount value for this packet
767  * @return true if all successfull
768  */
769 bool MotuTransmitStreamProcessor::encodePacketPorts(quadlet_t *data, unsigned int nevents,
770                 unsigned int dbc) {
771         bool ok=true;
772         char byte;
773
774         // Use char here since the target address won't necessarily be
775         // aligned; use of an unaligned quadlet_t may cause issues on
776         // certain architectures.  Besides, the target for MIDI data going
777         // directly to the MOTU isn't structured in quadlets anyway; it is a
778         // sequence of 3 unaligned bytes.
779         unsigned char *target = NULL;
780
781         for ( PortVectorIterator it = m_PacketPorts.begin();
782                 it != m_PacketPorts.end();
783                 ++it ) {
784
785                 Port *port=static_cast<Port *>(*it);
786                 assert(port); // this should not fail!!
787
788                 // Currently the only packet type of events for MOTU
789                 // is MIDI in mbla.  However in future control data
790                 // might also be sent via "packet" events.
791                 // assert(pinfo->getFormat()==MotuPortInfo::E_Midi);
792
793                 // FIXME: MIDI output is completely untested at present.
794                 switch (port->getPortType()) {
795                         case Port::E_Midi: {
796                                 MotuMidiPort *mp=static_cast<MotuMidiPort *>(*it);
797
798                                 // Send a byte if we can. MOTU MIDI data is
799                                 // sent using a 3-byte sequence starting at
800                                 // the port's position.  For now we'll
801                                 // always send in the first event of a
802                                 // packet, but this might need refinement
803                                 // later.
804                                 if (mp->canRead()) {
805                                         mp->readEvent(&byte);
806                                         target = (unsigned char *)data + mp->getPosition();
807                                         *(target++) = 0x01;
808                                         *(target++) = 0x00;
809                                         *(target++) = byte;
810                                 }
811                                 break;
812                         }
813                         default:
814                                 debugOutput(DEBUG_LEVEL_VERBOSE, "Unknown packet-type port type %d\n",port->getPortType());
815                                 return ok;       
816                 }
817         }
818
819         return ok;
820 }
821
822 int MotuTransmitStreamProcessor::encodePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
823                        unsigned int offset, unsigned int nevents) {
824 // Encodes nevents worth of data from the given port into the given buffer.  The
825 // format of the buffer is precisely that which will be sent to the MOTU.
826 // The basic idea:
827 //   iterate over the ports
828 //     * get port buffer address
829 //     * loop over events
830 //         - pick right sample in event based upon PortInfo
831 //         - convert sample from Port format (E_Int24, E_Float, ..) to MOTU
832 //           native format
833 //
834 // We include the ability to start the transfer from the given offset within
835 // the port (expressed in frames) so the 'efficient' transfer method can be
836 // utilised.
837
838         unsigned int j=0;
839
840         // Use char here since the target address won't necessarily be
841         // aligned; use of an unaligned quadlet_t may cause issues on certain
842         // architectures.  Besides, the target (data going directly to the MOTU)
843         // isn't structured in quadlets anyway; it mainly consists of packed
844         // 24-bit integers.
845         unsigned char *target;
846         target = (unsigned char *)data + p->getPosition();
847
848         switch(p->getDataType()) {
849                 default:
850                 case Port::E_Int24:
851                         {
852                                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
853
854                                 assert(nevents + offset <= p->getBufferSize());
855
856                                 // Offset is in frames, but each port is only a single
857                                 // channel, so the number of frames is the same as the
858                                 // number of quadlets to offset (assuming the port buffer
859                                 // uses one quadlet per sample, which is the case currently).
860                                 buffer+=offset;
861
862                                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
863                                         *target = (*buffer >> 16) & 0xff;
864                                         *(target+1) = (*buffer >> 8) & 0xff;
865                                         *(target+2) = (*buffer) & 0xff;
866
867                                         buffer++;
868                                         target+=m_event_size;
869                                 }
870                         }
871                         break;
872                 case Port::E_Float:
873                         {
874                                 const float multiplier = (float)(0x7FFFFF);
875                                 float *buffer=(float *)(p->getBufferAddress());
876
877                                 assert(nevents + offset <= p->getBufferSize());
878
879                                 buffer+=offset;
880
881                                 for(j = 0; j < nevents; j += 1) { // decode max nsamples               
882                                         unsigned int v = (int)(*buffer * multiplier);
883                                         *target = (v >> 16) & 0xff;
884                                         *(target+1) = (v >> 8) & 0xff;
885                                         *(target+2) = v & 0xff;
886
887                                         buffer++;
888                                         target+=m_event_size;
889                                 }
890                         }
891                         break;
892         }
893
894         return 0;
895 }
896
897 int MotuTransmitStreamProcessor::encodeSilencePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
898                        unsigned int offset, unsigned int nevents) {
899         unsigned int j=0;
900         unsigned char *target = (unsigned char *)data + p->getPosition();
901
902         switch (p->getDataType()) {
903         default:
904         case Port::E_Int24:
905         case Port::E_Float:
906                 for (j = 0; j < nevents; j++) {
907                         *target = *(target+1) = *(target+2) = 0;
908                         target += m_event_size;
909                 }
910                 break;
911         }
912
913         return 0;
914 }
915
916 /* --------------------- RECEIVE ----------------------- */
917
918 MotuReceiveStreamProcessor::MotuReceiveStreamProcessor(int port, int framerate,
919         unsigned int event_size)
920     : ReceiveStreamProcessor(port, framerate), m_event_size(event_size),
921         m_closedown_active(0) {
922
923 }
924
925 MotuReceiveStreamProcessor::~MotuReceiveStreamProcessor() {
926
927 }
928
929 bool MotuReceiveStreamProcessor::init() {
930
931         // call the parent init
932         // this has to be done before allocating the buffers,
933         // because this sets the buffersizes from the processormanager
934         if(!ReceiveStreamProcessor::init()) {
935                 debugFatal("Could not do base class init (%d)\n",this);
936                 return false;
937         }
938
939         return true;
940 }
941
942         // NOTE by PP: timestamp based sync fixes this automagically by
943         //             enforcing that the roundtrip latency is constant:
944         // Detect missed receive cycles
945         // FIXME: it would be nice to advance the rx buffer by the amount of
946         // frames missed.  However, since the MOTU transmits more frames per
947         // cycle than the average and "catches up" with periodic empty
948         // cycles it's not trivial to work out precisely how many frames
949         // were missed.  Ultimately I think we need to do so if sync is to
950         // be maintained across a transient receive failure.
951        
952 enum raw1394_iso_disposition
953 MotuReceiveStreamProcessor::putPacket(unsigned char *data, unsigned int length,
954                   unsigned char channel, unsigned char tag, unsigned char sy,
955                   unsigned int cycle, unsigned int dropped) {
956    
957         enum raw1394_iso_disposition retval=RAW1394_ISO_OK;
958         // this is needed for the base class getLastCycle() to work.
959         // this avoids a function call like StreamProcessor::updateLastCycle()
960     m_last_cycle=cycle;
961
962     // check our enable status
963     if (!m_disabled && m_is_disabled) {
964         // this means that we are trying to enable
965         if (cycle == m_cycle_to_enable_at) {
966             m_is_disabled=false;
967             debugOutput(DEBUG_LEVEL_VERBOSE,"Enabling StreamProcessor %p at %d\n",
968                 this, cycle);
969                
970             // the previous timestamp is the one we need to start with
971             // because we're going to update the buffer again this loop
972             // using writeframes
973 //            m_data_buffer->setBufferTailTimestamp(m_last_timestamp2);
974             m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
975
976 debugOutput(DEBUG_LEVEL_VERBOSE,"On enable: last ts=%lld, ts2=%lld = %lld (%p)\n",
977   m_last_timestamp, m_last_timestamp2, m_last_timestamp-m_last_timestamp2,
978   m_data_buffer);
979
980         } else {
981             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
982                 "will enable StreamProcessor %p at %u, now is %d\n",
983                     this, m_cycle_to_enable_at, cycle);
984         }
985     } else if (m_disabled && !m_is_disabled) {
986         // trying to disable
987         debugOutput(DEBUG_LEVEL_VERBOSE,"disabling StreamProcessor %p at %u\n", this, cycle);
988         m_is_disabled=true;
989     }
990        
991         // If the packet length is 8 bytes (ie: just a CIP-like header)
992         // there is no isodata.
993         if (length > 8) {
994                 // The iso data blocks from the MOTUs comprise a CIP-like
995                 // header followed by a number of events (8 for 1x rates, 16
996                 // for 2x rates, 32 for 4x rates).
997                 quadlet_t *quadlet = (quadlet_t *)data;
998                 unsigned int dbs = get_bits(ntohl(quadlet[0]), 23, 8);  // Size of one event in terms of fdf_size
999                 unsigned int fdf_size = get_bits(ntohl(quadlet[1]), 23, 8) == 0x22 ? 32:0; // Event unit size in bits
1000
1001                 // Don't even attempt to process a packet if it isn't what
1002                 // we expect from a MOTU.  Yes, an FDF value of 32 bears
1003                 // little relationship to the actual data (24 bit integer)
1004                 // sent by the MOTU - it's one of those areas where MOTU
1005                 // have taken a curious detour around the standards.
1006                 if (tag!=1 || fdf_size!=32) {
1007                         return RAW1394_ISO_OK;
1008                 }
1009                
1010                 // put this after the check because event_length can become 0 on invalid packets
1011                 unsigned int event_length = (fdf_size * dbs) / 8;       // Event size in bytes
1012                 unsigned int n_events = (length-8) / event_length;
1013                
1014         //=> store the previous timestamp
1015         m_last_timestamp2=m_last_timestamp;
1016
1017         //=> convert the SYT to a full timestamp in ticks
1018 //        m_last_timestamp=sytRecvToFullTicks((uint32_t)ntohl(*(quadlet_t *)(data+8)),
1019 //                                        cycle, m_handler->getCycleTimer());
1020 //***
1021 // FIXME: it given that we later advance this to be the timestamp of the sample immediately following
1022 // this packet, it perhaps makes more sense to acquire the timestamp of the last frame in the packet.
1023 // Then it's just a matter of adding m_ticks_per_frame rather than frame_size times this.
1024 uint32_t first_sph = ntohl(*(quadlet_t *)(data+8));
1025 //uint32_t first_sph = ntohl(*(quadlet_t *)(data+8+(event_length*(n_events-1))));
1026 //        m_last_timestamp = ((first_sph & 0x1fff000)>>12)*3072 + (first_sph & 0xfff);
1027 //        m_last_timestamp = CYCLE_TIMER_TO_TICKS(first_sph & 0x1ffffff);
1028 m_last_timestamp = sphRecvToFullTicks(first_sph, m_handler->getCycleTimer());
1029
1030                 // Signal that we're running
1031         if(!m_running && n_events && m_last_timestamp2 && m_last_timestamp) {
1032             debugOutput(DEBUG_LEVEL_VERBOSE,"Receive StreamProcessor %p started running at %d\n", this, cycle);
1033             m_running=true;
1034         }
1035
1036         //=> don't process the stream samples when it is not enabled.
1037         if(m_is_disabled) {
1038
1039             // we keep track of the timestamp here
1040             // this makes sure that we will have a somewhat accurate
1041             // estimate as to when a period might be ready. i.e. it will not
1042             // be ready earlier than this timestamp + period time
1043            
1044             // the next (possible) sample is not this one, but lies
1045             // SYT_INTERVAL * rate later
1046             float frame_size=m_framerate<=48000?8:(m_framerate<=96000?16:32);
1047             uint64_t ts=addTicks(m_last_timestamp,
1048                                  (uint64_t)(frame_size * m_ticks_per_frame));
1049 //            uint64_t ts=addTicks(m_last_timestamp,
1050 //                                 (uint64_t)(m_ticks_per_frame));
1051
1052             // set the timestamp as if there will be a sample put into
1053             // the buffer by the next packet.
1054 if (ts >= 128L* TICKS_PER_SECOND)
1055   ts -= 128L*TICKS_PER_SECOND;
1056             m_data_buffer->setBufferTailTimestamp(ts);
1057 //debugOutput(DEBUG_LEVEL_VERBOSE,"%p, last ts=%lld, ts=%lld, lts2=%lld\n", m_data_buffer, m_last_timestamp, ts, m_last_timestamp2);
1058            
1059             return RAW1394_ISO_DEFER;
1060         }
1061
1062                 debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "put packet...\n");
1063 //debugOutput(DEBUG_LEVEL_VERBOSE,"enabled: %p, last ts=%lld, ts2=%lld\n",m_data_buffer, m_last_timestamp, m_last_timestamp2);
1064
1065         //=> process the packet
1066         // add the data payload to the ringbuffer
1067         if(m_data_buffer->writeFrames(n_events, (char *)(data+8), m_last_timestamp)) {
1068             retval=RAW1394_ISO_OK;
1069            
1070             int dbc = get_bits(ntohl(quadlet[0]), 8, 8);
1071            
1072             // process all ports that should be handled on a per-packet base
1073             // this is MIDI for AMDTP (due to the need of DBC)
1074             if (!decodePacketPorts((quadlet_t *)(data+8), n_events, dbc)) {
1075                 debugWarning("Problem decoding Packet Ports\n");
1076                 retval=RAW1394_ISO_DEFER;
1077             }
1078            
1079         } else {
1080        
1081             debugWarning("Receive buffer overrun (cycle %d, FC=%d, PC=%d)\n",
1082                  cycle, m_data_buffer->getFrameCounter(), m_handler->getPacketCount());
1083            
1084             m_xruns++;
1085            
1086             // disable the processing, will be re-enabled when
1087             // the xrun is handled
1088             m_disabled=true;
1089             m_is_disabled=true;
1090
1091             retval=RAW1394_ISO_DEFER;
1092         }
1093     }
1094
1095         return retval;
1096 }
1097
1098 // returns the delay between the actual (real) time of a timestamp as received,
1099 // and the timestamp that is passed on for the same event. This is to cope with
1100 // ISO buffering
1101 int MotuReceiveStreamProcessor::getMinimalSyncDelay() {
1102         unsigned int n_events = m_framerate<=48000?8:(m_framerate<=96000?16:32);
1103    
1104     return (int)(m_handler->getWakeupInterval() * n_events * m_ticks_per_frame);
1105 }
1106
1107 bool MotuReceiveStreamProcessor::reset() {
1108
1109         debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
1110
1111     m_data_buffer->setTickOffset(0);
1112
1113         // reset all non-device specific stuff
1114         // i.e. the iso stream and the associated ports
1115         if(!ReceiveStreamProcessor::reset()) {
1116                 debugFatal("Could not do base class reset\n");
1117                 return false;
1118         }
1119
1120         return true;
1121 }
1122
1123 bool MotuReceiveStreamProcessor::prepare() {
1124
1125         // prepare all non-device specific stuff
1126         // i.e. the iso stream and the associated ports
1127         if(!ReceiveStreamProcessor::prepare()) {
1128                 debugFatal("Could not prepare base class\n");
1129                 return false;
1130         }
1131
1132         debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing...\n");
1133
1134         m_PeriodStat.setName("RCV PERIOD");
1135         m_PacketStat.setName("RCV PACKET");
1136         m_WakeupStat.setName("RCV WAKEUP");
1137
1138     // setup any specific stuff here
1139     // FIXME: m_frame_size would be a better name
1140         debugOutput( DEBUG_LEVEL_VERBOSE, "Event size: %d\n", m_event_size);
1141    
1142     // prepare the framerate estimate
1143     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
1144        
1145         // initialize internal buffer
1146         unsigned int ringbuffer_size_frames=m_nb_buffers * m_period;
1147        
1148         unsigned int events_per_frame = m_framerate<=48000?8:(m_framerate<=96000?16:32);
1149
1150     assert(m_data_buffer);   
1151     m_data_buffer->setBufferSize(ringbuffer_size_frames);
1152     m_data_buffer->setEventSize(m_event_size);
1153     m_data_buffer->setEventsPerFrame(1);       
1154    
1155 // JMW: The rx buffer receives a new timestamp once per received frame so I think the
1156 // buffer update period is events_per_frame, not events per period.
1157 //    m_data_buffer->setUpdatePeriod(m_period);
1158     m_data_buffer->setUpdatePeriod(events_per_frame);
1159     m_data_buffer->setNominalRate(m_ticks_per_frame);
1160    
1161     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
1162    
1163     m_data_buffer->prepare();
1164
1165         // set the parameters of ports we can:
1166         // we want the audio ports to be period buffered,
1167         // and the midi ports to be packet buffered
1168         for ( PortVectorIterator it = m_Ports.begin();
1169                   it != m_Ports.end();
1170                   ++it )
1171         {
1172                 debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
1173                
1174                 if(!(*it)->setBufferSize(m_period)) {
1175                         debugFatal("Could not set buffer size to %d\n",m_period);
1176                         return false;
1177                 }
1178
1179                 switch ((*it)->getPortType()) {
1180                         case Port::E_Audio:
1181                                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1182                                         debugFatal("Could not set signal type to PeriodSignalling");
1183                                         return false;
1184                                 }
1185                                 break;
1186                         case Port::E_Midi:
1187                                 if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
1188                                         debugFatal("Could not set signal type to PacketSignalling");
1189                                         return false;
1190                                 }
1191                                 if (!(*it)->setBufferType(Port::E_RingBuffer)) {
1192                                         debugFatal("Could not set buffer type");
1193                                         return false;
1194                                 }
1195                                 if (!(*it)->setDataType(Port::E_MidiEvent)) {
1196                                         debugFatal("Could not set data type");
1197                                         return false;
1198                                 }
1199                                 // FIXME: probably need rate control too.  See
1200                                 // Port::useRateControl() and AmdtpStreamProcessor.
1201                                 break;
1202                         case Port::E_Control:
1203                                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1204                                         debugFatal("Could not set signal type to PeriodSignalling");
1205                                         return false;
1206                                 }
1207                                 break;
1208                         default:
1209                                 debugWarning("Unsupported port type specified\n");
1210                                 break;
1211                 }
1212
1213         }
1214
1215         // The API specific settings of the ports are already set before
1216         // this routine is called, therefore we can init&prepare the ports
1217         if(!initPorts()) {
1218                 debugFatal("Could not initialize ports!\n");
1219                 return false;
1220         }
1221
1222         if(!preparePorts()) {
1223                 debugFatal("Could not initialize ports!\n");
1224                 return false;
1225         }
1226        
1227         return true;
1228
1229 }
1230
1231
1232 bool MotuReceiveStreamProcessor::prepareForStop() {
1233
1234         // A MOTU receive stream can stop at any time.  However, signify
1235         // that stopping is in progress because other streams (notably the
1236         // transmit stream) may keep going for some time and cause an
1237         // overflow in the receive buffers.  If a closedown is in progress
1238         // the receive handler simply throws all incoming data away so
1239         // no buffer overflow can occur.
1240         m_closedown_active = 1;
1241         return true;
1242 }
1243
1244 bool MotuReceiveStreamProcessor::prepareForStart() {
1245 // Reset some critical variables required so the stream starts cleanly. This
1246 // method is called once on every stream restart, including those during
1247 // xrun recovery.  Initialisations which should be done once should be
1248 // placed in the init() method instead.
1249         m_running = 0;
1250         m_closedown_active = 0;
1251
1252         // At this point we'll also disable the stream processor here.
1253         // At this stage stream processors are always explicitly re-enabled
1254         // after being started, so by starting in the disabled state we
1255         // ensure that every start will be exactly the same.
1256         disable();
1257
1258         return true;
1259 }
1260
1261 bool MotuReceiveStreamProcessor::getFrames(unsigned int nbframes) {
1262
1263     m_PeriodStat.mark(m_data_buffer->getBufferFill());
1264
1265     // ask the buffer to process nbframes of frames
1266     // using it's registered client's processReadBlock(),
1267     // which should be ours
1268     m_data_buffer->blockProcessReadFrames(nbframes);
1269
1270     return true;
1271 }
1272
1273 /**
1274  * \brief write received events to the port ringbuffers.
1275  */
1276 bool MotuReceiveStreamProcessor::processReadBlock(char *data,
1277                                            unsigned int nevents, unsigned int offset)
1278 {
1279         bool no_problem=true;
1280         for ( PortVectorIterator it = m_PeriodPorts.begin();
1281           it != m_PeriodPorts.end();
1282           ++it ) {
1283                 if((*it)->isDisabled()) {continue;};
1284
1285                 //FIXME: make this into a static_cast when not DEBUG?
1286                 Port *port=dynamic_cast<Port *>(*it);
1287                
1288                 switch(port->getPortType()) {
1289                
1290                 case Port::E_Audio:
1291                         if(decodeMotuEventsToPort(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
1292                                 debugWarning("Could not decode packet MBLA to port %s",(*it)->getName().c_str());
1293                                 no_problem=false;
1294                         }
1295                         break;
1296                 // midi is a packet based port, don't process
1297                 //      case MotuPortInfo::E_Midi:
1298                 //              break;
1299
1300                 default: // ignore
1301                         break;
1302                 }
1303         }
1304         return no_problem;
1305 }
1306
1307 /**
1308  * @brief decode a packet for the packet-based ports
1309  *
1310  * @param data Packet data
1311  * @param nevents number of events in data (including events of other ports & port types)
1312  * @param dbc DataBlockCount value for this packet
1313  * @return true if all successfull
1314  */
1315 bool MotuReceiveStreamProcessor::decodePacketPorts(quadlet_t *data, unsigned int nevents,
1316                 unsigned int dbc) {
1317         bool ok=true;
1318
1319         // Use char here since the source address won't necessarily be
1320         // aligned; use of an unaligned quadlet_t may cause issues on
1321         // certain architectures.  Besides, the source for MIDI data going
1322         // directly to the MOTU isn't structured in quadlets anyway; it is a
1323         // sequence of 3 unaligned bytes.
1324         unsigned char *src = NULL;
1325
1326         for ( PortVectorIterator it = m_PacketPorts.begin();
1327                 it != m_PacketPorts.end();
1328                 ++it ) {
1329
1330                 Port *port=dynamic_cast<Port *>(*it);
1331                 assert(port); // this should not fail!!
1332
1333                 // Currently the only packet type of events for MOTU
1334                 // is MIDI in mbla.  However in future control data
1335                 // might also be sent via "packet" events, so allow
1336                 // for this possible expansion.
1337
1338                 // FIXME: MIDI input is completely untested at present.
1339                 switch (port->getPortType()) {
1340                         case Port::E_Midi: {
1341                                 MotuMidiPort *mp=static_cast<MotuMidiPort *>(*it);
1342                                 signed int sample;
1343                                 unsigned int j = 0;
1344                                 // Get MIDI bytes if present anywhere in the
1345                                 // packet.  MOTU MIDI data is sent using a
1346                                 // 3-byte sequence starting at the port's
1347                                 // position.  It's thought that there can never
1348                                 // be more than one MIDI byte per packet, but
1349                                 // for completeness we'll check the entire packet
1350                                 // anyway.
1351                                 src = (unsigned char *)data + mp->getPosition();
1352                                 while (j < nevents) {
1353                                         if (*src==0x01 && *(src+1)==0x00) {
1354                                                 sample = *(src+2);
1355                                                 if (!mp->writeEvent(&sample)) {
1356                                                         debugWarning("MIDI packet port events lost\n");
1357                                                         ok = false;
1358                                                 }
1359                                         }
1360                                         j++;
1361                                         src += m_event_size;
1362                                 }
1363                                 break;
1364                         }
1365                         default:
1366                                 debugOutput(DEBUG_LEVEL_VERBOSE, "Unknown packet-type port format %d\n",port->getPortType());
1367                                 return ok;       
1368                 }
1369         }
1370
1371         return ok;
1372 }
1373
1374 signed int MotuReceiveStreamProcessor::decodeMotuEventsToPort(MotuAudioPort *p,
1375                 quadlet_t *data, unsigned int offset, unsigned int nevents)
1376 {
1377         unsigned int j=0;
1378
1379         // Use char here since a port's source address won't necessarily be
1380         // aligned; use of an unaligned quadlet_t may cause issues on
1381         // certain architectures.  Besides, the source (data coming directly
1382         // from the MOTU) isn't structured in quadlets anyway; it mainly
1383         // consists of packed 24-bit integers.
1384
1385         unsigned char *src_data;
1386         src_data = (unsigned char *)data + p->getPosition();
1387
1388         switch(p->getDataType()) {
1389                 default:
1390                 case Port::E_Int24:
1391                         {
1392                                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
1393
1394                                 assert(nevents + offset <= p->getBufferSize());
1395
1396                                 // Offset is in frames, but each port is only a single
1397                                 // channel, so the number of frames is the same as the
1398                                 // number of quadlets to offset (assuming the port buffer
1399                                 // uses one quadlet per sample, which is the case currently).
1400                                 buffer+=offset;
1401
1402                                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
1403                                         *buffer = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
1404                                         // Sign-extend highest bit of 24-bit int.
1405                                         // FIXME: this isn't strictly needed since E_Int24 is a 24-bit,
1406                                         // but doing so shouldn't break anything and makes the data
1407                                         // easier to deal with during debugging.
1408                                         if (*src_data & 0x80)
1409                                                 *buffer |= 0xff000000;
1410
1411                                         buffer++;
1412                                         src_data+=m_event_size;
1413                                 }
1414                         }
1415                         break;
1416                 case Port::E_Float:
1417                         {
1418                                 const float multiplier = 1.0f / (float)(0x7FFFFF);
1419                                 float *buffer=(float *)(p->getBufferAddress());
1420
1421                                 assert(nevents + offset <= p->getBufferSize());
1422
1423                                 buffer+=offset;
1424
1425                                 for(j = 0; j < nevents; j += 1) { // decode max nsamples               
1426        
1427                                         unsigned int v = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
1428
1429                                         // sign-extend highest bit of 24-bit int
1430                                         int tmp = (int)(v << 8) / 256;
1431                
1432                                         *buffer = tmp * multiplier;
1433                                
1434                                         buffer++;
1435                                         src_data+=m_event_size;
1436                                 }
1437                         }
1438                         break;
1439         }
1440
1441         return 0;
1442 }
1443
1444 signed int MotuReceiveStreamProcessor::setEventSize(unsigned int size) {
1445         m_event_size = size;
1446         return 0;
1447 }
1448
1449 unsigned int MotuReceiveStreamProcessor::getEventSize(void) {
1450 //
1451 // Return the size of a single event sent by the MOTU as part of an iso
1452 // data packet in bytes.
1453 //
1454         return m_event_size;
1455 }
1456
1457 void MotuReceiveStreamProcessor::setVerboseLevel(int l) {
1458         setDebugLevel(l);
1459         ReceiveStreamProcessor::setVerboseLevel(l);
1460 }
1461
1462 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.