root/trunk/libffado/src/libstreaming/MotuStreamProcessor.cpp

Revision 515, 53.5 kB (checked in by jwoithe, 17 years ago)

Cosmetic cleanups of MOTU driver source. No functional changes.

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