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

Revision 512, 54.1 kB (checked in by jwoithe, 16 years ago)

MOTU: more tweaks to improve reliability. Things are looking pretty good now.
MOTU: Commenced cleanup of MOTU code, removing temporary debug output etc.

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