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

Revision 492, 56.8 kB (checked in by jwoithe, 17 years ago)

MOTU: more debugging. There's nothing really profound in these changes.

Line 
1 /*
2  * Copyright (C) 2005-2007 by Jonathan Woithe
3  * Copyright (C) 2005-2007 by Pieter Palmers
4  *
5  * This file is part of FFADO
6  * FFADO = Free Firewire (pro-)audio drivers for linux
7  *
8  * FFADO is based upon FreeBoB.
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License version 2.1, as published by the Free Software Foundation;
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22  * MA 02110-1301 USA
23  */
24
25 #include "MotuStreamProcessor.h"
26 #include "Port.h"
27 #include "MotuPort.h"
28
29 #include <math.h>
30
31 #include <netinet/in.h>
32
33 #include "cycletimer.h"
34
35 // in ticks
36 #define TRANSMIT_TRANSFER_DELAY 6000U
37 // the number of cycles to send a packet in advance of it's timestamp
38 #define TRANSMIT_ADVANCE_CYCLES 1U
39
40 namespace Streaming {
41
42 IMPL_DEBUG_MODULE( MotuTransmitStreamProcessor, MotuTransmitStreamProcessor, DEBUG_LEVEL_NORMAL );
43 IMPL_DEBUG_MODULE( MotuReceiveStreamProcessor, MotuReceiveStreamProcessor, DEBUG_LEVEL_NORMAL );
44
45 // Set to 1 to enable the generation of a 1 kHz test tone in analog output 1
46 #define TESTTONE 1
47
48 // A macro to extract specific bits from a native endian quadlet
49 #define get_bits(_d,_start,_len) (((_d)>>((_start)-(_len)+1)) & ((1<<(_len))-1))
50
51 // Convert an SPH timestamp as received from the MOTU to a full timestamp in ticks.
52 static inline uint32_t sphRecvToFullTicks(uint32_t sph, uint32_t ct_now) {
53
54 uint32_t timestamp = CYCLE_TIMER_TO_TICKS(sph & 0x1ffffff);
55 uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(ct_now);
56
57 uint32_t ts_sec = CYCLE_TIMER_GET_SECS(ct_now);
58   // If the cycles have wrapped, correct ts_sec so it represents when timestamp
59   // was received.  The timestamps sent by the MOTU are always 1 or two cycles
60   // in advance of the cycle timer (reasons unknown at this stage).  In addition,
61   // iso buffering can delay the arrival of packets for quite a number of cycles
62   // (have seen a delay >12 cycles).
63   // Every so often we also see sph wrapping ahead of ct_now, so deal with that
64   // too.
65   if (CYCLE_TIMER_GET_CYCLES(sph) > now_cycles + 1000) {
66 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         for (i=0; i<n_events; i++, quadlet += dbs) {
350 //FIXME: not sure which is best for the MOTU
351 //            int64_t ts_frame = addTicks(ts, (unsigned int)(i * ticks_per_frame));
352             int64_t ts_frame = addTicks(timestamp, (unsigned int)(i * ticks_per_frame));
353             *quadlet = htonl(fullTicksToSph(ts_frame));
354 #if 0
355 if (i==0) {
356   debugOutput(DEBUG_LEVEL_VERBOSE,"  ts_frame=%8x (%3d:%04d:%04d)\n",ts_frame,
357     TICKS_TO_SECS(ts_frame), TICKS_TO_CYCLES(ts_frame), TICKS_TO_OFFSET(ts_frame));
358 }
359 #endif
360 #if 0
361 if (cycle<2) {
362   debugOutput(DEBUG_LEVEL_VERBOSE,"cycle %d: %d %d %d\n",
363     cycle,
364     TICKS_TO_SECS(ts_frame),
365     TICKS_TO_CYCLES(ts_frame),
366     TICKS_TO_OFFSET(ts_frame));
367 }
368 #endif
369 #if TESTTONE
370             // FIXME: remove this hacked in 1 kHz test signal to
371             // analog-1 when testing is complete.  Note that the tone is
372             // *never* added during closedown.
373             if (m_closedown_count<0) {
374                 static signed int a_cx = 0;
375                 signed int val;
376                 val = (int)(0x7fffff*sin(1000.0*2.0*M_PI*(a_cx/24576000.0)));
377                  if ((a_cx+=512) >= 24576000) {
378                     a_cx -= 24576000;
379                 }
380                 *(data+8+i*m_event_size+16) = (val >> 16) & 0xff;
381                 *(data+8+i*m_event_size+17) = (val >> 8) & 0xff;
382                 *(data+8+i*m_event_size+18) = val & 0xff;
383             }
384 #endif
385
386         }
387
388         // Process all ports that should be handled on a per-packet base
389         // this is MIDI for AMDTP (due to the need of DBC, which is lost
390         // when putting the events in the ringbuffer)
391         // for motu this might also be control data, however as control
392         // data isn't time specific I would also include it in the period
393         // based processing
394
395         // FIXME: m_tx_dbc probably needs to be initialised to a non-zero
396         // value somehow so MIDI sync is possible.  For now we ignore
397         // this issue.
398         if (!encodePacketPorts((quadlet_t *)(data+8), n_events, m_tx_dbc)) {
399             debugWarning("Problem encoding Packet Ports\n");
400         }
401
402         return RAW1394_ISO_OK;
403
404     } else if (now_cycles<cycle) {
405         // we can still postpone the queueing of the packets
406         return RAW1394_ISO_AGAIN;
407     } else { // there is no more data in the ringbuffer
408
409         debugWarning("Transmit buffer underrun (now %d, queue %d, target %d)\n",
410                  now_cycles, cycle, TICKS_TO_CYCLES(ts));
411
412         // signal underrun
413         m_xruns++;
414
415         // disable the processing, will be re-enabled when
416         // the xrun is handled
417         m_disabled=true;
418         m_is_disabled=true;
419
420         // compose a no-data packet, we should always
421         // send a valid packet
422
423         // send dummy packet
424
425         // construct the packet CIP-like header.  Even if this is a data-less
426         // packet the dbs field is still set as if there were data blocks
427         // present.  For data-less packets the dbc is the same as the previously
428         // transmitted block.
429         *quadlet = htonl(0x00000400 | ((getNodeId()&0x3f)<<24) | m_tx_dbc | (dbs<<16));
430         quadlet++;
431         *quadlet = htonl(0x8222ffff);
432         quadlet++;
433         *length = 8;
434
435         return RAW1394_ISO_DEFER;
436     }
437
438     // we shouldn't get here
439     return RAW1394_ISO_ERROR;
440
441 }
442
443 int MotuTransmitStreamProcessor::getMinimalSyncDelay() {
444     return 0;
445 }
446
447 bool MotuTransmitStreamProcessor::prefill() {
448     // this is needed because otherwise there is no data to be
449     // sent when the streaming starts
450
451     int i = m_nb_buffers;
452     while (i--) {
453         if(!transferSilence(m_period)) {
454             debugFatal("Could not prefill transmit stream\n");
455             return false;
456         }
457     }
458     return true;
459 }
460
461 bool MotuTransmitStreamProcessor::reset() {
462
463     debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
464
465     // we have to make sure that the buffer HEAD timestamp
466     // lies in the future for every possible buffer fill case.
467     int offset=(int)(m_data_buffer->getBufferSize()*m_ticks_per_frame);
468
469     m_data_buffer->setTickOffset(offset);
470
471     // reset all non-device specific stuff
472     // i.e. the iso stream and the associated ports
473     if (!TransmitStreamProcessor::reset()) {
474         debugFatal("Could not do base class reset\n");
475         return false;
476     }
477
478     // we should prefill the event buffer
479     if (!prefill()) {
480         debugFatal("Could not prefill buffers\n");
481         return false;
482     }
483
484     return true;
485 }
486
487 bool MotuTransmitStreamProcessor::prepare() {
488
489     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing...\n");
490
491     // prepare all non-device specific stuff
492     // i.e. the iso stream and the associated ports
493     if (!TransmitStreamProcessor::prepare()) {
494         debugFatal("Could not prepare base class\n");
495         return false;
496     }
497
498     m_PeriodStat.setName("XMT PERIOD");
499     m_PacketStat.setName("XMT PACKET");
500     m_WakeupStat.setName("XMT WAKEUP");
501
502     debugOutput( DEBUG_LEVEL_VERBOSE, "Event size: %d\n", m_event_size);
503
504     // allocate the event buffer
505     unsigned int ringbuffer_size_frames=m_nb_buffers * m_period;
506
507     // allocate the internal buffer
508     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
509
510     assert(m_data_buffer);
511     // Note: terminology is slightly confused here.  From the point of view
512     // of the buffer the event size is the size of a single complete "event"
513     // in the MOTU datastream, which consists of one sample from each audio
514     // channel plus a timestamp and other control data.  Almost by
515     // definition then, the buffer's "events per frame" must be 1.  With
516     // these values, data copies to/from the MOTU data stream can be handled
517     // by the generic copying functions.
518     m_data_buffer->setBufferSize(ringbuffer_size_frames);
519     m_data_buffer->setEventSize(m_event_size);
520     m_data_buffer->setEventsPerFrame(1);
521
522     m_data_buffer->setUpdatePeriod(m_period);
523     m_data_buffer->setNominalRate(m_ticks_per_frame);
524
525     // FIXME: check if the timestamp wraps at one second
526     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
527
528     m_data_buffer->prepare();
529
530     // Set the parameters of ports we can: we want the audio ports to be
531     // period buffered, and the midi ports to be packet buffered.
532     for ( PortVectorIterator it = m_Ports.begin();
533       it != m_Ports.end();
534       ++it ) {
535         debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
536         if(!(*it)->setBufferSize(m_period)) {
537             debugFatal("Could not set buffer size to %d\n",m_period);
538             return false;
539             }
540
541         switch ((*it)->getPortType()) {
542         case Port::E_Audio:
543             if (!(*it)->setSignalType(Port::E_PeriodSignalled)) {
544                 debugFatal("Could not set signal type to PeriodSignalling");
545                 return false;
546             }
547             break;
548
549         case Port::E_Midi:
550             if (!(*it)->setSignalType(Port::E_PacketSignalled)) {
551                 debugFatal("Could not set signal type to PacketSignalling");
552                 return false;
553             }
554             if (!(*it)->setBufferType(Port::E_RingBuffer)) {
555                 debugFatal("Could not set buffer type");
556                 return false;
557             }
558             if (!(*it)->setDataType(Port::E_MidiEvent)) {
559                 debugFatal("Could not set data type");
560                 return false;
561             }
562             // FIXME: probably need rate control too.  See
563             // Port::useRateControl() and AmdtpStreamProcessor.
564             break;
565
566         case Port::E_Control:
567             if (!(*it)->setSignalType(Port::E_PeriodSignalled)) {
568                 debugFatal("Could not set signal type to PeriodSignalling");
569                 return false;
570             }
571             break;
572
573         default:
574             debugWarning("Unsupported port type specified\n");
575             break;
576         }
577     }
578
579     // The API specific settings of the ports are already set before
580     // this routine is called, therefore we can init&prepare the ports
581     if (!initPorts()) {
582         debugFatal("Could not initialize ports!\n");
583         return false;
584     }
585
586     if(!preparePorts()) {
587         debugFatal("Could not initialize ports!\n");
588         return false;
589     }
590
591     return true;
592 }
593
594 bool MotuTransmitStreamProcessor::prepareForStop() {
595
596     // If the stream is disabled or isn't running there's no need to
597     // wait since the MOTU *should* still be in a "zero data" state.
598     //
599     // If the m_streaming_active flag is 0 it indicates that the
600     // transmit callback hasn't been called since a closedown was
601     // requested when this function was last called.  This effectively
602     // signifies that the streaming thread has been exitted due to an
603     // xrun in either the receive or transmit handlers.  In this case
604     // there's no point in waiting for the closedown count to hit zero
605     // because it never will; the zero data will never get to the MOTU.
606     // It's best to allow an immediate stop and let the xrun handler
607     // proceed as best it can.
608     //
609     // The ability to detect the lack of streaming also prevents the
610     // "wait for stop" in the stream processor manager's stop() method
611     // from hitting its timeout which in turn seems to increase the
612     // probability of a successful recovery.
613     if (m_is_disabled || !isRunning() || !m_streaming_active)
614         return true;
615
616     if (m_closedown_count < 0) {
617         // No closedown has been initiated, so start one now.  Set
618         // the closedown count to the number of zero packets which
619         // will be sent to the MOTU before closing off the iso
620         // streams.  FIXME: 128 packets (each containing 8 frames at
621         // 48 kHz) is the experimentally-determined figure for 48
622         // kHz with a period size of 1024.  It seems that at least
623         // one period of zero samples need to be sent to allow for
624         // inter-thread communication occuring on period boundaries.
625         // This needs to be confirmed for other rates and period
626         // sizes.
627         signed n_events = m_framerate<=48000?8:(m_framerate<=96000?16:32);
628         m_closedown_count = m_period / n_events;
629
630         // Set up a test to confirm that streaming is still active.
631         // If the streaming function hasn't been called by the next
632         // iteration through this function there's no point in
633         // continuing since it means the zero data will never get to
634         // the MOTU.
635         m_streaming_active = 0;
636         return false;
637     }
638
639     // We are "go" for closedown once all requested zero packets
640     // (initiated by a previous call to this function) have been sent to
641     // the MOTU.
642     return m_closedown_count == 0;
643 }
644
645 bool MotuTransmitStreamProcessor::prepareForStart() {
646 // Reset some critical variables required so the stream starts cleanly. This
647 // method is called once on every stream restart. Initialisations which should
648 // be done once should be placed in the init() method instead.
649     m_running = 0;
650     m_closedown_count = -1;
651     m_streaming_active = 0;
652
653     // At this point we'll also disable the stream processor here.
654     // At this stage stream processors are always explicitly re-enabled
655     // after being started, so by starting in the disabled state we
656     // ensure that every start will be exactly the same.
657     disable();
658
659     return true;
660 }
661
662 bool MotuTransmitStreamProcessor::prepareForEnable(uint64_t time_to_enable_at) {
663
664     debugOutput(DEBUG_LEVEL_VERBOSE,"Preparing to enable...\n");
665
666     // for the transmit SP, we have to initialize the
667     // buffer timestamp to something sane, because this timestamp
668     // is used when it is SyncSource
669
670     // the time we initialize to will determine the time at which
671     // the first sample in the buffer will be sent, so we should
672     // make it at least 'time_to_enable_at'
673
674     uint64_t now=m_handler->getCycleTimer();
675     unsigned int now_secs=CYCLE_TIMER_GET_SECS(now);
676
677     // check if a wraparound on the secs will happen between
678     // now and the time we start
679     int until_enable=(int)time_to_enable_at - (int)CYCLE_TIMER_GET_CYCLES(now);
680
681     if(until_enable>4000) {
682         // wraparound on CYCLE_TIMER_GET_CYCLES(now)
683         // this means that we are late starting up,
684         // and that the start lies in the previous second
685         if (now_secs==0) now_secs=127;
686         else now_secs--;
687     } else if (until_enable<-4000) {
688         // wraparound on time_to_enable_at
689         // this means that we are early and that the start
690         // point lies in the next second
691         now_secs++;
692         if (now_secs>=128) now_secs=0;
693     }
694
695 ////    uint64_t ts_head= now_secs*TICKS_PER_SECOND;
696 //    uint64_t ts_head = time_to_enable_at*TICKS_PER_CYCLE;
697     uint64_t ts_head= now_secs*TICKS_PER_SECOND;
698     ts_head+=time_to_enable_at*TICKS_PER_CYCLE;
699
700     // we also add the nb of cycles we transmit in advance
701     ts_head=addTicks(ts_head, TRANSMIT_ADVANCE_CYCLES*TICKS_PER_CYCLE);
702
703     m_data_buffer->setBufferTailTimestamp(ts_head);
704
705     if (!StreamProcessor::prepareForEnable(time_to_enable_at)) {
706         debugError("StreamProcessor::prepareForEnable failed\n");
707         return false;
708     }
709
710     return true;
711 }
712
713 bool MotuTransmitStreamProcessor::transferSilence(unsigned int size) {
714     bool retval;
715
716     // This function should tranfer 'size' frames of 'silence' to the event buffer
717     char *dummybuffer=(char *)calloc(size,m_event_size);
718
719     transmitSilenceBlock(dummybuffer, size, 0);
720
721     // add the silence data to the ringbuffer
722     if(m_data_buffer->writeFrames(size, dummybuffer, 0)) {
723         retval=true;
724     } else {
725         debugWarning("Could not write to event buffer\n");
726         retval=false;
727     }
728
729     free(dummybuffer);
730
731     return retval;
732 }
733
734 bool MotuTransmitStreamProcessor::putFrames(unsigned int nbframes, int64_t ts) {
735     m_PeriodStat.mark(m_data_buffer->getBufferFill());
736
737     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "MotuTransmitStreamProcessor::putFrames(%d, %llu)\n", nbframes, ts);
738
739     // transfer the data
740 #if 0
741 debugOutput(DEBUG_LEVEL_VERBOSE, "1 - timestamp is %d\n", ts);
742 #endif
743     m_data_buffer->blockProcessWriteFrames(nbframes, ts);
744 #if 0
745 debugOutput(DEBUG_LEVEL_VERBOSE, "  done\n");
746 #endif
747     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " New timestamp: %llu\n", ts);
748
749     return true;
750 }
751
752 /*
753  * write received events to the stream ringbuffers.
754  */
755
756 bool MotuTransmitStreamProcessor::processWriteBlock(char *data,
757                        unsigned int nevents, unsigned int offset) {
758     bool no_problem=true;
759     unsigned int i;
760
761     // FIXME: ensure the MIDI and control streams are all zeroed until
762     // such time as they are fully implemented.
763     for (i=0; i<nevents; i++) {
764         memset(data+4+i*m_event_size, 0x00, 6);
765     }
766
767     for ( PortVectorIterator it = m_PeriodPorts.begin();
768       it != m_PeriodPorts.end();
769       ++it ) {
770         // If this port is disabled, don't process it
771         if((*it)->isDisabled()) {continue;};
772
773         //FIXME: make this into a static_cast when not DEBUG?
774         Port *port=dynamic_cast<Port *>(*it);
775
776         switch(port->getPortType()) {
777
778         case Port::E_Audio:
779             if (encodePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
780                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
781                 no_problem=false;
782             }
783             break;
784         // midi is a packet based port, don't process
785         //    case MotuPortInfo::E_Midi:
786         //        break;
787
788         default: // ignore
789             break;
790         }
791     }
792     return no_problem;
793 }
794
795 int MotuTransmitStreamProcessor::transmitSilenceBlock(char *data,
796                        unsigned int nevents, unsigned int offset) {
797     // This is the same as the non-silence version, except that is
798     // doesn't read from the port buffers.
799
800     int problem=0;
801
802     for ( PortVectorIterator it = m_PeriodPorts.begin();
803       it != m_PeriodPorts.end();
804       ++it ) {
805         //FIXME: make this into a static_cast when not DEBUG?
806         Port *port=dynamic_cast<Port *>(*it);
807
808         switch(port->getPortType()) {
809
810         case Port::E_Audio:
811             if (encodeSilencePortToMotuEvents(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
812                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
813                 problem=1;
814             }
815             break;
816         // midi is a packet based port, don't process
817         //    case MotuPortInfo::E_Midi:
818         //        break;
819
820         default: // ignore
821             break;
822         }
823     }
824     return problem;
825 }
826
827 /**
828  * @brief decode a packet for the packet-based ports
829  *
830  * @param data Packet data
831  * @param nevents number of events in data (including events of other ports & port types)
832  * @param dbc DataBlockCount value for this packet
833  * @return true if all successfull
834  */
835 bool MotuTransmitStreamProcessor::encodePacketPorts(quadlet_t *data, unsigned int nevents,
836         unsigned int dbc) {
837     bool ok=true;
838     char byte;
839
840     // Use char here since the target address won't necessarily be
841     // aligned; use of an unaligned quadlet_t may cause issues on
842     // certain architectures.  Besides, the target for MIDI data going
843     // directly to the MOTU isn't structured in quadlets anyway; it is a
844     // sequence of 3 unaligned bytes.
845     unsigned char *target = NULL;
846
847     for ( PortVectorIterator it = m_PacketPorts.begin();
848         it != m_PacketPorts.end();
849         ++it ) {
850
851         Port *port=static_cast<Port *>(*it);
852          assert(port); // this should not fail!!
853
854         // Currently the only packet type of events for MOTU
855         // is MIDI in mbla.  However in future control data
856         // might also be sent via "packet" events.
857         // assert(pinfo->getFormat()==MotuPortInfo::E_Midi);
858
859         // FIXME: MIDI output is completely untested at present.
860         switch (port->getPortType()) {
861             case Port::E_Midi: {
862                 MotuMidiPort *mp=static_cast<MotuMidiPort *>(*it);
863
864                 // Send a byte if we can. MOTU MIDI data is
865                 // sent using a 3-byte sequence starting at
866                 // the port's position.  For now we'll
867                 // always send in the first event of a
868                 // packet, but this might need refinement
869                 // later.
870                 if (mp->canRead()) {
871                     mp->readEvent(&byte);
872                     target = (unsigned char *)data + mp->getPosition();
873                     *(target++) = 0x01;
874                     *(target++) = 0x00;
875                     *(target++) = byte;
876                 }
877                 break;
878             }
879             default:
880                 debugOutput(DEBUG_LEVEL_VERBOSE, "Unknown packet-type port type %d\n",port->getPortType());
881                 return ok;
882               }
883     }
884
885     return ok;
886 }
887
888 int MotuTransmitStreamProcessor::encodePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
889                        unsigned int offset, unsigned int nevents) {
890 // Encodes nevents worth of data from the given port into the given buffer.  The
891 // format of the buffer is precisely that which will be sent to the MOTU.
892 // The basic idea:
893 //   iterate over the ports
894 //     * get port buffer address
895 //     * loop over events
896 //         - pick right sample in event based upon PortInfo
897 //         - convert sample from Port format (E_Int24, E_Float, ..) to MOTU
898 //           native format
899 //
900 // We include the ability to start the transfer from the given offset within
901 // the port (expressed in frames) so the 'efficient' transfer method can be
902 // utilised.
903
904     unsigned int j=0;
905
906     // Use char here since the target address won't necessarily be
907     // aligned; use of an unaligned quadlet_t may cause issues on certain
908     // architectures.  Besides, the target (data going directly to the MOTU)
909     // isn't structured in quadlets anyway; it mainly consists of packed
910     // 24-bit integers.
911     unsigned char *target;
912     target = (unsigned char *)data + p->getPosition();
913
914     switch(p->getDataType()) {
915         default:
916         case Port::E_Int24:
917             {
918                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
919
920                 assert(nevents + offset <= p->getBufferSize());
921
922                 // Offset is in frames, but each port is only a single
923                 // channel, so the number of frames is the same as the
924                 // number of quadlets to offset (assuming the port buffer
925                 // uses one quadlet per sample, which is the case currently).
926                 buffer+=offset;
927
928                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
929                     *target = (*buffer >> 16) & 0xff;
930                     *(target+1) = (*buffer >> 8) & 0xff;
931                     *(target+2) = (*buffer) & 0xff;
932
933                     buffer++;
934                     target+=m_event_size;
935                 }
936             }
937             break;
938         case Port::E_Float:
939             {
940                 const float multiplier = (float)(0x7FFFFF);
941                 float *buffer=(float *)(p->getBufferAddress());
942
943                 assert(nevents + offset <= p->getBufferSize());
944
945                 buffer+=offset;
946
947                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
948                     unsigned int v = (int)(*buffer * multiplier);
949                     *target = (v >> 16) & 0xff;
950                     *(target+1) = (v >> 8) & 0xff;
951                     *(target+2) = v & 0xff;
952
953                     buffer++;
954                     target+=m_event_size;
955                 }
956             }
957             break;
958     }
959
960     return 0;
961 }
962
963 int MotuTransmitStreamProcessor::encodeSilencePortToMotuEvents(MotuAudioPort *p, quadlet_t *data,
964                        unsigned int offset, unsigned int nevents) {
965     unsigned int j=0;
966     unsigned char *target = (unsigned char *)data + p->getPosition();
967
968     switch (p->getDataType()) {
969     default:
970         case Port::E_Int24:
971         case Port::E_Float:
972         for (j = 0; j < nevents; j++) {
973             *target = *(target+1) = *(target+2) = 0;
974             target += m_event_size;
975         }
976         break;
977     }
978
979     return 0;
980 }
981
982 /* --------------------- RECEIVE ----------------------- */
983
984 MotuReceiveStreamProcessor::MotuReceiveStreamProcessor(int port, int framerate,
985     unsigned int event_size)
986     : ReceiveStreamProcessor(port, framerate), m_event_size(event_size),
987     m_closedown_active(0) {
988
989 }
990
991 MotuReceiveStreamProcessor::~MotuReceiveStreamProcessor() {
992
993 }
994
995 bool MotuReceiveStreamProcessor::init() {
996
997     // call the parent init
998     // this has to be done before allocating the buffers,
999     // because this sets the buffersizes from the processormanager
1000     if(!ReceiveStreamProcessor::init()) {
1001         debugFatal("Could not do base class init (%d)\n",this);
1002         return false;
1003     }
1004
1005     return true;
1006 }
1007
1008     // NOTE by PP: timestamp based sync fixes this automagically by
1009     //             enforcing that the roundtrip latency is constant:
1010     // Detect missed receive cycles
1011     // FIXME: it would be nice to advance the rx buffer by the amount of
1012     // frames missed.  However, since the MOTU transmits more frames per
1013     // cycle than the average and "catches up" with periodic empty
1014     // cycles it's not trivial to work out precisely how many frames
1015     // were missed.  Ultimately I think we need to do so if sync is to
1016     // be maintained across a transient receive failure.
1017
1018 enum raw1394_iso_disposition
1019 MotuReceiveStreamProcessor::putPacket(unsigned char *data, unsigned int length,
1020                   unsigned char channel, unsigned char tag, unsigned char sy,
1021                   unsigned int cycle, unsigned int dropped) {
1022
1023     enum raw1394_iso_disposition retval=RAW1394_ISO_OK;
1024     // this is needed for the base class getLastCycle() to work.
1025     // this avoids a function call like StreamProcessor::updateLastCycle()
1026     m_last_cycle=cycle;
1027
1028 //debugOutput(DEBUG_LEVEL_VERBOSE,"rx: enabled=%d, cycle=%d\n",!m_is_disabled,cycle);
1029
1030     // check our enable status
1031     if (!m_disabled && m_is_disabled) {
1032         // this means that we are trying to enable
1033
1034         // check if we are on or past the enable point
1035         int cycles_past_enable=diffCycles(cycle, m_cycle_to_enable_at);
1036
1037         if (cycles_past_enable >= 0) {
1038             m_is_disabled=false;
1039             debugOutput(DEBUG_LEVEL_VERBOSE,"Enabling Rx StreamProcessor %p at %d\n",
1040                 this, cycle);
1041
1042             // the previous timestamp is the one we need to start with
1043             // because we're going to update the buffer again this loop
1044             // using writeframes
1045 //            m_data_buffer->setBufferTailTimestamp(m_last_timestamp2);
1046             m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
1047
1048 debugOutput(DEBUG_LEVEL_VERBOSE,"On enable: last ts=%lld, ts2=%lld = %lld (%p)\n",
1049   m_last_timestamp, m_last_timestamp2, m_last_timestamp-m_last_timestamp2,
1050   m_data_buffer);
1051
1052         } else {
1053 static int foo=0;
1054 if (!foo) {
1055 debugOutput(DEBUG_LEVEL_VERBOSE,
1056   "will enable rx StreamProcessor %p at %u, now is %d\n",
1057   this, m_cycle_to_enable_at, cycle);
1058   foo=1;
1059 }
1060             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
1061                 "will enable StreamProcessor %p at %u, now is %d\n",
1062                     this, m_cycle_to_enable_at, cycle);
1063         }
1064     } else if (m_disabled && !m_is_disabled) {
1065         // trying to disable
1066         debugOutput(DEBUG_LEVEL_VERBOSE,"disabling StreamProcessor %p at %u\n", this, cycle);
1067         m_is_disabled=true;
1068     }
1069
1070     // If the packet length is 8 bytes (ie: just a CIP-like header)
1071     // there is no isodata.
1072     if (length > 8) {
1073         // The iso data blocks from the MOTUs comprise a CIP-like
1074         // header followed by a number of events (8 for 1x rates, 16
1075         // for 2x rates, 32 for 4x rates).
1076         quadlet_t *quadlet = (quadlet_t *)data;
1077         unsigned int dbs = get_bits(ntohl(quadlet[0]), 23, 8);  // Size of one event in terms of fdf_size
1078         unsigned int fdf_size = get_bits(ntohl(quadlet[1]), 23, 8) == 0x22 ? 32:0; // Event unit size in bits
1079
1080         // Don't even attempt to process a packet if it isn't what
1081         // we expect from a MOTU.  Yes, an FDF value of 32 bears
1082         // little relationship to the actual data (24 bit integer)
1083         // sent by the MOTU - it's one of those areas where MOTU
1084         // have taken a curious detour around the standards.
1085         if (tag!=1 || fdf_size!=32) {
1086             return RAW1394_ISO_OK;
1087         }
1088
1089         // put this after the check because event_length can become 0 on invalid packets
1090         unsigned int event_length = (fdf_size * dbs) / 8;       // Event size in bytes
1091         unsigned int n_events = (length-8) / event_length;
1092
1093         //=> store the previous timestamp
1094         m_last_timestamp2=m_last_timestamp;
1095
1096         //=> convert the SYT to a full timestamp in ticks
1097 //        m_last_timestamp=sytRecvToFullTicks((uint32_t)ntohl(*(quadlet_t *)(data+8)),
1098 //                                        cycle, m_handler->getCycleTimer());
1099 //***
1100 // FIXME: it given that we later advance this to be the timestamp of the sample immediately following
1101 // this packet, it perhaps makes more sense to acquire the timestamp of the last frame in the packet.
1102 // Then it's just a matter of adding m_ticks_per_frame rather than frame_size times this.
1103 #if 0
1104 uint32_t first_sph = ntohl(*(quadlet_t *)(data+8));
1105 //uint32_t first_sph = ntohl(*(quadlet_t *)(data+8+(event_length*(n_events-1))));
1106 //        m_last_timestamp = ((first_sph & 0x1fff000)>>12)*3072 + (first_sph & 0xfff);
1107 //        m_last_timestamp = CYCLE_TIMER_TO_TICKS(first_sph & 0x1ffffff);
1108 m_last_timestamp = sphRecvToFullTicks(first_sph, m_handler->getCycleTimer());
1109 float frame_size=m_framerate<=48000?8:(m_framerate<=96000?16:32);
1110 uint64_t ts=addTicks(m_last_timestamp, (uint64_t)((frame_size-1) * m_ticks_per_frame));
1111 m_last_timestamp = ts;
1112 #endif
1113
1114 #if 1
1115 uint32_t last_sph = ntohl(*(quadlet_t *)(data+8+(n_events-1)*event_length));
1116 m_last_timestamp = sphRecvToFullTicks(last_sph, m_handler->getCycleTimer());
1117 #endif
1118                                                          
1119         // Signal that we're running
1120         if(!m_running && n_events && m_last_timestamp2 && m_last_timestamp) {
1121             debugOutput(DEBUG_LEVEL_VERBOSE,"Receive StreamProcessor %p started running at %d\n", this, cycle);
1122             m_running=true;
1123         }
1124
1125         //=> don't process the stream samples when it is not enabled.
1126         if(m_is_disabled) {
1127
1128             // we keep track of the timestamp here
1129             // this makes sure that we will have a somewhat accurate
1130             // estimate as to when a period might be ready. i.e. it will not
1131             // be ready earlier than this timestamp + period time
1132
1133             // the next (possible) sample is not this one, but lies
1134             // SYT_INTERVAL * rate later
1135             float frame_size=m_framerate<=48000?8:(m_framerate<=96000?16:32);
1136             uint64_t ts=addTicks(m_last_timestamp,
1137                                  (uint64_t)(frame_size * m_ticks_per_frame));
1138 //            uint64_t ts=addTicks(m_last_timestamp,
1139 //                                 (uint64_t)(m_ticks_per_frame));
1140
1141             // set the timestamp as if there will be a sample put into
1142             // the buffer by the next packet.  This means we use the timestamp
1143             // corresponding to the last frame which would have been added to the
1144             // buffer this cycle if we weren't disabled.
1145 if (ts >= 128L* TICKS_PER_SECOND)
1146   ts -= 128L*TICKS_PER_SECOND;
1147 //            m_data_buffer->setBufferTailTimestamp(ts);
1148             m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
1149 //debugOutput(DEBUG_LEVEL_VERBOSE,"%p, last ts=%lld, ts=%lld, lts2=%lld\n", m_data_buffer, m_last_timestamp, ts, m_last_timestamp2);
1150
1151             return RAW1394_ISO_DEFER;
1152         }
1153
1154         debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "put packet...\n");
1155 //debugOutput(DEBUG_LEVEL_VERBOSE,"cycle=%d, mp=%d, last ts=%lld, ts2=%lld\n",cycle,m_period, m_last_timestamp, m_last_timestamp2);
1156
1157         //=> process the packet
1158         // add the data payload to the ringbuffer
1159         // Note: the last argument to writeFrames is the timestamp of the *last sample* being
1160         // added.
1161         if(m_data_buffer->writeFrames(n_events, (char *)(data+8), m_last_timestamp)) {
1162             retval=RAW1394_ISO_OK;
1163             int dbc = get_bits(ntohl(quadlet[0]), 8, 8);
1164
1165             // process all ports that should be handled on a per-packet base
1166             // this is MIDI for AMDTP (due to the need of DBC)
1167             if (!decodePacketPorts((quadlet_t *)(data+8), n_events, dbc)) {
1168                 debugWarning("Problem decoding Packet Ports\n");
1169                 retval=RAW1394_ISO_DEFER;
1170             }
1171
1172         } else {
1173
1174             debugWarning("Receive buffer overrun (cycle %d, FC=%d, PC=%d)\n",
1175                  cycle, m_data_buffer->getFrameCounter(), m_handler->getPacketCount());
1176
1177             m_xruns++;
1178
1179             // disable the processing, will be re-enabled when
1180             // the xrun is handled
1181             m_disabled=true;
1182             m_is_disabled=true;
1183
1184             retval=RAW1394_ISO_DEFER;
1185         }
1186     }
1187
1188     return retval;
1189 }
1190
1191 // returns the delay between the actual (real) time of a timestamp as received,
1192 // and the timestamp that is passed on for the same event. This is to cope with
1193 // ISO buffering
1194 int MotuReceiveStreamProcessor::getMinimalSyncDelay() {
1195     unsigned int n_events = m_framerate<=48000?8:(m_framerate<=96000?16:32);
1196
1197     return (int)(m_handler->getWakeupInterval() * n_events * m_ticks_per_frame);
1198 }
1199
1200 bool MotuReceiveStreamProcessor::reset() {
1201
1202     debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
1203
1204     m_data_buffer->setTickOffset(0);
1205
1206     // reset all non-device specific stuff
1207     // i.e. the iso stream and the associated ports
1208     if(!ReceiveStreamProcessor::reset()) {
1209         debugFatal("Could not do base class reset\n");
1210         return false;
1211     }
1212
1213     return true;
1214 }
1215
1216 bool MotuReceiveStreamProcessor::prepare() {
1217
1218     // prepare all non-device specific stuff
1219     // i.e. the iso stream and the associated ports
1220     if(!ReceiveStreamProcessor::prepare()) {
1221         debugFatal("Could not prepare base class\n");
1222         return false;
1223     }
1224
1225     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing...\n");
1226
1227     m_PeriodStat.setName("RCV PERIOD");
1228     m_PacketStat.setName("RCV PACKET");
1229     m_WakeupStat.setName("RCV WAKEUP");
1230
1231     // setup any specific stuff here
1232     // FIXME: m_frame_size would be a better name
1233     debugOutput( DEBUG_LEVEL_VERBOSE, "Event size: %d\n", m_event_size);
1234
1235     // prepare the framerate estimate
1236     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
1237
1238     // initialize internal buffer
1239     unsigned int ringbuffer_size_frames=m_nb_buffers * m_period;
1240
1241     unsigned int events_per_frame = m_framerate<=48000?8:(m_framerate<=96000?16:32);
1242
1243     assert(m_data_buffer);
1244     m_data_buffer->setBufferSize(ringbuffer_size_frames);
1245     m_data_buffer->setEventSize(m_event_size);
1246     m_data_buffer->setEventsPerFrame(1);
1247
1248 // JMW: The rx buffer receives a new timestamp once per received frame so I think the
1249 // buffer update period is events_per_frame, not events per period.
1250 //    m_data_buffer->setUpdatePeriod(m_period);
1251     m_data_buffer->setUpdatePeriod(events_per_frame);
1252     m_data_buffer->setNominalRate(m_ticks_per_frame);
1253
1254     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
1255
1256     m_data_buffer->prepare();
1257
1258     // set the parameters of ports we can:
1259     // we want the audio ports to be period buffered,
1260     // and the midi ports to be packet buffered
1261     for ( PortVectorIterator it = m_Ports.begin();
1262           it != m_Ports.end();
1263           ++it )
1264     {
1265         debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
1266
1267         if(!(*it)->setBufferSize(m_period)) {
1268             debugFatal("Could not set buffer size to %d\n",m_period);
1269             return false;
1270         }
1271
1272         switch ((*it)->getPortType()) {
1273             case Port::E_Audio:
1274                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1275                     debugFatal("Could not set signal type to PeriodSignalling");
1276                     return false;
1277                 }
1278                 break;
1279             case Port::E_Midi:
1280                 if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
1281                     debugFatal("Could not set signal type to PacketSignalling");
1282                     return false;
1283                 }
1284                 if (!(*it)->setBufferType(Port::E_RingBuffer)) {
1285                     debugFatal("Could not set buffer type");
1286                     return false;
1287                 }
1288                 if (!(*it)->setDataType(Port::E_MidiEvent)) {
1289                     debugFatal("Could not set data type");
1290                     return false;
1291                 }
1292                 // FIXME: probably need rate control too.  See
1293                 // Port::useRateControl() and AmdtpStreamProcessor.
1294                 break;
1295             case Port::E_Control:
1296                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1297                     debugFatal("Could not set signal type to PeriodSignalling");
1298                     return false;
1299                 }
1300                 break;
1301             default:
1302                 debugWarning("Unsupported port type specified\n");
1303                 break;
1304         }
1305
1306     }
1307
1308     // The API specific settings of the ports are already set before
1309     // this routine is called, therefore we can init&prepare the ports
1310     if(!initPorts()) {
1311         debugFatal("Could not initialize ports!\n");
1312         return false;
1313     }
1314
1315     if(!preparePorts()) {
1316         debugFatal("Could not initialize ports!\n");
1317         return false;
1318     }
1319
1320     return true;
1321
1322 }
1323
1324
1325 bool MotuReceiveStreamProcessor::prepareForStop() {
1326
1327     // A MOTU receive stream can stop at any time.  However, signify
1328     // that stopping is in progress because other streams (notably the
1329     // transmit stream) may keep going for some time and cause an
1330     // overflow in the receive buffers.  If a closedown is in progress
1331     // the receive handler simply throws all incoming data away so
1332     // no buffer overflow can occur.
1333     m_closedown_active = 1;
1334     return true;
1335 }
1336
1337 bool MotuReceiveStreamProcessor::prepareForStart() {
1338 // Reset some critical variables required so the stream starts cleanly. This
1339 // method is called once on every stream restart, including those during
1340 // xrun recovery.  Initialisations which should be done once should be
1341 // placed in the init() method instead.
1342     m_running = 0;
1343     m_closedown_active = 0;
1344
1345     // At this point we'll also disable the stream processor here.
1346     // At this stage stream processors are always explicitly re-enabled
1347     // after being started, so by starting in the disabled state we
1348     // ensure that every start will be exactly the same.
1349     disable();
1350
1351     return true;
1352 }
1353
1354 bool MotuReceiveStreamProcessor::getFrames(unsigned int nbframes) {
1355
1356     m_PeriodStat.mark(m_data_buffer->getBufferFill());
1357
1358     // ask the buffer to process nbframes of frames
1359     // using it's registered client's processReadBlock(),
1360     // which should be ours
1361     m_data_buffer->blockProcessReadFrames(nbframes);
1362
1363     return true;
1364 }
1365
1366 /**
1367  * \brief write received events to the port ringbuffers.
1368  */
1369 bool MotuReceiveStreamProcessor::processReadBlock(char *data,
1370                        unsigned int nevents, unsigned int offset)
1371 {
1372     bool no_problem=true;
1373     for ( PortVectorIterator it = m_PeriodPorts.begin();
1374           it != m_PeriodPorts.end();
1375           ++it ) {
1376         if((*it)->isDisabled()) {continue;};
1377
1378         //FIXME: make this into a static_cast when not DEBUG?
1379         Port *port=dynamic_cast<Port *>(*it);
1380
1381         switch(port->getPortType()) {
1382
1383         case Port::E_Audio:
1384             if(decodeMotuEventsToPort(static_cast<MotuAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
1385                 debugWarning("Could not decode packet MBLA to port %s",(*it)->getName().c_str());
1386                 no_problem=false;
1387             }
1388             break;
1389         // midi is a packet based port, don't process
1390         //    case MotuPortInfo::E_Midi:
1391         //        break;
1392
1393         default: // ignore
1394             break;
1395         }
1396     }
1397     return no_problem;
1398 }
1399
1400 /**
1401  * @brief decode a packet for the packet-based ports
1402  *
1403  * @param data Packet data
1404  * @param nevents number of events in data (including events of other ports & port types)
1405  * @param dbc DataBlockCount value for this packet
1406  * @return true if all successfull
1407  */
1408 bool MotuReceiveStreamProcessor::decodePacketPorts(quadlet_t *data, unsigned int nevents,
1409         unsigned int dbc) {
1410     bool ok=true;
1411
1412     // Use char here since the source address won't necessarily be
1413     // aligned; use of an unaligned quadlet_t may cause issues on
1414     // certain architectures.  Besides, the source for MIDI data going
1415     // directly to the MOTU isn't structured in quadlets anyway; it is a
1416     // sequence of 3 unaligned bytes.
1417     unsigned char *src = NULL;
1418
1419     for ( PortVectorIterator it = m_PacketPorts.begin();
1420         it != m_PacketPorts.end();
1421         ++it ) {
1422
1423         Port *port=dynamic_cast<Port *>(*it);
1424         assert(port); // this should not fail!!
1425
1426         // Currently the only packet type of events for MOTU
1427         // is MIDI in mbla.  However in future control data
1428         // might also be sent via "packet" events, so allow
1429         // for this possible expansion.
1430
1431         // FIXME: MIDI input is completely untested at present.
1432         switch (port->getPortType()) {
1433             case Port::E_Midi: {
1434                 MotuMidiPort *mp=static_cast<MotuMidiPort *>(*it);
1435                 signed int sample;
1436                 unsigned int j = 0;
1437                 // Get MIDI bytes if present anywhere in the
1438                 // packet.  MOTU MIDI data is sent using a
1439                 // 3-byte sequence starting at the port's
1440                 // position.  It's thought that there can never
1441                 // be more than one MIDI byte per packet, but
1442                 // for completeness we'll check the entire packet
1443                 // anyway.
1444                 src = (unsigned char *)data + mp->getPosition();
1445                 while (j < nevents) {
1446                     if (*src==0x01 && *(src+1)==0x00) {
1447                         sample = *(src+2);
1448                         if (!mp->writeEvent(&sample)) {
1449                             debugWarning("MIDI packet port events lost\n");
1450                             ok = false;
1451                         }
1452                     }
1453                     j++;
1454                     src += m_event_size;
1455                 }
1456                 break;
1457             }
1458             default:
1459                 debugOutput(DEBUG_LEVEL_VERBOSE, "Unknown packet-type port format %d\n",port->getPortType());
1460                 return ok;
1461               }
1462     }
1463
1464     return ok;
1465 }
1466
1467 signed int MotuReceiveStreamProcessor::decodeMotuEventsToPort(MotuAudioPort *p,
1468         quadlet_t *data, unsigned int offset, unsigned int nevents)
1469 {
1470     unsigned int j=0;
1471
1472     // Use char here since a port's source address won't necessarily be
1473     // aligned; use of an unaligned quadlet_t may cause issues on
1474     // certain architectures.  Besides, the source (data coming directly
1475     // from the MOTU) isn't structured in quadlets anyway; it mainly
1476     // consists of packed 24-bit integers.
1477
1478     unsigned char *src_data;
1479     src_data = (unsigned char *)data + p->getPosition();
1480
1481     switch(p->getDataType()) {
1482         default:
1483         case Port::E_Int24:
1484             {
1485                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
1486
1487                 assert(nevents + offset <= p->getBufferSize());
1488
1489                 // Offset is in frames, but each port is only a single
1490                 // channel, so the number of frames is the same as the
1491                 // number of quadlets to offset (assuming the port buffer
1492                 // uses one quadlet per sample, which is the case currently).
1493                 buffer+=offset;
1494
1495                 for(j = 0; j < nevents; j += 1) { // Decode nsamples
1496                     *buffer = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
1497                     // Sign-extend highest bit of 24-bit int.
1498                     // FIXME: this isn't strictly needed since E_Int24 is a 24-bit,
1499                     // but doing so shouldn't break anything and makes the data
1500                     // easier to deal with during debugging.
1501                     if (*src_data & 0x80)
1502                         *buffer |= 0xff000000;
1503
1504                     buffer++;
1505                     src_data+=m_event_size;
1506                 }
1507             }
1508             break;
1509         case Port::E_Float:
1510             {
1511                 const float multiplier = 1.0f / (float)(0x7FFFFF);
1512                 float *buffer=(float *)(p->getBufferAddress());
1513
1514                 assert(nevents + offset <= p->getBufferSize());
1515
1516                 buffer+=offset;
1517
1518                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
1519
1520                     unsigned int v = (*src_data<<16)+(*(src_data+1)<<8)+*(src_data+2);
1521
1522                     // sign-extend highest bit of 24-bit int
1523                     int tmp = (int)(v << 8) / 256;
1524
1525                     *buffer = tmp * multiplier;
1526
1527                     buffer++;
1528                     src_data+=m_event_size;
1529                 }
1530             }
1531             break;
1532     }
1533
1534     return 0;
1535 }
1536
1537 signed int MotuReceiveStreamProcessor::setEventSize(unsigned int size) {
1538     m_event_size = size;
1539     return 0;
1540 }
1541
1542 unsigned int MotuReceiveStreamProcessor::getEventSize(void) {
1543 //
1544 // Return the size of a single event sent by the MOTU as part of an iso
1545 // data packet in bytes.
1546 //
1547     return m_event_size;
1548 }
1549
1550 void MotuReceiveStreamProcessor::setVerboseLevel(int l) {
1551     setDebugLevel(l);
1552     ReceiveStreamProcessor::setVerboseLevel(l);
1553 }
1554
1555 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.