root/branches/ppalmers-streaming/src/libstreaming/motu/MotuStreamProcessor.cpp

Revision 703, 53.6 kB (checked in by ppalmers, 15 years ago)

- rework of streaming startup
- started moving files around to enhance structure

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