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

Revision 435, 46.8 kB (checked in by pieterpalmers, 17 years ago)

src/devicemanager:
- start OSC server for the device manager

src/devicemanager,
src/iavdevice,
src/libieee1394/configrom:
- inherit from OscNode? to become Osc'able

src/bounce,
src/libstreaming/AmdtpStreamProcessor,
src/libstreaming/AmdtpSlaveStreamProcessor:
- fixed bounce device implementation, now working

src/bebob:
- fixed midi bug

General:
- removed 'intermediate XML'
- removed obsolete tests
- removed obsolete files
- removed obsolete API calls

Line 
1 /* $Id$ */
2
3 /*
4  *   FreeBob Streaming API
5  *   FreeBob = Firewire (pro-)audio for linux
6  *
7  *   http://freebob.sf.net
8  *
9  *   Copyright (C) 2005,2006,2007 Pieter Palmers <pieterpalmers@users.sourceforge.net>
10  *
11  *   This program is free software {} you can redistribute it and/or modify
12  *   it under the terms of the GNU General Public License as published by
13  *   the Free Software Foundation {} either version 2 of the License, or
14  *   (at your option) any later version.
15  *
16  *   This program is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY {} without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *   GNU General Public License for more details.
20  *
21  *   You should have received a copy of the GNU General Public License
22  *   along with this program {} if not, write to the Free Software
23  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  *
25  *
26  *
27  */
28 #include "AmdtpStreamProcessor.h"
29 #include "Port.h"
30 #include "AmdtpPort.h"
31
32 #include "cycletimer.h"
33
34 #include <netinet/in.h>
35 #include <assert.h>
36
37 // in ticks
38 #define TRANSMIT_TRANSFER_DELAY 9000U
39 // the number of cycles to send a packet in advance of it's timestamp
40 #define TRANSMIT_ADVANCE_CYCLES 1U
41
42 namespace Streaming {
43
44 IMPL_DEBUG_MODULE( AmdtpTransmitStreamProcessor, AmdtpTransmitStreamProcessor, DEBUG_LEVEL_NORMAL );
45 IMPL_DEBUG_MODULE( AmdtpReceiveStreamProcessor, AmdtpReceiveStreamProcessor, DEBUG_LEVEL_NORMAL );
46
47
48 /* transmit */
49 AmdtpTransmitStreamProcessor::AmdtpTransmitStreamProcessor(int port, int framerate, int dimension)
50         : TransmitStreamProcessor(port, framerate), m_dimension(dimension)
51         , m_last_timestamp(0), m_dbc(0), m_ringbuffer_size_frames(0)
52 {
53
54 }
55
56 AmdtpTransmitStreamProcessor::~AmdtpTransmitStreamProcessor() {
57
58 }
59
60 /**
61  * @return
62  */
63 bool AmdtpTransmitStreamProcessor::init() {
64
65         debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing (%p)...\n");
66         // call the parent init
67         // this has to be done before allocating the buffers,
68         // because this sets the buffersizes from the processormanager
69         if(!TransmitStreamProcessor::init()) {
70                 debugFatal("Could not do base class init (%p)\n",this);
71                 return false;
72         }
73        
74         return true;
75 }
76
77 void AmdtpTransmitStreamProcessor::setVerboseLevel(int l) {
78         setDebugLevel(l);
79         TransmitStreamProcessor::setVerboseLevel(l);
80 }
81
82 enum raw1394_iso_disposition
83 AmdtpTransmitStreamProcessor::getPacket(unsigned char *data, unsigned int *length,
84                       unsigned char *tag, unsigned char *sy,
85                       int cycle, unsigned int dropped, unsigned int max_length) {
86    
87     struct iec61883_packet *packet = (struct iec61883_packet *) data;
88     if (cycle<0) return RAW1394_ISO_OK;
89    
90     m_last_cycle=cycle;
91    
92     debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"Xmit handler for cycle %d, (running=%d, enabled=%d,%d)\n",
93         cycle, m_running, m_disabled, m_is_disabled);
94    
95 #ifdef DEBUG
96     if(dropped>0) {
97         debugWarning("Dropped %d packets on cycle %d\n",dropped, cycle);
98     }
99 #endif
100    
101     // calculate & preset common values
102    
103     /* Our node ID can change after a bus reset, so it is best to fetch
104      * our node ID for each packet. */
105     packet->sid = getNodeId() & 0x3f;
106
107     packet->dbs = m_dimension;
108     packet->fn = 0;
109     packet->qpc = 0;
110     packet->sph = 0;
111     packet->reserved = 0;
112     packet->dbc = m_dbc;
113     packet->eoh1 = 2;
114     packet->fmt = IEC61883_FMT_AMDTP;
115    
116     *tag = IEC61883_TAG_WITH_CIP;
117     *sy = 0;
118    
119     // determine if we want to send a packet or not
120     // note that we can't use getCycleTimer directly here,
121     // because packets are queued in advance. This means that
122     // we the packet we are constructing will be sent out
123     // on 'cycle', not 'now'.
124     unsigned int ctr=m_handler->getCycleTimer();
125     int now_cycles = (int)CYCLE_TIMER_GET_CYCLES(ctr);
126    
127     // the difference between the cycle this
128     // packet is intended for and 'now'
129     int cycle_diff = diffCycles(cycle, now_cycles);
130    
131 #ifdef DEBUG
132     if(m_running && (cycle_diff < 0)) {
133         debugWarning("Requesting packet for cycle %04d which is in the past (now=%04dcy)\n",
134             cycle, now_cycles);
135     }
136 #endif
137
138     // as long as the cycle parameter is not in sync with
139     // the current time, the stream is considered not
140     // to be 'running'
141     // NOTE: this works only at startup
142     if (!m_running && cycle_diff >= 0 && cycle >= 0) {
143             debugOutput(DEBUG_LEVEL_VERBOSE, "Xmit StreamProcessor %p started running at cycle %d\n",this, cycle);
144             m_running=true;
145     }
146    
147     uint64_t ts_head, fc;
148     if (!m_disabled && m_is_disabled) { // this means that we are trying to enable
149         // check if we are on or past the enable point
150         int cycles_past_enable=diffCycles(cycle, m_cycle_to_enable_at);
151        
152         if (cycles_past_enable >= 0) {
153             m_is_disabled=false;
154            
155             debugOutput(DEBUG_LEVEL_VERBOSE,"Enabling StreamProcessor %p at %u\n", this, cycle);
156            
157             // initialize the buffer head & tail
158             m_SyncSource->m_data_buffer->getBufferHeadTimestamp(&ts_head, &fc); // thread safe
159            
160             // the number of cycles the sync source lags (> 0)
161             // or leads (< 0)
162             int sync_lag_cycles=diffCycles(cycle, m_SyncSource->getLastCycle());
163            
164             // account for the cycle lag between sync SP and this SP
165             // the last update of the sync source's timestamps was sync_lag_cycles
166             // cycles before the cycle we are calculating the timestamp for.
167             // if we were to use one-frame buffers, you would expect the
168             // frame that is sent on cycle CT to have a timestamp T1.
169             // ts_head however is for cycle CT-sync_lag_cycles, and lies
170             // therefore sync_lag_cycles * TICKS_PER_CYCLE earlier than
171             // T1.
172             ts_head = addTicks(ts_head, (sync_lag_cycles) * TICKS_PER_CYCLE);
173            
174             ts_head = substractTicks(ts_head, TICKS_PER_CYCLE);
175            
176             // account for the number of cycles we are too late to enable
177             ts_head = addTicks(ts_head, cycles_past_enable * TICKS_PER_CYCLE);
178            
179             // account for one extra packet of frames
180             ts_head = substractTicks(ts_head,
181                         (uint32_t)((float)m_syt_interval * m_SyncSource->m_data_buffer->getRate()));
182
183             m_data_buffer->setBufferHeadTimestamp(ts_head);
184
185             #ifdef DEBUG
186             if ((unsigned int)m_data_buffer->getFrameCounter() != m_data_buffer->getBufferSize()) {
187                 debugWarning("m_data_buffer->getFrameCounter() != m_data_buffer->getBufferSize()\n");
188             }
189             #endif
190             debugOutput(DEBUG_LEVEL_VERBOSE,"XMIT TS SET: TS=%10llu, LAG=%03d, FC=%4d\n",
191                             ts_head, sync_lag_cycles, m_data_buffer->getFrameCounter());
192         } else {
193             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
194                         "will enable StreamProcessor %p at %u, now is %d\n",
195                         this, m_cycle_to_enable_at, cycle);
196         }
197     } else if (m_disabled && !m_is_disabled) {
198         // trying to disable
199         debugOutput(DEBUG_LEVEL_VERBOSE,"disabling StreamProcessor %p at %u\n",
200                     this, cycle);
201         m_is_disabled=true;
202     }
203    
204     // the base timestamp is the one of the next sample in the buffer
205     m_data_buffer->getBufferHeadTimestamp(&ts_head, &fc); // thread safe
206
207     // we send a packet some cycles in advance, to avoid the
208     // following situation:
209     // suppose we are only a few ticks away from
210     // the moment to send this packet. therefore we decide
211     // not to send the packet, but send it in the next cycle.
212     // This means that the next time point will be 3072 ticks
213     // later, making that the timestamp will be expired when the
214     // packet is sent, unless TRANSFER_DELAY > 3072.
215     // this means that we need at least one cycle of extra buffering.
216     uint32_t ticks_to_advance = TICKS_PER_CYCLE * TRANSMIT_ADVANCE_CYCLES;
217    
218     // if cycle lies cycle_diff cycles in the future, we should
219     // queue this packet cycle_diff * TICKS_PER_CYCLE earlier than
220     // we would if it were to be sent immediately.
221     ticks_to_advance += cycle_diff * TICKS_PER_CYCLE;
222
223     // determine the 'now' time in ticks
224     uint32_t cycle_timer=CYCLE_TIMER_TO_TICKS(ctr);
225    
226     cycle_timer = addTicks(cycle_timer, ticks_to_advance);
227    
228     // time until the packet is to be sent (if > 0: send packet)
229     int32_t until_next=diffTicks(ts_head, cycle_timer);
230
231     // if until_next < 0 we should send a filled packet
232     // otherwise we should send a NO-DATA packet
233     if((until_next<0) && (m_running)) {
234         // add the transmit transfer delay to construct the playout time (=SYT timestamp)
235         uint32_t ts_packet=addTicks(ts_head, TRANSMIT_TRANSFER_DELAY);
236    
237         // if we are disabled, send a silent packet
238         // and advance the buffer head timestamp
239         if(m_is_disabled) {
240            
241 //             transmitSilenceBlock((char *)(data+8), m_syt_interval, 0);
242 //             m_dbc += fillDataPacketHeader(packet, length, ts_packet);
243 //             
244 //             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT SYNC: CY=%04u TSH=%011llu TSP=%011lu\n",
245 //                 cycle, ts_head, ts_packet);
246 //
247 //             // update the base timestamp
248 //             uint32_t ts_step=(uint32_t)((float)(m_syt_interval)
249 //                              *m_SyncSource->m_data_buffer->getRate());
250 //             
251 //             // the next buffer head timestamp
252 //             ts_head=addTicks(ts_head,ts_step);
253 //             m_data_buffer->setBufferHeadTimestamp(ts_head);
254 //             
255             // no-data
256             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT SYNC: CY=%04u NONE\n", cycle);
257             m_dbc += fillNoDataPacketHeader(packet, length);
258             // defer to make sure we get to be enabled asap
259             return RAW1394_ISO_DEFER;
260            
261         } else { // enabled & packet due, read from the buffer
262             if (m_data_buffer->readFrames(m_syt_interval, (char *)(data + 8))) {
263                 m_dbc += fillDataPacketHeader(packet, length, ts_packet);
264                
265                 // process all ports that should be handled on a per-packet base
266                 // this is MIDI for AMDTP (due to the need of DBC)
267                 if (!encodePacketPorts((quadlet_t *)(data+8), m_syt_interval, packet->dbc)) {
268                     debugWarning("Problem encoding Packet Ports\n");
269                 }
270                
271                 debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT DATA: CY=%04u TSH=%011llu TSP=%011lu\n",
272                     cycle, ts_head, ts_packet);
273                
274                 return RAW1394_ISO_OK;
275                
276             } else if (now_cycles<cycle) {
277                 // we can still postpone the queueing of the packets
278                 // because the ISO transmit packet buffer is not empty yet
279                 return RAW1394_ISO_AGAIN;
280                
281             } else { // there is no more data in the ringbuffer
282                 // compose a silent packet, we should always
283                 // send a valid packet
284                 transmitSilenceBlock((char *)(data+8), m_syt_interval, 0);
285                 m_dbc += fillDataPacketHeader(packet, length, ts_packet);
286            
287                 debugWarning("Transmit buffer underrun (now %d, queue %d, target %d)\n",
288                         now_cycles, cycle, TICKS_TO_CYCLES(ts_packet));
289                 // signal underrun
290                 m_xruns++;
291                 // disable the processing, will be re-enabled when
292                 // the xrun is handled
293                 m_disabled=true;
294                 m_is_disabled=true;
295                
296                 return RAW1394_ISO_DEFER;
297             }
298         }
299        
300     } else { // no packet due, send no-data packet
301         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT NONE: CY=%04u TSH=%011llu\n",
302                 cycle, ts_head);
303                
304         m_dbc += fillNoDataPacketHeader(packet, length);
305         return RAW1394_ISO_DEFER;
306     }
307    
308     // we shouldn't get here
309     return RAW1394_ISO_ERROR;
310
311 }
312
313 unsigned int AmdtpTransmitStreamProcessor::fillDataPacketHeader(
314         struct iec61883_packet *packet, unsigned int* length,
315         uint32_t ts) {
316    
317     packet->fdf = m_fdf;
318
319     // convert the timestamp to SYT format
320     uint16_t timestamp_SYT = TICKS_TO_SYT(ts);
321     packet->syt = ntohs(timestamp_SYT);
322    
323     *length = m_syt_interval*sizeof(quadlet_t)*m_dimension + 8;
324
325     return m_syt_interval;
326 }
327
328 unsigned int AmdtpTransmitStreamProcessor::fillNoDataPacketHeader(
329         struct iec61883_packet *packet, unsigned int* length) {
330    
331     // no-data packets have syt=0xFFFF
332     // and have the usual amount of events as dummy data (?)
333     packet->fdf = IEC61883_FDF_NODATA;
334     packet->syt = 0xffff;
335    
336     // FIXME: either make this a setting or choose
337     bool send_payload=true;
338     if(send_payload) {
339         // this means no-data packets with payload (DICE doesn't like that)
340         *length = 2*sizeof(quadlet_t) + m_syt_interval * m_dimension * sizeof(quadlet_t);
341         return m_syt_interval;
342     } else {
343         // dbc is not incremented
344         // this means no-data packets without payload
345         *length = 2*sizeof(quadlet_t);
346         return 0;
347     }
348 }
349
350 int AmdtpTransmitStreamProcessor::getMinimalSyncDelay() {
351     return 0;
352 }
353
354 bool AmdtpTransmitStreamProcessor::prefill() {
355
356     debugOutput( DEBUG_LEVEL_VERBOSE, "Prefill transmit buffers...\n");
357    
358     if(!transferSilence(m_ringbuffer_size_frames)) {
359         debugFatal("Could not prefill transmit stream\n");
360         return false;
361     }
362
363     return true;
364 }
365
366 bool AmdtpTransmitStreamProcessor::reset() {
367
368     debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
369
370     // reset the statistics
371     m_PeriodStat.reset();
372     m_PacketStat.reset();
373     m_WakeupStat.reset();
374    
375     // we have to make sure that the buffer HEAD timestamp
376     // lies in the future for every possible buffer fill case.
377     int offset=(int)(m_ringbuffer_size_frames*m_ticks_per_frame);
378    
379     m_data_buffer->setTickOffset(offset);
380    
381     // reset all non-device specific stuff
382     // i.e. the iso stream and the associated ports
383     if(!TransmitStreamProcessor::reset()) {
384         debugFatal("Could not do base class reset\n");
385         return false;
386     }
387    
388     // we should prefill the event buffer
389     if (!prefill()) {
390         debugFatal("Could not prefill buffers\n");
391         return false;   
392     }
393    
394     return true;
395 }
396
397 bool AmdtpTransmitStreamProcessor::prepare() {
398     m_PeriodStat.setName("XMT PERIOD");
399     m_PacketStat.setName("XMT PACKET");
400     m_WakeupStat.setName("XMT WAKEUP");
401
402     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this);
403    
404     // prepare all non-device specific stuff
405     // i.e. the iso stream and the associated ports
406     if(!TransmitStreamProcessor::prepare()) {
407         debugFatal("Could not prepare base class\n");
408         return false;
409     }
410    
411     switch (m_framerate) {
412     case 32000:
413         m_syt_interval = 8;
414         m_fdf = IEC61883_FDF_SFC_32KHZ;
415         break;
416     case 44100:
417         m_syt_interval = 8;
418         m_fdf = IEC61883_FDF_SFC_44K1HZ;
419         break;
420     default:
421     case 48000:
422         m_syt_interval = 8;
423         m_fdf = IEC61883_FDF_SFC_48KHZ;
424         break;
425     case 88200:
426         m_syt_interval = 16;
427         m_fdf = IEC61883_FDF_SFC_88K2HZ;
428         break;
429     case 96000:
430         m_syt_interval = 16;
431         m_fdf = IEC61883_FDF_SFC_96KHZ;
432         break;
433     case 176400:
434         m_syt_interval = 32;
435         m_fdf = IEC61883_FDF_SFC_176K4HZ;
436         break;
437     case 192000:
438         m_syt_interval = 32;
439         m_fdf = IEC61883_FDF_SFC_192KHZ;
440         break;
441     }
442    
443     iec61883_cip_init (
444         &m_cip_status,
445         IEC61883_FMT_AMDTP,
446         m_fdf,
447         m_framerate,
448         m_dimension,
449         m_syt_interval);
450
451     // prepare the framerate estimate
452     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
453    
454         // initialize internal buffer
455     m_ringbuffer_size_frames=m_nb_buffers * m_period;
456
457     assert(m_data_buffer);   
458     m_data_buffer->setBufferSize(m_ringbuffer_size_frames);
459     m_data_buffer->setEventSize(sizeof(quadlet_t));
460     m_data_buffer->setEventsPerFrame(m_dimension);
461    
462     m_data_buffer->setUpdatePeriod(m_period);
463     m_data_buffer->setNominalRate(m_ticks_per_frame);
464    
465     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
466    
467     m_data_buffer->prepare();
468
469     // set the parameters of ports we can:
470     // we want the audio ports to be period buffered,
471     // and the midi ports to be packet buffered
472     for ( PortVectorIterator it = m_Ports.begin();
473           it != m_Ports.end();
474           ++it )
475     {
476         debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
477         if(!(*it)->setBufferSize(m_period)) {
478             debugFatal("Could not set buffer size to %d\n",m_period);
479             return false;
480         }
481        
482        
483         switch ((*it)->getPortType()) {
484             case Port::E_Audio:
485                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
486                     debugFatal("Could not set signal type to PeriodSignalling");
487                     return false;
488                 }
489                 debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
490                 // buffertype and datatype are dependant on the API
491                 if(!(*it)->setBufferType(Port::E_PointerBuffer)) {
492                     debugFatal("Could not set buffer type");
493                     return false;
494                 }
495                 if(!(*it)->useExternalBuffer(true)) {
496                     debugFatal("Could not set external buffer usage");
497                     return false;
498                 }
499                
500                 if(!(*it)->setDataType(Port::E_Float)) {
501                     debugFatal("Could not set data type");
502                     return false;
503                 }
504                
505                
506                 break;
507             case Port::E_Midi:
508                 if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
509                     debugFatal("Could not set signal type to PeriodSignalling");
510                     return false;
511                 }
512                
513                 // we use a timing unit of 10ns
514                 // this makes sure that for the max syt interval
515                 // we don't have rounding, and keeps the numbers low
516                 // we have 1 slot every 8 events
517                 // we have syt_interval events per packet
518                 // => syt_interval/8 slots per packet
519                 // packet rate is 8000pkt/sec => interval=125us
520                 // so the slot interval is (1/8000)/(syt_interval/8)
521                 // or: 1/(1000 * syt_interval) sec
522                 // which is 1e9/(1000*syt_interval) nsec
523                 // or 100000/syt_interval 'units'
524                 // the event interval is fixed to 320us = 32000 'units'
525                 if(!(*it)->useRateControl(true,(100000/m_syt_interval),32000, false)) {
526                     debugFatal("Could not set signal type to PeriodSignalling");
527                     return false;
528                 }
529                
530                 // buffertype and datatype are dependant on the API
531                 debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
532                 // buffertype and datatype are dependant on the API
533                 if(!(*it)->setBufferType(Port::E_RingBuffer)) {
534                     debugFatal("Could not set buffer type");
535                     return false;
536                 }
537                 if(!(*it)->setDataType(Port::E_MidiEvent)) {
538                     debugFatal("Could not set data type");
539                     return false;
540                 }
541                 break;
542             default:
543                 debugWarning("Unsupported port type specified\n");
544                 break;
545         }
546     }
547
548     // the API specific settings of the ports should already be set,
549     // as this is called from the processorManager->prepare()
550     // so we can init the ports
551     if(!initPorts()) {
552         debugFatal("Could not initialize ports!\n");
553         return false;
554     }
555
556     if(!preparePorts()) {
557         debugFatal("Could not initialize ports!\n");
558         return false;
559     }
560
561     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepared for:\n");
562     debugOutput( DEBUG_LEVEL_VERBOSE, " Samplerate: %d, FDF: %d, DBS: %d, SYT: %d\n",
563              m_framerate,m_fdf,m_dimension,m_syt_interval);
564     debugOutput( DEBUG_LEVEL_VERBOSE, " PeriodSize: %d, NbBuffers: %d\n",
565              m_period,m_nb_buffers);
566     debugOutput( DEBUG_LEVEL_VERBOSE, " Port: %d, Channel: %d\n",
567              m_port,m_channel);
568
569     return true;
570
571 }
572
573 bool AmdtpTransmitStreamProcessor::prepareForStart() {
574
575     return true;
576 }
577
578 bool AmdtpTransmitStreamProcessor::prepareForStop() {
579     disable();
580     return true;
581 }
582
583 bool AmdtpTransmitStreamProcessor::prepareForEnable(uint64_t time_to_enable_at) {
584
585     debugOutput(DEBUG_LEVEL_VERBOSE,"Preparing to enable...\n");
586
587     // for the transmit SP, we have to initialize the
588     // buffer timestamp to something sane, because this timestamp
589     // is used when it is SyncSource
590    
591     // the time we initialize to will determine the time at which
592     // the first sample in the buffer will be sent, so we should
593     // make it at least 'time_to_enable_at'
594    
595     uint64_t now=m_handler->getCycleTimer();
596     unsigned int now_secs=CYCLE_TIMER_GET_SECS(now);
597    
598     // check if a wraparound on the secs will happen between
599     // now and the time we start
600     int until_enable=(int)time_to_enable_at - (int)CYCLE_TIMER_GET_CYCLES(now);
601    
602     if(until_enable>4000) {
603         // wraparound on CYCLE_TIMER_GET_CYCLES(now)
604         // this means that we are late starting up,
605         // and that the start lies in the previous second
606         if (now_secs==0) now_secs=127;
607         else now_secs--;
608     } else if (until_enable<-4000) {
609         // wraparound on time_to_enable_at
610         // this means that we are early and that the start
611         // point lies in the next second
612         now_secs++;
613         if (now_secs>=128) now_secs=0;
614     }
615
616     uint64_t ts_head= now_secs*TICKS_PER_SECOND;
617     ts_head+=time_to_enable_at*TICKS_PER_CYCLE;
618    
619     // we also add the nb of cycles we transmit in advance
620     ts_head=addTicks(ts_head, TRANSMIT_ADVANCE_CYCLES*TICKS_PER_CYCLE);
621    
622     m_data_buffer->setBufferTailTimestamp(ts_head);
623
624
625     if (!StreamProcessor::prepareForEnable(time_to_enable_at)) {
626         debugError("StreamProcessor::prepareForEnable failed\n");
627         return false;
628     }
629
630     return true;
631 }
632
633 bool AmdtpTransmitStreamProcessor::transferSilence(unsigned int nframes) {
634     bool retval;
635    
636     char *dummybuffer=(char *)calloc(sizeof(quadlet_t),nframes*m_dimension);
637    
638     transmitSilenceBlock(dummybuffer, nframes, 0);
639
640     // add the silence data to the ringbuffer
641     if(m_data_buffer->writeFrames(nframes, dummybuffer, 0)) {
642         retval=true;
643     } else {
644         debugWarning("Could not write to event buffer\n");
645         retval=false;
646     }
647
648     free(dummybuffer);
649    
650     return retval;
651 }
652
653 bool AmdtpTransmitStreamProcessor::putFrames(unsigned int nbframes, int64_t ts) {
654     m_PeriodStat.mark(m_data_buffer->getBufferFill());
655    
656     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "AmdtpTransmitStreamProcessor::putFrames(%d, %llu)\n", nbframes, ts);
657    
658     // transfer the data
659     m_data_buffer->blockProcessWriteFrames(nbframes, ts);
660
661     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " New timestamp: %llu\n", ts);
662
663     return true;
664 }
665 /*
666  * write received events to the stream ringbuffers.
667  */
668
669 bool AmdtpTransmitStreamProcessor::processWriteBlock(char *data,
670                        unsigned int nevents, unsigned int offset)
671 {
672     bool no_problem=true;
673
674     for ( PortVectorIterator it = m_PeriodPorts.begin();
675           it != m_PeriodPorts.end();
676           ++it )
677     {
678
679         if((*it)->isDisabled()) {continue;};
680        
681         //FIXME: make this into a static_cast when not DEBUG?
682
683         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
684         assert(pinfo); // this should not fail!!
685
686         switch(pinfo->getFormat()) {
687         case AmdtpPortInfo::E_MBLA:
688             if(encodePortToMBLAEvents(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
689                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
690                 no_problem=false;
691             }
692             break;
693         case AmdtpPortInfo::E_SPDIF: // still unimplemented
694             break;
695         default: // ignore
696             break;
697         }
698     }
699     return no_problem;
700
701 }
702
703 int AmdtpTransmitStreamProcessor::transmitSilenceBlock(char *data,
704                        unsigned int nevents, unsigned int offset)
705 {
706     int problem=0;
707
708     for ( PortVectorIterator it = m_PeriodPorts.begin();
709           it != m_PeriodPorts.end();
710           ++it )
711     {
712
713         //FIXME: make this into a static_cast when not DEBUG?
714
715         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
716         assert(pinfo); // this should not fail!!
717
718         switch(pinfo->getFormat()) {
719         case AmdtpPortInfo::E_MBLA:
720             if(encodeSilencePortToMBLAEvents(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
721                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
722                 problem=1;
723             }
724             break;
725         case AmdtpPortInfo::E_SPDIF: // still unimplemented
726             break;
727         default: // ignore
728             break;
729         }
730     }
731     return problem;
732
733 }
734
735 /**
736  * @brief decode a packet for the packet-based ports
737  *
738  * @param data Packet data
739  * @param nevents number of events in data (including events of other ports & port types)
740  * @param dbc DataBlockCount value for this packet
741  * @return true if all successfull
742  */
743 bool AmdtpTransmitStreamProcessor::encodePacketPorts(quadlet_t *data, unsigned int nevents, unsigned int dbc)
744 {
745     bool ok=true;
746     char byte;
747    
748     quadlet_t *target_event=NULL;
749     unsigned int j;
750    
751     for ( PortVectorIterator it = m_PacketPorts.begin();
752           it != m_PacketPorts.end();
753           ++it )
754     {
755
756 #ifdef DEBUG
757         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
758         assert(pinfo); // this should not fail!!
759
760         // the only packet type of events for AMDTP is MIDI in mbla
761         assert(pinfo->getFormat()==AmdtpPortInfo::E_Midi);
762 #endif
763        
764         AmdtpMidiPort *mp=static_cast<AmdtpMidiPort *>(*it);
765        
766         // we encode this directly (no function call) due to the high frequency
767         /* idea:
768         spec says: current_midi_port=(dbc+j)%8;
769         => if we start at (dbc+stream->location-1)%8,
770         we'll start at the right event for the midi port.
771         => if we increment j with 8, we stay at the right event.
772         */
773         // FIXME: as we know in advance how big a packet is (syt_interval) we can
774         //        predict how much loops will be present here
775         // first prefill the buffer with NO_DATA's on all time muxed channels
776        
777         for(j = (dbc & 0x07)+mp->getLocation(); j < nevents; j += 8) {
778        
779             target_event=(quadlet_t *)(data + ((j * m_dimension) + mp->getPosition()));
780            
781             if(mp->canRead()) { // we can send a byte
782                 mp->readEvent(&byte);
783                 *target_event=htonl(
784                     IEC61883_AM824_SET_LABEL((byte)<<16,
785                                              IEC61883_AM824_LABEL_MIDI_1X));
786             } else {
787                 // can't send a byte, either because there is no byte,
788                 // or because this would exceed the maximum rate
789                 *target_event=htonl(
790                     IEC61883_AM824_SET_LABEL(0,IEC61883_AM824_LABEL_MIDI_NO_DATA));
791             }
792         }
793
794     }
795        
796     return ok;
797 }
798
799
800 int AmdtpTransmitStreamProcessor::encodePortToMBLAEvents(AmdtpAudioPort *p, quadlet_t *data,
801                        unsigned int offset, unsigned int nevents)
802 {
803     unsigned int j=0;
804
805     quadlet_t *target_event;
806
807     target_event=(quadlet_t *)(data + p->getPosition());
808
809     switch(p->getDataType()) {
810         default:
811         case Port::E_Int24:
812             {
813                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
814
815                 assert(nevents + offset <= p->getBufferSize());
816
817                 buffer+=offset;
818
819                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
820                     *target_event = htonl((*(buffer) & 0x00FFFFFF) | 0x40000000);
821                     buffer++;
822                     target_event += m_dimension;
823                 }
824             }
825             break;
826         case Port::E_Float:
827             {
828                 const float multiplier = (float)(0x7FFFFF00);
829                 float *buffer=(float *)(p->getBufferAddress());
830
831                 assert(nevents + offset <= p->getBufferSize());
832
833                 buffer+=offset;
834
835                 for(j = 0; j < nevents; j += 1) { // decode max nsamples               
836    
837                     // don't care for overflow
838                     float v = *buffer * multiplier;  // v: -231 .. 231
839                     unsigned int tmp = ((int)v);
840                     *target_event = htonl((tmp >> 8) | 0x40000000);
841                    
842                     buffer++;
843                     target_event += m_dimension;
844                 }
845             }
846             break;
847     }
848
849     return 0;
850 }
851 int AmdtpTransmitStreamProcessor::encodeSilencePortToMBLAEvents(AmdtpAudioPort *p, quadlet_t *data,
852                        unsigned int offset, unsigned int nevents)
853 {
854     unsigned int j=0;
855
856     quadlet_t *target_event;
857
858     target_event=(quadlet_t *)(data + p->getPosition());
859
860     switch(p->getDataType()) {
861         default:
862         case Port::E_Int24:
863         case Port::E_Float:
864             {
865                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
866                     *target_event = htonl(0x40000000);
867                     target_event += m_dimension;
868                 }
869             }
870             break;
871     }
872
873     return 0;
874 }
875
876 /* --------------------- RECEIVE ----------------------- */
877
878 AmdtpReceiveStreamProcessor::AmdtpReceiveStreamProcessor(int port, int framerate, int dimension)
879     : ReceiveStreamProcessor(port, framerate), m_dimension(dimension), m_last_timestamp(0), m_last_timestamp2(0) {
880
881 }
882
883 AmdtpReceiveStreamProcessor::~AmdtpReceiveStreamProcessor() {
884
885 }
886
887 bool AmdtpReceiveStreamProcessor::init() {
888
889     // call the parent init
890     // this has to be done before allocating the buffers,
891     // because this sets the buffersizes from the processormanager
892     if(!ReceiveStreamProcessor::init()) {
893         debugFatal("Could not do base class init (%d)\n",this);
894         return false;
895     }
896
897     return true;
898 }
899
900 enum raw1394_iso_disposition
901 AmdtpReceiveStreamProcessor::putPacket(unsigned char *data, unsigned int length,
902                   unsigned char channel, unsigned char tag, unsigned char sy,
903                   unsigned int cycle, unsigned int dropped) {
904    
905     enum raw1394_iso_disposition retval=RAW1394_ISO_OK;
906     m_last_cycle=cycle;
907    
908     struct iec61883_packet *packet = (struct iec61883_packet *) data;
909     assert(packet);
910
911 #ifdef DEBUG
912     if(dropped>0) {
913         debugWarning("Dropped %d packets on cycle %d\n",dropped, cycle);
914     }
915
916     debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"ch%2u: CY=%4u, SYT=%08X (%4ucy + %04uticks) (running=%d, disabled=%d,%d)\n",
917         channel, cycle,ntohs(packet->syt), 
918         CYCLE_TIMER_GET_CYCLES(ntohs(packet->syt)), CYCLE_TIMER_GET_OFFSET(ntohs(packet->syt)),
919         m_running,m_disabled,m_is_disabled);
920
921     debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
922         "RCV: CH = %d, FDF = %X. SYT = %6d, DBS = %3d, DBC = %3d, FMT = %3d, LEN = %4d\n",
923         channel, packet->fdf,
924         packet->syt,
925         packet->dbs,
926         packet->dbc,
927         packet->fmt,
928         length);
929
930 #endif
931     if (!m_disabled && m_is_disabled) { // this means that we are trying to enable
932         // check if we are on or past the enable point
933         int cycles_past_enable=diffCycles(cycle, m_cycle_to_enable_at);
934        
935         if (cycles_past_enable >= 0) {
936             m_is_disabled=false;
937             debugOutput(DEBUG_LEVEL_VERBOSE,"Enabling StreamProcessor %p at %d (SYT=%04X)\n",
938                 this, cycle, ntohs(packet->syt));
939             // the previous timestamp is the one we need to start with
940             // because we're going to update the buffer again this loop
941             // using writeframes
942             m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
943
944         } else {
945             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
946                 "will enable StreamProcessor %p at %u, now is %d\n",
947                     this, m_cycle_to_enable_at, cycle);
948         }
949     } else if (m_disabled && !m_is_disabled) {
950         // trying to disable
951         debugOutput(DEBUG_LEVEL_VERBOSE,"disabling StreamProcessor %p at %u\n", this, cycle);
952         m_is_disabled=true;
953     }
954
955     // check if this is a valid packet
956     if((packet->syt != 0xFFFF)
957        && (packet->fdf != 0xFF)
958        && (packet->fmt == 0x10)
959        && (packet->dbs>0)
960        && (length>=2*sizeof(quadlet_t))) {
961        
962         unsigned int nevents=((length / sizeof (quadlet_t)) - 2)/packet->dbs;
963
964         //=> store the previous timestamp
965         m_last_timestamp2=m_last_timestamp;
966
967         //=> convert the SYT to a full timestamp in ticks
968         m_last_timestamp=sytRecvToFullTicks((uint32_t)ntohs(packet->syt),
969                                         cycle, m_handler->getCycleTimer());
970
971         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "RECV: CY=%04u TS=%011llu\n",
972                 cycle, m_last_timestamp);
973        
974         // we have to keep in mind that there are also
975         // some packets buffered by the ISO layer,
976         // at most x=m_handler->getWakeupInterval()
977         // these contain at most x*syt_interval
978         // frames, meaning that we might receive
979         // this packet x*syt_interval*ticks_per_frame
980         // later than expected (the real receive time)
981         debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"STMP: %lluticks | buff=%d, syt_interval=%d, tpf=%f\n",
982             m_last_timestamp, m_handler->getWakeupInterval(),m_syt_interval,m_ticks_per_frame);
983        
984         //=> signal that we're running (if we are)
985         if(!m_running && nevents && m_last_timestamp2 && m_last_timestamp) {
986             debugOutput(DEBUG_LEVEL_VERBOSE,"Receive StreamProcessor %p started running at %d\n", this, cycle);
987             m_running=true;
988         }
989
990         //=> don't process the stream samples when it is not enabled.
991         if(m_is_disabled) {
992
993             // we keep track of the timestamp here
994             // this makes sure that we will have a somewhat accurate
995             // estimate as to when a period might be ready. i.e. it will not
996             // be ready earlier than this timestamp + period time
997            
998             // the next (possible) sample is not this one, but lies
999             // SYT_INTERVAL * rate later
1000             uint64_t ts=addTicks(m_last_timestamp,
1001                                  (uint64_t)((float)m_syt_interval * m_ticks_per_frame));
1002
1003             // set the timestamp as if there will be a sample put into
1004             // the buffer by the next packet.
1005             m_data_buffer->setBufferTailTimestamp(ts);
1006            
1007             return RAW1394_ISO_DEFER;
1008         }
1009        
1010         #ifdef DEBUG_OFF
1011         if((cycle % 1000) == 0) {
1012             uint32_t syt = (uint32_t)ntohs(packet->syt);
1013             uint32_t now=m_handler->getCycleTimer();
1014             uint32_t now_ticks=CYCLE_TIMER_TO_TICKS(now);
1015            
1016             uint32_t test_ts=sytRecvToFullTicks(syt, cycle, now);
1017
1018             debugOutput(DEBUG_LEVEL_VERBOSE, "R %04d: SYT=%08X,            CY=%02d OFF=%04d\n",
1019                 cycle, syt, CYCLE_TIMER_GET_CYCLES(syt), CYCLE_TIMER_GET_OFFSET(syt)
1020                 );
1021             debugOutput(DEBUG_LEVEL_VERBOSE, "R %04d: NOW=%011lu, SEC=%03u CY=%02u OFF=%04u\n",
1022                 cycle, now_ticks, CYCLE_TIMER_GET_SECS(now), CYCLE_TIMER_GET_CYCLES(now), CYCLE_TIMER_GET_OFFSET(now)
1023                 );
1024             debugOutput(DEBUG_LEVEL_VERBOSE, "R %04d: TSS=%011lu, SEC=%03u CY=%02u OFF=%04u\n",
1025                 cycle, test_ts, TICKS_TO_SECS(test_ts), TICKS_TO_CYCLES(test_ts), TICKS_TO_OFFSET(test_ts)
1026                 );
1027         }
1028         #endif
1029        
1030         //=> process the packet
1031         // add the data payload to the ringbuffer
1032         if(m_data_buffer->writeFrames(nevents, (char *)(data+8), m_last_timestamp)) {
1033             retval=RAW1394_ISO_OK;
1034            
1035             // process all ports that should be handled on a per-packet base
1036             // this is MIDI for AMDTP (due to the need of DBC)
1037             if (!decodePacketPorts((quadlet_t *)(data+8), nevents, packet->dbc)) {
1038                 debugWarning("Problem decoding Packet Ports\n");
1039                 retval=RAW1394_ISO_DEFER;
1040             }
1041            
1042         } else {
1043        
1044             debugWarning("Receive buffer overrun (cycle %d, FC=%d, PC=%d)\n",
1045                  cycle, m_data_buffer->getFrameCounter(), m_handler->getPacketCount());
1046            
1047             m_xruns++;
1048            
1049             // disable the processing, will be re-enabled when
1050             // the xrun is handled
1051             m_disabled=true;
1052             m_is_disabled=true;
1053
1054             retval=RAW1394_ISO_DEFER;
1055         }
1056     }
1057
1058     return retval;
1059 }
1060
1061 // returns the delay between the actual (real) time of a timestamp as received,
1062 // and the timestamp that is passed on for the same event. This is to cope with
1063 // ISO buffering
1064 int AmdtpReceiveStreamProcessor::getMinimalSyncDelay() {
1065     return ((int)(m_handler->getWakeupInterval() * m_syt_interval * m_ticks_per_frame));
1066 }
1067
1068 void AmdtpReceiveStreamProcessor::dumpInfo() {
1069     StreamProcessor::dumpInfo();
1070 }
1071
1072 void AmdtpReceiveStreamProcessor::setVerboseLevel(int l) {
1073         setDebugLevel(l);
1074         ReceiveStreamProcessor::setVerboseLevel(l);
1075 }
1076
1077 bool AmdtpReceiveStreamProcessor::reset() {
1078
1079     debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
1080
1081     m_PeriodStat.reset();
1082     m_PacketStat.reset();
1083     m_WakeupStat.reset();
1084
1085     m_data_buffer->setTickOffset(0);
1086
1087     // reset all non-device specific stuff
1088     // i.e. the iso stream and the associated ports
1089     if(!ReceiveStreamProcessor::reset()) {
1090             debugFatal("Could not do base class reset\n");
1091             return false;
1092     }
1093     return true;
1094 }
1095
1096 bool AmdtpReceiveStreamProcessor::prepare() {
1097
1098     m_PeriodStat.setName("RCV PERIOD");
1099     m_PacketStat.setName("RCV PACKET");
1100     m_WakeupStat.setName("RCV WAKEUP");
1101
1102     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this);
1103        
1104         // prepare all non-device specific stuff
1105         // i.e. the iso stream and the associated ports
1106         if(!ReceiveStreamProcessor::prepare()) {
1107                 debugFatal("Could not prepare base class\n");
1108                 return false;
1109         }
1110        
1111         switch (m_framerate) {
1112         case 32000:
1113                 m_syt_interval = 8;
1114                 break;
1115         case 44100:
1116                 m_syt_interval = 8;
1117                 break;
1118         default:
1119         case 48000:
1120                 m_syt_interval = 8;
1121                 break;
1122         case 88200:
1123                 m_syt_interval = 16;
1124                 break;
1125         case 96000:
1126                 m_syt_interval = 16;
1127                 break;
1128         case 176400:
1129                 m_syt_interval = 32;
1130                 break;
1131         case 192000:
1132                 m_syt_interval = 32;
1133                 break;
1134         }
1135
1136     // prepare the framerate estimate
1137     m_ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_framerate);
1138
1139     debugOutput(DEBUG_LEVEL_VERBOSE,"Initializing remote ticks/frame to %f\n",m_ticks_per_frame);
1140
1141         // initialize internal buffer
1142     unsigned int ringbuffer_size_frames=m_nb_buffers * m_period;
1143    
1144     assert(m_data_buffer);   
1145     m_data_buffer->setBufferSize(ringbuffer_size_frames);
1146     m_data_buffer->setEventSize(sizeof(quadlet_t));
1147     m_data_buffer->setEventsPerFrame(m_dimension);
1148        
1149     // the buffer is written every syt_interval
1150     m_data_buffer->setUpdatePeriod(m_syt_interval);
1151     m_data_buffer->setNominalRate(m_ticks_per_frame);
1152    
1153     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
1154    
1155     m_data_buffer->prepare();
1156
1157         // set the parameters of ports we can:
1158         // we want the audio ports to be period buffered,
1159         // and the midi ports to be packet buffered
1160         for ( PortVectorIterator it = m_Ports.begin();
1161                   it != m_Ports.end();
1162                   ++it )
1163         {
1164                 debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
1165                 if(!(*it)->setBufferSize(m_period)) {
1166                         debugFatal("Could not set buffer size to %d\n",m_period);
1167                         return false;
1168                 }
1169
1170                 switch ((*it)->getPortType()) {
1171                         case Port::E_Audio:
1172                                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1173                                         debugFatal("Could not set signal type to PeriodSignalling");
1174                                         return false;
1175                                 }
1176                                 // buffertype and datatype are dependant on the API
1177                                 debugWarning("---------------- ! Doing hardcoded dummy setup ! --------------\n");
1178                                 // buffertype and datatype are dependant on the API
1179                                 if(!(*it)->setBufferType(Port::E_PointerBuffer)) {
1180                                         debugFatal("Could not set buffer type");
1181                                         return false;
1182                                 }
1183                                 if(!(*it)->useExternalBuffer(true)) {
1184                                         debugFatal("Could not set external buffer usage");
1185                                         return false;
1186                                 }
1187                                 if(!(*it)->setDataType(Port::E_Float)) {
1188                                         debugFatal("Could not set data type");
1189                                         return false;
1190                                 }
1191                                 break;
1192                         case Port::E_Midi:
1193                                 if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
1194                                         debugFatal("Could not set signal type to PacketSignalling");
1195                                         return false;
1196                                 }
1197                                 // buffertype and datatype are dependant on the API
1198                                 // buffertype and datatype are dependant on the API
1199                                 debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
1200                                 // buffertype and datatype are dependant on the API
1201                                 if(!(*it)->setBufferType(Port::E_RingBuffer)) {
1202                                         debugFatal("Could not set buffer type");
1203                                         return false;
1204                                 }
1205                                 if(!(*it)->setDataType(Port::E_MidiEvent)) {
1206                                         debugFatal("Could not set data type");
1207                                         return false;
1208                                 }
1209                                 break;
1210                         default:
1211                                 debugWarning("Unsupported port type specified\n");
1212                                 break;
1213                 }
1214         }
1215
1216         // the API specific settings of the ports should already be set,
1217         // as this is called from the processorManager->prepare()
1218         // so we can init the ports
1219         if(!initPorts()) {
1220                 debugFatal("Could not initialize ports!\n");
1221                 return false;
1222         }
1223
1224         if(!preparePorts()) {
1225                 debugFatal("Could not initialize ports!\n");
1226                 return false;
1227         }
1228
1229     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepared for:\n");
1230     debugOutput( DEBUG_LEVEL_VERBOSE, " Samplerate: %d, DBS: %d, SYT: %d\n",
1231              m_framerate,m_dimension,m_syt_interval);
1232     debugOutput( DEBUG_LEVEL_VERBOSE, " PeriodSize: %d, NbBuffers: %d\n",
1233              m_period,m_nb_buffers);
1234     debugOutput( DEBUG_LEVEL_VERBOSE, " Port: %d, Channel: %d\n",
1235              m_port,m_channel);
1236    
1237     return true;
1238
1239 }
1240
1241 bool AmdtpReceiveStreamProcessor::prepareForStart() {
1242     disable();
1243     return true;
1244 }
1245
1246 bool AmdtpReceiveStreamProcessor::prepareForStop() {
1247     disable();
1248     return true;
1249 }
1250
1251 bool AmdtpReceiveStreamProcessor::getFrames(unsigned int nbframes) {
1252
1253     m_PeriodStat.mark(m_data_buffer->getBufferFill());
1254
1255     // ask the buffer to process nbframes of frames
1256     // using it's registered client's processReadBlock(),
1257     // which should be ours
1258     m_data_buffer->blockProcessReadFrames(nbframes);
1259
1260     return true;
1261 }
1262
1263 /**
1264  * \brief write received events to the stream ringbuffers.
1265  */
1266 bool AmdtpReceiveStreamProcessor::processReadBlock(char *data,
1267                                            unsigned int nevents, unsigned int offset)
1268 {
1269         debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "(%p)->processReadBlock(%u, %u)\n",this,nevents,offset);
1270        
1271         bool no_problem=true;
1272
1273         for ( PortVectorIterator it = m_PeriodPorts.begin();
1274           it != m_PeriodPorts.end();
1275           ++it )
1276     {
1277
1278         if((*it)->isDisabled()) {continue;};
1279
1280                 //FIXME: make this into a static_cast when not DEBUG?
1281
1282                 AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
1283                 assert(pinfo); // this should not fail!!
1284
1285                 switch(pinfo->getFormat()) {
1286                 case AmdtpPortInfo::E_MBLA:
1287                         if(decodeMBLAEventsToPort(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
1288                                 debugWarning("Could not decode packet MBLA to port %s",(*it)->getName().c_str());
1289                                 no_problem=false;
1290                         }
1291                         break;
1292                 case AmdtpPortInfo::E_SPDIF: // still unimplemented
1293                         break;
1294         /* for this processor, midi is a packet based port
1295                 case AmdtpPortInfo::E_Midi:
1296                         break;*/
1297                 default: // ignore
1298                         break;
1299                 }
1300     }
1301     return no_problem;
1302
1303 }
1304
1305 /**
1306  * @brief decode a packet for the packet-based ports
1307  *
1308  * @param data Packet data
1309  * @param nevents number of events in data (including events of other ports & port types)
1310  * @param dbc DataBlockCount value for this packet
1311  * @return true if all successfull
1312  */
1313 bool AmdtpReceiveStreamProcessor::decodePacketPorts(quadlet_t *data, unsigned int nevents, unsigned int dbc)
1314 {
1315         bool ok=true;
1316        
1317         quadlet_t *target_event=NULL;
1318         unsigned int j;
1319        
1320         for ( PortVectorIterator it = m_PacketPorts.begin();
1321           it != m_PacketPorts.end();
1322           ++it )
1323         {
1324
1325 #ifdef DEBUG
1326                 AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
1327                 assert(pinfo); // this should not fail!!
1328
1329                 // the only packet type of events for AMDTP is MIDI in mbla
1330                 assert(pinfo->getFormat()==AmdtpPortInfo::E_Midi);
1331 #endif
1332                 AmdtpMidiPort *mp=static_cast<AmdtpMidiPort *>(*it);
1333                
1334                 // we decode this directly (no function call) due to the high frequency
1335                 /* idea:
1336                 spec says: current_midi_port=(dbc+j)%8;
1337                 => if we start at (dbc+stream->location-1)%8,
1338                 we'll start at the right event for the midi port.
1339                 => if we increment j with 8, we stay at the right event.
1340                 */
1341                 // FIXME: as we know in advance how big a packet is (syt_interval) we can
1342                 //        predict how much loops will be present here
1343                 for(j = (dbc & 0x07)+mp->getLocation(); j < nevents; j += 8) {
1344                         target_event=(quadlet_t *)(data + ((j * m_dimension) + mp->getPosition()));
1345                         quadlet_t sample_int=ntohl(*target_event);
1346                         // FIXME: this assumes that 2X and 3X speed isn't used,
1347                         // because only the 1X slot is put into the ringbuffer
1348                         if(IEC61883_AM824_GET_LABEL(sample_int) != IEC61883_AM824_LABEL_MIDI_NO_DATA) {
1349                                 sample_int=(sample_int >> 16) & 0x000000FF;
1350                                 if(!mp->writeEvent(&sample_int)) {
1351                                         debugWarning("Packet port events lost\n");
1352                                         ok=false;
1353                                 }
1354                         }
1355                 }
1356
1357         }
1358        
1359         return ok;
1360 }
1361
1362 int AmdtpReceiveStreamProcessor::decodeMBLAEventsToPort(AmdtpAudioPort *p, quadlet_t *data,
1363                                            unsigned int offset, unsigned int nevents)
1364 {
1365         unsigned int j=0;
1366
1367 //      printf("****************\n");
1368 //      hexDumpQuadlets(data,m_dimension*4);
1369 //      printf("****************\n");
1370
1371         quadlet_t *target_event;
1372
1373         target_event=(quadlet_t *)(data + p->getPosition());
1374
1375         switch(p->getDataType()) {
1376                 default:
1377                 case Port::E_Int24:
1378                         {
1379                                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
1380
1381                                 assert(nevents + offset <= p->getBufferSize());
1382
1383                                 buffer+=offset;
1384
1385                                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
1386                                         *(buffer)=(ntohl((*target_event) ) & 0x00FFFFFF);
1387                                         buffer++;
1388                                         target_event+=m_dimension;
1389                                 }
1390                         }
1391                         break;
1392                 case Port::E_Float:
1393                         {
1394                                 const float multiplier = 1.0f / (float)(0x7FFFFF);
1395                                 float *buffer=(float *)(p->getBufferAddress());
1396
1397                                 assert(nevents + offset <= p->getBufferSize());
1398
1399                                 buffer+=offset;
1400
1401                                 for(j = 0; j < nevents; j += 1) { // decode max nsamples               
1402        
1403                                         unsigned int v = ntohl(*target_event) & 0x00FFFFFF;
1404                                         // sign-extend highest bit of 24-bit int
1405                                         int tmp = (int)(v << 8) / 256;
1406                
1407                                         *buffer = tmp * multiplier;
1408                                
1409                                         buffer++;
1410                                         target_event+=m_dimension;
1411                                 }
1412                         }
1413                         break;
1414         }
1415
1416         return 0;
1417 }
1418
1419 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.