root/branches/ppalmers-streaming/src/libstreaming/amdtp/AmdtpReceiveStreamProcessor.cpp

Revision 720, 12.5 kB (checked in by ppalmers, 16 years ago)

first working version of the reworked streaming code

Line 
1 /*
2  * Copyright (C) 2005-2007 by Pieter Palmers
3  *
4  * This file is part of FFADO
5  * FFADO = Free Firewire (pro-)audio drivers for linux
6  *
7  * FFADO is based upon FreeBoB.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License version 2.1, as published by the Free Software Foundation;
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21  * MA 02110-1301 USA
22  */
23
24 #include "AmdtpReceiveStreamProcessor.h"
25 #include "AmdtpPort.h"
26 #include "../StreamProcessorManager.h"
27
28 #include "../util/cycletimer.h"
29
30 #include <netinet/in.h>
31 #include <assert.h>
32
33 // in ticks
34 // as per AMDTP2.1:
35 // 354.17us + 125us @ 24.576ticks/usec = 11776.08192 ticks
36 #define DEFAULT_TRANSFER_DELAY (11776U)
37
38 #define TRANSMIT_TRANSFER_DELAY DEFAULT_TRANSFER_DELAY
39
40 namespace Streaming {
41
42 /* --------------------- RECEIVE ----------------------- */
43
44 AmdtpReceiveStreamProcessor::AmdtpReceiveStreamProcessor(int port, int dimension)
45     : StreamProcessor(ePT_Receive , port)
46     , m_dimension(dimension)
47 {}
48
49
50 unsigned int
51 AmdtpReceiveStreamProcessor::getPacketsPerPeriod()
52 {
53     return (m_manager->getPeriodSize())/m_syt_interval;
54 }
55
56 bool AmdtpReceiveStreamProcessor::prepareChild() {
57     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this);
58
59     switch (m_manager->getNominalRate()) {
60         case 32000:
61         case 44100:
62         case 48000:
63             m_syt_interval = 8;
64             break;
65         case 88200:
66         case 96000:
67             m_syt_interval = 16;
68             break;
69         case 176400:
70         case 192000:
71             m_syt_interval = 32;
72             break;
73         default:
74             debugError("Unsupported rate: %d\n", m_manager->getNominalRate());
75             return false;
76     }
77
78     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepared for:\n");
79     debugOutput( DEBUG_LEVEL_VERBOSE, " Samplerate: %d, DBS: %d, SYT: %d\n",
80              m_manager->getNominalRate(), m_dimension, m_syt_interval);
81     debugOutput( DEBUG_LEVEL_VERBOSE, " PeriodSize: %d, NbBuffers: %d\n",
82              m_manager->getPeriodSize(), m_manager->getNbBuffers());
83     debugOutput( DEBUG_LEVEL_VERBOSE, " Port: %d, Channel: %d\n",
84              m_port,m_channel);
85
86     return true;
87 }
88
89
90 /**
91  * Processes packet header to extract timestamps and so on
92  * @param data
93  * @param length
94  * @param channel
95  * @param tag
96  * @param sy
97  * @param cycle
98  * @param dropped
99  * @return true if this is a valid packet, false if not
100  */
101 bool
102 AmdtpReceiveStreamProcessor::processPacketHeader(unsigned char *data, unsigned int length,
103                   unsigned char channel, unsigned char tag, unsigned char sy,
104                   unsigned int cycle, unsigned int dropped)
105 {
106     struct iec61883_packet *packet = (struct iec61883_packet *) data;
107     assert(packet);
108     bool retval = (packet->syt != 0xFFFF) &&
109                   (packet->fdf != 0xFF) &&
110                   (packet->fmt == 0x10) &&
111                   (packet->dbs > 0) &&
112                   (length >= 2*sizeof(quadlet_t));
113     if(retval) {
114         uint64_t now = m_handler->getCycleTimer();
115         //=> convert the SYT to a full timestamp in ticks
116         m_last_timestamp = sytRecvToFullTicks((uint32_t)ntohs(packet->syt),
117                                               cycle, now);
118     }
119     return retval;
120 }
121
122 /**
123  * extract the data from the packet
124  * @pre the IEC61883 packet is valid according to isValidPacket
125  * @param data
126  * @param length
127  * @param channel
128  * @param tag
129  * @param sy
130  * @param cycle
131  * @param dropped
132  * @return true if successful, false if xrun
133  */
134 bool
135 AmdtpReceiveStreamProcessor::processPacketData(unsigned char *data, unsigned int length,
136                   unsigned char channel, unsigned char tag, unsigned char sy,
137                   unsigned int cycle, unsigned int dropped_cycles) {
138     struct iec61883_packet *packet = (struct iec61883_packet *) data;
139     assert(packet);
140
141     unsigned int nevents=((length / sizeof (quadlet_t)) - 2)/packet->dbs;
142
143     // we have to keep in mind that there are also
144     // some packets buffered by the ISO layer,
145     // at most x=m_handler->getWakeupInterval()
146     // these contain at most x*syt_interval
147     // frames, meaning that we might receive
148     // this packet x*syt_interval*ticks_per_frame
149     // later than expected (the real receive time)
150     #ifdef DEBUG
151     if(isRunning()) {
152         debugOutput(DEBUG_LEVEL_VERY_VERBOSE,"STMP: %lluticks | buff=%d, syt_interval=%d, tpf=%f\n",
153             m_last_timestamp, m_handler->getWakeupInterval(), m_syt_interval, getTicksPerFrame());
154     }
155     #endif
156
157     if(m_data_buffer->writeFrames(nevents, (char *)(data+8), m_last_timestamp)) {
158         // process all ports that should be handled on a per-packet base
159         // this is MIDI for AMDTP (due to the need of DBC)
160         if (!decodePacketPorts((quadlet_t *)(data+8), nevents, packet->dbc)) {
161             debugWarning("Problem decoding Packet Ports\n");
162         }
163         return true;
164     } else {
165         return false;
166     }
167 }
168
169 /***********************************************
170  * Encoding/Decoding API                       *
171  ***********************************************/
172 /**
173  * @brief write received events to the stream ringbuffers.
174  */
175 bool AmdtpReceiveStreamProcessor::processReadBlock(char *data,
176                        unsigned int nevents, unsigned int offset)
177 {
178     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "(%p)->processReadBlock(%u, %u)\n",this,nevents,offset);
179
180     bool no_problem=true;
181
182     for ( PortVectorIterator it = m_PeriodPorts.begin();
183           it != m_PeriodPorts.end();
184           ++it )
185     {
186         if((*it)->isDisabled()) {continue;};
187
188         //FIXME: make this into a static_cast when not DEBUG?
189
190         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
191         assert(pinfo); // this should not fail!!
192
193         switch(pinfo->getFormat()) {
194         case AmdtpPortInfo::E_MBLA:
195             if(decodeMBLAEventsToPort(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
196                 debugWarning("Could not decode packet MBLA to port %s",(*it)->getName().c_str());
197                 no_problem=false;
198             }
199             break;
200         case AmdtpPortInfo::E_SPDIF: // still unimplemented
201             break;
202     /* for this processor, midi is a packet based port
203         case AmdtpPortInfo::E_Midi:
204             break;*/
205         default: // ignore
206             break;
207         }
208     }
209     return no_problem;
210 }
211
212 /**
213  * @brief write silence events to the stream ringbuffers.
214  */
215 bool AmdtpReceiveStreamProcessor::provideSilenceBlock(unsigned int nevents, unsigned int offset)
216 {
217     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "(%p)->proviceSilenceBlock(%u, %u)\n", this, nevents, offset);
218
219     bool no_problem=true;
220
221     for ( PortVectorIterator it = m_PeriodPorts.begin();
222           it != m_PeriodPorts.end();
223           ++it )
224     {
225         if((*it)->isDisabled()) {continue;};
226         //FIXME: make this into a static_cast when not DEBUG?
227         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
228         assert(pinfo); // this should not fail!!
229
230         switch(pinfo->getFormat()) {
231         case AmdtpPortInfo::E_MBLA:
232             if(provideSilenceToPort(static_cast<AmdtpAudioPort *>(*it), offset, nevents)) {
233                 debugWarning("Could not put silence into to port %s",(*it)->getName().c_str());
234                 no_problem=false;
235             }
236             break;
237         case AmdtpPortInfo::E_SPDIF: // still unimplemented
238             break;
239     /* for this processor, midi is a packet based port
240         case AmdtpPortInfo::E_Midi:
241             break;*/
242         default: // ignore
243             break;
244         }
245     }
246     return no_problem;
247 }
248
249 /**
250  * @brief decode a packet for the packet-based ports
251  *
252  * @param data Packet data
253  * @param nevents number of events in data (including events of other ports & port types)
254  * @param dbc DataBlockCount value for this packet
255  * @return true if all successfull
256  */
257 bool AmdtpReceiveStreamProcessor::decodePacketPorts(quadlet_t *data, unsigned int nevents, unsigned int dbc)
258 {
259     bool ok=true;
260
261     quadlet_t *target_event=NULL;
262     unsigned int j;
263
264     for ( PortVectorIterator it = m_PacketPorts.begin();
265           it != m_PacketPorts.end();
266           ++it )
267     {
268
269 #ifdef DEBUG
270         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
271         assert(pinfo); // this should not fail!!
272
273         // the only packet type of events for AMDTP is MIDI in mbla
274         assert(pinfo->getFormat()==AmdtpPortInfo::E_Midi);
275 #endif
276         AmdtpMidiPort *mp=static_cast<AmdtpMidiPort *>(*it);
277
278         // we decode this directly (no function call) due to the high frequency
279         /* idea:
280         spec says: current_midi_port=(dbc+j)%8;
281         => if we start at (dbc+stream->location-1)%8,
282         we'll start at the right event for the midi port.
283         => if we increment j with 8, we stay at the right event.
284         */
285         // FIXME: as we know in advance how big a packet is (syt_interval) we can
286         //        predict how much loops will be present here
287         for(j = (dbc & 0x07)+mp->getLocation(); j < nevents; j += 8) {
288             target_event=(quadlet_t *)(data + ((j * m_dimension) + mp->getPosition()));
289             quadlet_t sample_int=ntohl(*target_event);
290             // FIXME: this assumes that 2X and 3X speed isn't used,
291             // because only the 1X slot is put into the ringbuffer
292             if(IEC61883_AM824_GET_LABEL(sample_int) != IEC61883_AM824_LABEL_MIDI_NO_DATA) {
293                 sample_int=(sample_int >> 16) & 0x000000FF;
294                 if(!mp->writeEvent(&sample_int)) {
295                     debugWarning("Packet port events lost\n");
296                     ok=false;
297                 }
298             }
299         }
300
301     }
302
303     return ok;
304 }
305
306 int
307 AmdtpReceiveStreamProcessor::decodeMBLAEventsToPort(
308                        AmdtpAudioPort *p, quadlet_t *data,
309                        unsigned int offset, unsigned int nevents)
310 {
311     unsigned int j=0;
312     quadlet_t *target_event;
313
314     target_event=(quadlet_t *)(data + p->getPosition());
315
316     switch(p->getDataType()) {
317         default:
318         case Port::E_Int24:
319             {
320                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
321
322                 assert(nevents + offset <= p->getBufferSize());
323
324                 buffer+=offset;
325
326                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
327                     *(buffer)=(ntohl((*target_event) ) & 0x00FFFFFF);
328                     buffer++;
329                     target_event+=m_dimension;
330                 }
331             }
332             break;
333         case Port::E_Float:
334             {
335                 const float multiplier = 1.0f / (float)(0x7FFFFF);
336                 float *buffer=(float *)(p->getBufferAddress());
337
338                 assert(nevents + offset <= p->getBufferSize());
339
340                 buffer+=offset;
341
342                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
343
344                     unsigned int v = ntohl(*target_event) & 0x00FFFFFF;
345                     // sign-extend highest bit of 24-bit int
346                     int tmp = (int)(v << 8) / 256;
347
348                     *buffer = tmp * multiplier;
349
350                     buffer++;
351                     target_event+=m_dimension;
352                 }
353             }
354             break;
355     }
356
357     return 0;
358 }
359
360 int
361 AmdtpReceiveStreamProcessor::provideSilenceToPort(
362                        AmdtpAudioPort *p, unsigned int offset, unsigned int nevents)
363 {
364     unsigned int j=0;
365     switch(p->getDataType()) {
366         default:
367         case Port::E_Int24:
368             {
369                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
370                 assert(nevents + offset <= p->getBufferSize());
371                 buffer+=offset;
372
373                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
374                     *(buffer)=0;
375                     buffer++;
376                 }
377             }
378             break;
379         case Port::E_Float:
380             {
381                 float *buffer=(float *)(p->getBufferAddress());
382                 assert(nevents + offset <= p->getBufferSize());
383                 buffer+=offset;
384
385                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
386                     *buffer = 0.0;
387                     buffer++;
388                 }
389             }
390             break;
391     }
392     return 0;
393 }
394
395 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.