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

Revision 732, 53.6 kB (checked in by ppalmers, 14 years ago)

reorganize motu SP files to prepare for updated streaming implementation (disfunctional)

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