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

Revision 480, 52.8 kB (checked in by jwoithe, 15 years ago)

Make teststreaming2 work again (needed for MOTU debugging).
Fix a typo in StreamProcessorManager? which assigned the value of snoopMode to m_is_slave.
Debugging of MOTU driver.

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