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

Revision 493, 57.6 kB (checked in by jwoithe, 17 years ago)

StreamProcessorManager?.cpp: MOTU requires larger ENABLE_DELAY_CYCLES to successfully start.
TimestampedBuffer?.cpp: MOTU needs more exact m_buffer_tail_timestamp.
MOTU: Make startup more reliable and nearly eliminate audio glitches in output.
Note that the changes to StreamProcessorManager?.cpp and TimestampedBuffer?.cpp are regarded as temporary while a more robust solution is devised following further investigations.

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