root/trunk/libffado/src/libstreaming/amdtp/AmdtpTransmitStreamProcessor.cpp

Revision 1134, 39.4 kB (checked in by ppalmers, 16 years ago)

revert r1131 since it's does unconditional byteswapping

Line 
1 /*
2  * Copyright (C) 2005-2008 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 program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 2 of the License, or
12  * (at your option) version 3 of the License.
13  *
14  * This program 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
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 #include "config.h"
25 #include "AmdtpTransmitStreamProcessor.h"
26 #include "AmdtpPort.h"
27 #include "../StreamProcessorManager.h"
28 #include "devicemanager.h"
29
30 #include "libutil/Time.h"
31 #include "libutil/float_cast.h"
32
33 #include "libieee1394/ieee1394service.h"
34 #include "libieee1394/IsoHandlerManager.h"
35 #include "libieee1394/cycletimer.h"
36
37 #include <netinet/in.h>
38 #include <assert.h>
39
40 #define AMDTP_FLOAT_MULTIPLIER 2147483392.0
41
42 namespace Streaming
43 {
44
45 /* transmit */
46 AmdtpTransmitStreamProcessor::AmdtpTransmitStreamProcessor(FFADODevice &parent, int dimension)
47         : StreamProcessor(parent, ePT_Transmit)
48         , m_dimension( dimension )
49         , m_dbc( 0 )
50 #if AMDTP_ALLOW_PAYLOAD_IN_NODATA_XMIT
51         , m_send_nodata_payload ( AMDTP_SEND_PAYLOAD_IN_NODATA_XMIT_BY_DEFAULT )
52 #endif
53         , m_nb_audio_ports( 0 )
54         , m_nb_midi_ports( 0 )
55 {}
56
57 enum StreamProcessor::eChildReturnValue
58 AmdtpTransmitStreamProcessor::generatePacketHeader (
59     unsigned char *data, unsigned int *length,
60     unsigned char *tag, unsigned char *sy,
61     uint32_t pkt_ctr )
62 {
63     __builtin_prefetch(data, 1, 0); // prefetch events for write, no temporal locality
64     struct iec61883_packet *packet = (struct iec61883_packet *)data;
65     /* Our node ID can change after a bus reset, so it is best to fetch
66     * our node ID for each packet. */
67     packet->sid = m_local_node_id;
68
69     packet->dbs = m_dimension;
70     packet->fn = 0;
71     packet->qpc = 0;
72     packet->sph = 0;
73     packet->reserved = 0;
74     packet->dbc = m_dbc;
75     packet->eoh1 = 2;
76     packet->fmt = IEC61883_FMT_AMDTP;
77
78     *tag = IEC61883_TAG_WITH_CIP;
79     *sy = 0;
80
81     signed int fc;
82     uint64_t presentation_time;
83     unsigned int presentation_cycle;
84     int cycles_until_presentation;
85
86     uint64_t transmit_at_time;
87     unsigned int transmit_at_cycle;
88     int cycles_until_transmit;
89
90     debugOutputExtreme( DEBUG_LEVEL_ULTRA_VERBOSE,
91                         "Try for cycle %d\n", CYCLE_TIMER_GET_CYCLES(pkt_ctr) );
92     // check whether the packet buffer has packets for us to send.
93     // the base timestamp is the one of the next sample in the buffer
94     ffado_timestamp_t ts_head_tmp;
95     m_data_buffer->getBufferHeadTimestamp( &ts_head_tmp, &fc ); // thread safe
96
97     // the timestamp gives us the time at which we want the sample block
98     // to be output by the device
99     presentation_time = ( uint64_t ) ts_head_tmp;
100
101     // now we calculate the time when we have to transmit the sample block
102     transmit_at_time = substractTicks( presentation_time, AMDTP_TRANSMIT_TRANSFER_DELAY );
103
104     // calculate the cycle this block should be presented in
105     // (this is just a virtual calculation since at that time it should
106     //  already be in the device's buffer)
107     presentation_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( presentation_time ) );
108
109     // calculate the cycle this block should be transmitted in
110     transmit_at_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( transmit_at_time ) );
111
112     // we can check whether this cycle is within the 'window' we have
113     // to send this packet.
114     // first calculate the number of cycles left before presentation time
115     cycles_until_presentation = diffCycles ( presentation_cycle, CYCLE_TIMER_GET_CYCLES(pkt_ctr) );
116
117     // we can check whether this cycle is within the 'window' we have
118     // to send this packet.
119     // first calculate the number of cycles left before presentation time
120     cycles_until_transmit = diffCycles ( transmit_at_cycle, CYCLE_TIMER_GET_CYCLES(pkt_ctr) );
121
122     // two different options:
123     // 1) there are not enough frames for one packet
124     //      => determine wether this is a problem, since we might still
125     //         have some time to send it
126     // 2) there are enough packets
127     //      => determine whether we have to send them in this packet
128     if ( fc < ( signed int ) m_syt_interval )
129     {
130         // not enough frames in the buffer,
131
132         // we can still postpone the queueing of the packets
133         // if we are far enough ahead of the presentation time
134         if ( cycles_until_presentation <= AMDTP_MIN_CYCLES_BEFORE_PRESENTATION )
135         {
136             debugOutput( DEBUG_LEVEL_NORMAL,
137                          "Insufficient frames (P): N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
138                          fc, CYCLE_TIMER_GET_CYCLES(pkt_ctr),
139                          transmit_at_cycle, cycles_until_transmit );
140             // we are too late
141             return eCRV_XRun;
142         }
143         else
144         {
145             #if DEBUG_EXTREME
146             unsigned int now_cycle = ( unsigned int ) ( TICKS_TO_CYCLES ( m_1394service.getCycleTimerTicks() ) );
147
148             debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
149                                "Insufficient frames (NP): N=%02d, CY=%04u, TC=%04u, CUT=%04d, NOW=%04d\n",
150                                fc, CYCLE_TIMER_GET_CYCLES(pkt_ctr),
151                                transmit_at_cycle, cycles_until_transmit, now_cycle );
152             #endif
153
154             // there is still time left to send the packet
155             // we want the system to give this packet another go at a later time instant
156             return eCRV_Again; // note that the raw1394 again system doesn't work as expected
157
158             // we could wait here for a certain time before trying again. However, this
159             // is not going to work since we then block the iterator thread, hence also
160             // the receiving code, meaning that we are not processing received packets,
161             // and hence there is no progression in the number of frames available.
162
163             // for example:
164             // SleepRelativeUsec(125); // one cycle
165             // goto try_block_of_frames;
166
167             // or more advanced, calculate how many cycles we are ahead of 'now' and
168             // base the sleep on that.
169
170             // note that this requires that there is one thread for each IsoHandler,
171             // otherwise we're in the deadlock described above.
172         }
173     }
174     else
175     {
176         // there are enough frames, so check the time they are intended for
177         // all frames have a certain 'time window' in which they can be sent
178         // this corresponds to the range of the timestamp mechanism:
179         // we can send a packet 15 cycles in advance of the 'presentation time'
180         // in theory we can send the packet up till one cycle before the presentation time,
181         // however this is not very smart.
182
183         // There are 3 options:
184         // 1) the frame block is too early
185         //      => send an empty packet
186         // 2) the frame block is within the window
187         //      => send it
188         // 3) the frame block is too late
189         //      => discard (and raise xrun?)
190         //         get next block of frames and repeat
191
192         if(cycles_until_transmit < 0)
193         {
194             // we are too late
195             debugOutput(DEBUG_LEVEL_VERBOSE,
196                         "Too late: CY=%04u, TC=%04u, CUT=%04d, TSP=%011llu (%04u)\n",
197                         CYCLE_TIMER_GET_CYCLES(pkt_ctr),
198                         transmit_at_cycle, cycles_until_transmit,
199                         presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time) );
200             //debugShowBackLogLines(200);
201             // however, if we can send this sufficiently before the presentation
202             // time, it could be harmless.
203             // NOTE: dangerous since the device has no way of reporting that it didn't get
204             //       this packet on time.
205             if(cycles_until_presentation >= AMDTP_MIN_CYCLES_BEFORE_PRESENTATION)
206             {
207                 // we are not that late and can still try to transmit the packet
208                 m_dbc += fillDataPacketHeader(packet, length, presentation_time);
209                 m_last_timestamp = presentation_time;
210                 return (fc < (signed)(2*m_syt_interval) ? eCRV_Defer : eCRV_Packet);
211             }
212             else   // definitely too late
213             {
214                 return eCRV_XRun;
215             }
216         }
217         else if(cycles_until_transmit <= AMDTP_MAX_CYCLES_TO_TRANSMIT_EARLY)
218         {
219             // it's time send the packet
220             m_dbc += fillDataPacketHeader(packet, length, presentation_time);
221             m_last_timestamp = presentation_time;
222
223             // for timestamp tracing
224             debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
225                                "XMIT PKT: TSP= %011llu (%04u) (%04u) (%04u)\n",
226                                presentation_time,
227                                (unsigned int)CYCLE_TIMER_GET_CYCLES(pkt_ctr),
228                                presentation_cycle, transmit_at_cycle);
229
230             return (fc < (signed)(m_syt_interval) ? eCRV_Defer : eCRV_Packet);
231         }
232         else
233         {
234             debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
235                                "Too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
236                                CYCLE_TIMER_GET_CYCLES(pkt_ctr),
237                                transmit_at_cycle, cycles_until_transmit,
238                                transmit_at_time, (unsigned int)TICKS_TO_CYCLES(transmit_at_time),
239                                presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
240 #ifdef DEBUG
241             if ( cycles_until_transmit > AMDTP_MAX_CYCLES_TO_TRANSMIT_EARLY + 1 )
242             {
243                 debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
244                                    "Way too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
245                                    CYCLE_TIMER_GET_CYCLES(pkt_ctr),
246                                    transmit_at_cycle, cycles_until_transmit,
247                                    transmit_at_time, (unsigned int)TICKS_TO_CYCLES(transmit_at_time),
248                                    presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
249             }
250 #endif
251             // we are too early, send only an empty packet
252             return eCRV_EmptyPacket;
253         }
254     }
255     return eCRV_Invalid;
256 }
257
258 enum StreamProcessor::eChildReturnValue
259 AmdtpTransmitStreamProcessor::generatePacketData (
260     unsigned char *data, unsigned int *length )
261 {
262     if (m_data_buffer->readFrames(m_syt_interval, (char *)(data + 8)))
263     {
264         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
265                            "XMIT DATA: TSP= %011llu (%04u)\n",
266                            m_last_timestamp,
267                            (unsigned int)TICKS_TO_CYCLES(m_last_timestamp));
268         return eCRV_OK;
269     }
270     else return eCRV_XRun;
271 }
272
273 enum StreamProcessor::eChildReturnValue
274 AmdtpTransmitStreamProcessor::generateSilentPacketHeader (
275     unsigned char *data, unsigned int *length,
276     unsigned char *tag, unsigned char *sy,
277     uint32_t pkt_ctr )
278 {
279     struct iec61883_packet *packet = ( struct iec61883_packet * ) data;
280     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
281                        "XMIT SILENT (cy %04d): CY=%04u, TSP=%011llu (%04u)\n",
282                        CYCLE_TIMER_GET_CYCLES(pkt_ctr), m_last_timestamp,
283                        (unsigned int)TICKS_TO_CYCLES(m_last_timestamp));
284
285     packet->sid = m_local_node_id;
286
287     packet->dbs = m_dimension;
288     packet->fn = 0;
289     packet->qpc = 0;
290     packet->sph = 0;
291     packet->reserved = 0;
292     packet->dbc = m_dbc;
293     packet->eoh1 = 2;
294     packet->fmt = IEC61883_FMT_AMDTP;
295
296     *tag = IEC61883_TAG_WITH_CIP;
297     *sy = 0;
298
299     m_dbc += fillNoDataPacketHeader(packet, length);
300     return eCRV_Packet;
301 }
302
303 enum StreamProcessor::eChildReturnValue
304 AmdtpTransmitStreamProcessor::generateSilentPacketData (
305     unsigned char *data, unsigned int *length )
306 {
307     return eCRV_OK; // no need to do anything
308 }
309
310 enum StreamProcessor::eChildReturnValue
311 AmdtpTransmitStreamProcessor::generateEmptyPacketHeader (
312     unsigned char *data, unsigned int *length,
313     unsigned char *tag, unsigned char *sy,
314     uint32_t pkt_ctr )
315 {
316     struct iec61883_packet *packet = ( struct iec61883_packet * ) data;
317     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
318                        "XMIT EMPTY (cy %04d): CY=%04u, TSP=%011llu (%04u)\n",
319                        CYCLE_TIMER_GET_CYCLES(pkt_ctr), m_last_timestamp,
320                        (unsigned int)TICKS_TO_CYCLES(m_last_timestamp) );
321     packet->sid = m_local_node_id;
322
323     packet->dbs = m_dimension;
324     packet->fn = 0;
325     packet->qpc = 0;
326     packet->sph = 0;
327     packet->reserved = 0;
328     packet->dbc = m_dbc;
329     packet->eoh1 = 2;
330     packet->fmt = IEC61883_FMT_AMDTP;
331
332     *tag = IEC61883_TAG_WITH_CIP;
333     *sy = 0;
334
335     m_dbc += fillNoDataPacketHeader(packet, length);
336     return eCRV_OK;
337 }
338
339 enum StreamProcessor::eChildReturnValue
340 AmdtpTransmitStreamProcessor::generateEmptyPacketData (
341     unsigned char *data, unsigned int *length )
342 {
343     return eCRV_OK; // no need to do anything
344 }
345
346 unsigned int AmdtpTransmitStreamProcessor::fillDataPacketHeader (
347     struct iec61883_packet *packet, unsigned int* length,
348     uint32_t ts )
349 {
350
351     packet->fdf = m_fdf;
352
353     // convert the timestamp to SYT format
354     uint16_t timestamp_SYT = TICKS_TO_SYT ( ts );
355     packet->syt = htons ( timestamp_SYT );
356
357     // FIXME: use a precomputed value here
358     *length = m_syt_interval*sizeof ( quadlet_t ) *m_dimension + 8;
359
360     return m_syt_interval;
361 }
362
363 unsigned int AmdtpTransmitStreamProcessor::fillNoDataPacketHeader (
364     struct iec61883_packet *packet, unsigned int* length )
365 {
366     // no-data packets have syt=0xFFFF
367     // and (can) have the usual amount of events as dummy data
368     // DBC is not increased
369     packet->fdf = IEC61883_FDF_NODATA;
370     packet->syt = 0xffff;
371
372 #if AMDTP_ALLOW_PAYLOAD_IN_NODATA_XMIT
373     if ( m_send_nodata_payload )
374     { // no-data packets with payload (NOTE: DICE-II doesn't like that)
375         *length = 2*sizeof ( quadlet_t ) + m_syt_interval * m_dimension * sizeof ( quadlet_t );
376         return m_syt_interval;
377     } else { // no-data packets without payload
378         *length = 2*sizeof ( quadlet_t );
379         return 0;
380     }
381 #else
382     // no-data packets without payload
383     *length = 2*sizeof ( quadlet_t );
384     return 0;
385 #endif
386 }
387
388 unsigned int
389 AmdtpTransmitStreamProcessor::getSytInterval() {
390     switch (m_StreamProcessorManager.getNominalRate()) {
391         case 32000:
392         case 44100:
393         case 48000:
394             return 8;
395         case 88200:
396         case 96000:
397             return 16;
398         case 176400:
399         case 192000:
400             return 32;
401         default:
402             debugError("Unsupported rate: %d\n", m_StreamProcessorManager.getNominalRate());
403             return 0;
404     }
405 }
406 unsigned int
407 AmdtpTransmitStreamProcessor::getFDF() {
408     switch (m_StreamProcessorManager.getNominalRate()) {
409         case 32000: return IEC61883_FDF_SFC_32KHZ;
410         case 44100: return IEC61883_FDF_SFC_44K1HZ;
411         case 48000: return IEC61883_FDF_SFC_48KHZ;
412         case 88200: return IEC61883_FDF_SFC_88K2HZ;
413         case 96000: return IEC61883_FDF_SFC_96KHZ;
414         case 176400: return IEC61883_FDF_SFC_176K4HZ;
415         case 192000: return IEC61883_FDF_SFC_192KHZ;
416         default:
417             debugError("Unsupported rate: %d\n", m_StreamProcessorManager.getNominalRate());
418             return 0;
419     }
420 }
421
422 bool AmdtpTransmitStreamProcessor::prepareChild()
423 {
424     debugOutput ( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this );
425     m_syt_interval = getSytInterval();
426     m_fdf = getFDF();
427
428     iec61883_cip_init (
429         &m_cip_status,
430         IEC61883_FMT_AMDTP,
431         m_fdf,
432         m_StreamProcessorManager.getNominalRate(),
433         m_dimension,
434         m_syt_interval );
435
436     if (!initPortCache()) {
437         debugError("Could not init port cache\n");
438         return false;
439     }
440
441     return true;
442 }
443
444 /*
445 * compose the event streams for the packets from the port buffers
446 */
447 bool AmdtpTransmitStreamProcessor::processWriteBlock ( char *data,
448         unsigned int nevents, unsigned int offset )
449 {
450     // update the variable parts of the cache
451     updatePortCache();
452
453     // encode audio data
454     switch(m_StreamProcessorManager.getAudioDataType()) {
455         case StreamProcessorManager::eADT_Int24:
456             encodeAudioPortsInt24((quadlet_t *)data, offset, nevents);
457             break;
458         case StreamProcessorManager::eADT_Float:
459             encodeAudioPortsFloat((quadlet_t *)data, offset, nevents);
460             break;
461     }
462
463     // do midi ports
464     encodeMidiPorts((quadlet_t *)data, offset, nevents);
465     return true;
466 }
467
468 bool
469 AmdtpTransmitStreamProcessor::transmitSilenceBlock(
470     char *data, unsigned int nevents, unsigned int offset)
471 {
472     // no need to update the port cache when transmitting silence since
473     // no dynamic values are used to do so.
474     encodeAudioPortsSilence((quadlet_t *)data, offset, nevents);
475     encodeMidiPortsSilence((quadlet_t *)data, offset, nevents);
476     return true;
477 }
478
479 /**
480  * @brief encodes all audio ports in the cache to events (silent data)
481  * @param data
482  * @param offset
483  * @param nevents
484  */
485 void
486 AmdtpTransmitStreamProcessor::encodeAudioPortsSilence(quadlet_t *data,
487                                                       unsigned int offset,
488                                                       unsigned int nevents)
489 {
490     unsigned int j;
491     quadlet_t *target_event;
492     unsigned int i;
493
494     for (i = 0; i < m_nb_audio_ports; i++) {
495         target_event = (quadlet_t *)(data + i);
496
497         for (j = 0;j < nevents; j += 1)
498         {
499             *target_event = 0x00000040;
500             target_event += m_dimension;
501         }
502     }
503 }
504
505 #ifdef __SSE2__
506 //#if 0
507 #include <emmintrin.h>
508 #warning SSE2 build
509
510 /**
511  * @brief mux all audio ports to events
512  * @param data
513  * @param offset
514  * @param nevents
515  */
516 void
517 AmdtpTransmitStreamProcessor::encodeAudioPortsFloat(quadlet_t *data,
518                                                     unsigned int offset,
519                                                     unsigned int nevents)
520 {
521     unsigned int j;
522     quadlet_t *target_event;
523     unsigned int i;
524
525     float * client_buffers[4];
526     float tmp_values[4] __attribute__ ((aligned (16)));
527     uint32_t tmp_values_int[4] __attribute__ ((aligned (16)));
528
529     // prepare the scratch buffer
530     assert(m_scratch_buffer_size_bytes > nevents * 4);
531     memset(m_scratch_buffer, 0, nevents * 4);
532
533     const __m128i label = _mm_set_epi32 (0x40000000, 0x40000000, 0x40000000, 0x40000000);
534     const __m128 mult = _mm_set_ps(AMDTP_FLOAT_MULTIPLIER, AMDTP_FLOAT_MULTIPLIER, AMDTP_FLOAT_MULTIPLIER, AMDTP_FLOAT_MULTIPLIER);
535
536 #if AMDTP_CLIP_FLOATS
537     const __m128 v_max = _mm_set_ps(1.0, 1.0, 1.0, 1.0);
538     const __m128 v_min = _mm_set_ps(-1.0, -1.0, -1.0, -1.0);
539 #endif
540
541     // this assumes that audio ports are sorted by position,
542     // and that there are no gaps
543     for (i = 0; i < m_nb_audio_ports-4; i += 4) {
544         struct _MBLA_port_cache *p;
545
546         // get the port buffers
547         for (j=0; j<4; j++) {
548             p = &(m_audio_ports.at(i+j));
549             if(p->buffer && p->enabled) {
550                 client_buffers[j] = (float *) p->buffer;
551                 client_buffers[j] += offset;
552             } else {
553                 // if a port is disabled or has no valid
554                 // buffer, use the scratch buffer (all zero's)
555                 client_buffers[j] = (float *) m_scratch_buffer;
556             }
557         }
558
559         // the base event for this position
560         target_event = (quadlet_t *)(data + i);
561
562         // process the events
563         for (j=0;j < nevents; j += 1)
564         {
565             // read the values
566             tmp_values[0] = *(client_buffers[0]);
567             tmp_values[1] = *(client_buffers[1]);
568             tmp_values[2] = *(client_buffers[2]);
569             tmp_values[3] = *(client_buffers[3]);
570
571             // now do the SSE based conversion/labeling
572             __m128 v_float = *((__m128*)tmp_values);
573             __m128i *target = (__m128i*)target_event;
574             __m128i v_int;
575
576             // clip
577 #if AMDTP_CLIP_FLOATS
578             // do SSE clipping
579             v_float = _mm_max_ps(v_float, v_min);
580             v_float = _mm_min_ps(v_float, v_max);
581 #endif
582
583             // multiply
584             v_float = _mm_mul_ps(v_float, mult);
585             // convert to signed integer
586             v_int = _mm_cvttps_epi32( v_float );
587             // shift right 8 bits
588             v_int = _mm_srli_epi32( v_int, 8 );
589             // label it
590             v_int = _mm_or_si128( v_int, label );
591
592             // do endian conversion (SSE is always little endian)
593             // do first swap
594             v_int = _mm_or_si128( _mm_slli_epi16( v_int, 8 ), _mm_srli_epi16( v_int, 8 ) );
595             // do second swap
596             v_int = _mm_or_si128( _mm_slli_epi32( v_int, 16 ), _mm_srli_epi32( v_int, 16 ) );
597
598             // store the packed int
599             // (target misalignment is assumed since we don't know the m_dimension)
600             _mm_storeu_si128 (target, v_int);
601
602             // increment the buffer pointers
603             client_buffers[0]++;
604             client_buffers[1]++;
605             client_buffers[2]++;
606             client_buffers[3]++;
607
608             // go to next target event position
609             target_event += m_dimension;
610         }
611     }
612
613     // do remaining ports
614     // NOTE: these can be time-SSE'd
615     for (; i < m_nb_audio_ports; i++) {
616         struct _MBLA_port_cache &p = m_audio_ports.at(i);
617         target_event = (quadlet_t *)(data + i);
618         assert(nevents + offset <= p.buffer_size );
619
620         if(p.buffer && p.enabled) {
621             float *buffer = (float *)(p.buffer);
622             buffer += offset;
623    
624             for (j = 0;j < nevents; j += 4)
625             {
626                 // read the values
627                 tmp_values[0] = *buffer;
628                 buffer++;
629                 tmp_values[1] = *buffer;
630                 buffer++;
631                 tmp_values[2] = *buffer;
632                 buffer++;
633                 tmp_values[3] = *buffer;
634                 buffer++;
635
636                 // now do the SSE based conversion/labeling
637                 __m128 v_float = *((__m128*)tmp_values);
638                 __m128i v_int;
639
640 #if AMDTP_CLIP_FLOATS
641                 // do SSE clipping
642                 v_float = _mm_max_ps(v_float, v_min);
643                 v_float = _mm_min_ps(v_float, v_max);
644 #endif
645
646                 // multiply
647                 v_float = _mm_mul_ps(v_float, mult);
648                 // convert to signed integer
649                 v_int = _mm_cvttps_epi32( v_float );
650                 // shift right 8 bits
651                 v_int = _mm_srli_epi32( v_int, 8 );
652                 // label it
653                 v_int = _mm_or_si128( v_int, label );
654    
655                 // do endian conversion (SSE is always little endian)
656                 // do first swap
657                 v_int = _mm_or_si128( _mm_slli_epi16( v_int, 8 ), _mm_srli_epi16( v_int, 8 ) );
658                 // do second swap
659                 v_int = _mm_or_si128( _mm_slli_epi32( v_int, 16 ), _mm_srli_epi32( v_int, 16 ) );
660
661                 // store the packed int
662                 _mm_store_si128 ((__m128i *)(&tmp_values_int), v_int);
663
664                 // increment the buffer pointers
665                 *target_event = tmp_values_int[0];
666                 target_event += m_dimension;
667                 *target_event = tmp_values_int[1];
668                 target_event += m_dimension;
669                 *target_event = tmp_values_int[2];
670                 target_event += m_dimension;
671                 *target_event = tmp_values_int[3];
672                 target_event += m_dimension;
673             }
674
675             // do the remainder of the events
676             for(;j < nevents; j += 1) {
677                 float *in = (float *)buffer;
678 #if AMDTP_CLIP_FLOATS
679                 if(*in > 1.0) *in=1.0;
680                 if(*in < -1.0) *in=-1.0;
681 #endif
682                 float v = (*in) * AMDTP_FLOAT_MULTIPLIER;
683                 unsigned int tmp = ((int) v);
684                 tmp = ( tmp >> 8 ) | 0x40000000;
685                 *target_event = htonl((quadlet_t)tmp);
686                 buffer++;
687                 target_event += m_dimension;
688             }
689
690         } else {
691             for (j = 0;j < nevents; j += 1)
692             {
693                 // hardcoded byte swapped
694                 *target_event = 0x00000040;
695                 target_event += m_dimension;
696             }
697         }
698     }
699 }
700
701
702 /**
703  * @brief mux all audio ports to events
704  * @param data
705  * @param offset
706  * @param nevents
707  */
708 void
709 AmdtpTransmitStreamProcessor::encodeAudioPortsInt24(quadlet_t *data,
710                                                     unsigned int offset,
711                                                     unsigned int nevents)
712 {
713     unsigned int j;
714     quadlet_t *target_event;
715     unsigned int i;
716
717     uint32_t *client_buffers[4];
718     uint32_t tmp_values[4] __attribute__ ((aligned (16)));
719
720     // prepare the scratch buffer
721     assert(m_scratch_buffer_size_bytes > nevents * 4);
722     memset(m_scratch_buffer, 0, nevents * 4);
723
724     const __m128i label = _mm_set_epi32 (0x40000000, 0x40000000, 0x40000000, 0x40000000);
725     const __m128i mask  = _mm_set_epi32 (0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF, 0x00FFFFFF);
726
727     // this assumes that audio ports are sorted by position,
728     // and that there are no gaps
729     for (i = 0; i < m_nb_audio_ports-4; i += 4) {
730         struct _MBLA_port_cache *p;
731
732         // get the port buffers
733         for (j=0; j<4; j++) {
734             p = &(m_audio_ports.at(i+j));
735             if(p->buffer && p->enabled) {
736                 client_buffers[j] = (uint32_t *) p->buffer;
737                 client_buffers[j] += offset;
738             } else {
739                 // if a port is disabled or has no valid
740                 // buffer, use the scratch buffer (all zero's)
741                 client_buffers[j] = (uint32_t *) m_scratch_buffer;
742             }
743         }
744
745         // the base event for this position
746         target_event = (quadlet_t *)(data + i);
747
748         // process the events
749         for (j=0;j < nevents; j += 1)
750         {
751             // read the values
752             tmp_values[0] = *(client_buffers[0]);
753             tmp_values[1] = *(client_buffers[1]);
754             tmp_values[2] = *(client_buffers[2]);
755             tmp_values[3] = *(client_buffers[3]);
756
757             // now do the SSE based conversion/labeling
758             __m128i *target = (__m128i*)target_event;
759             __m128i v_int = *((__m128i*)tmp_values);;
760
761             // mask
762             v_int = _mm_and_si128( v_int, mask );
763             // label it
764             v_int = _mm_or_si128( v_int, label );
765
766             // do endian conversion (SSE is always little endian)
767             // do first swap
768             v_int = _mm_or_si128( _mm_slli_epi16( v_int, 8 ), _mm_srli_epi16( v_int, 8 ) );
769             // do second swap
770             v_int = _mm_or_si128( _mm_slli_epi32( v_int, 16 ), _mm_srli_epi32( v_int, 16 ) );
771
772             // store the packed int
773             // (target misalignment is assumed since we don't know the m_dimension)
774             _mm_storeu_si128 (target, v_int);
775
776             // increment the buffer pointers
777             client_buffers[0]++;
778             client_buffers[1]++;
779             client_buffers[2]++;
780             client_buffers[3]++;
781
782             // go to next target event position
783             target_event += m_dimension;
784         }
785     }
786
787     // do remaining ports
788     // NOTE: these can be time-SSE'd
789     for (; i < m_nb_audio_ports; i++) {
790         struct _MBLA_port_cache &p = m_audio_ports.at(i);
791         target_event = (quadlet_t *)(data + i);
792         assert(nevents + offset <= p.buffer_size );
793
794         if(p.buffer && p.enabled) {
795             uint32_t *buffer = (uint32_t *)(p.buffer);
796             buffer += offset;
797    
798             for (j = 0;j < nevents; j += 4)
799             {
800                 // read the values
801                 tmp_values[0] = *buffer;
802                 buffer++;
803                 tmp_values[1] = *buffer;
804                 buffer++;
805                 tmp_values[2] = *buffer;
806                 buffer++;
807                 tmp_values[3] = *buffer;
808                 buffer++;
809
810                 // now do the SSE based conversion/labeling
811                 __m128i v_int = *((__m128i*)tmp_values);;
812
813                 // mask
814                 v_int = _mm_and_si128( v_int, mask );
815                 // label it
816                 v_int = _mm_or_si128( v_int, label );
817
818                 // do endian conversion (SSE is always little endian)
819                 // do first swap
820                 v_int = _mm_or_si128( _mm_slli_epi16( v_int, 8 ), _mm_srli_epi16( v_int, 8 ) );
821                 // do second swap
822                 v_int = _mm_or_si128( _mm_slli_epi32( v_int, 16 ), _mm_srli_epi32( v_int, 16 ) );
823
824                 // store the packed int
825                 _mm_store_si128 ((__m128i *)(&tmp_values), v_int);
826
827                 // increment the buffer pointers
828                 *target_event = tmp_values[0];
829                 target_event += m_dimension;
830                 *target_event = tmp_values[1];
831                 target_event += m_dimension;
832                 *target_event = tmp_values[2];
833                 target_event += m_dimension;
834                 *target_event = tmp_values[3];
835                 target_event += m_dimension;
836             }
837
838             // do the remainder of the events
839             for(;j < nevents; j += 1) {
840                 uint32_t in = (uint32_t)(*buffer);
841                 *target_event = htonl((quadlet_t)((in & 0x00FFFFFF) | 0x40000000));
842                 buffer++;
843                 target_event += m_dimension;
844             }
845
846         } else {
847             for (j = 0;j < nevents; j += 1)
848             {
849                 // hardcoded byte swapped
850                 *target_event = 0x00000040;
851                 target_event += m_dimension;
852             }
853         }
854     }
855 }
856
857 #else
858
859 /**
860  * @brief mux all audio ports to events
861  * @param data
862  * @param offset
863  * @param nevents
864  */
865 void
866 AmdtpTransmitStreamProcessor::encodeAudioPortsInt24(quadlet_t *data,
867                                                     unsigned int offset,
868                                                     unsigned int nevents)
869 {
870     unsigned int j;
871     quadlet_t *target_event;
872     unsigned int i;
873
874     for (i = 0; i < m_nb_audio_ports; i++) {
875         struct _MBLA_port_cache &p = m_audio_ports.at(i);
876         target_event = (quadlet_t *)(data + i);
877         assert(nevents + offset <= p.buffer_size );
878
879         if(p.buffer && p.enabled) {
880             quadlet_t *buffer = (quadlet_t *)(p.buffer);
881             buffer += offset;
882    
883             for (j = 0;j < nevents; j += 1)
884             {
885                 uint32_t in = (uint32_t)(*buffer);
886                 *target_event = htonl((quadlet_t)((in & 0x00FFFFFF) | 0x40000000));
887                 buffer++;
888                 target_event += m_dimension;
889             }
890         } else {
891             for (j = 0;j < nevents; j += 1)
892             {
893                 *target_event = 0x00000040;
894                 target_event += m_dimension;
895             }
896         }
897     }
898 }
899
900 /**
901  * @brief mux all audio ports to events
902  * @param data
903  * @param offset
904  * @param nevents
905  */
906 void
907 AmdtpTransmitStreamProcessor::encodeAudioPortsFloat(quadlet_t *data,
908                                                     unsigned int offset,
909                                                     unsigned int nevents)
910 {
911     unsigned int j;
912     quadlet_t *target_event;
913     unsigned int i;
914
915     for (i = 0; i < m_nb_audio_ports; i++) {
916         struct _MBLA_port_cache &p = m_audio_ports.at(i);
917         target_event = (quadlet_t *)(data + i);
918         assert(nevents + offset <= p.buffer_size );
919
920         if(p.buffer && p.enabled) {
921             quadlet_t *buffer = (quadlet_t *)(p.buffer);
922             buffer += offset;
923    
924             for (j = 0;j < nevents; j += 1)
925             {
926                 float *in = (float *)buffer;
927 #if AMDTP_CLIP_FLOATS
928                 if(*in > 1.0) *in=1.0;
929                 if(*in < -1.0) *in=-1.0;
930 #endif
931                 float v = (*in) * AMDTP_FLOAT_MULTIPLIER;
932                 unsigned int tmp = ((int) lrintf(v));
933
934                 tmp = ( tmp >> 8 ) | 0x40000000;
935                 *target_event = htonl((quadlet_t)tmp);
936                 buffer++;
937                 target_event += m_dimension;
938             }
939         } else {
940             for (j = 0;j < nevents; j += 1)
941             {
942                 // hardcoded little endian
943                 *target_event = 0x00000040;
944                 target_event += m_dimension;
945             }
946         }
947     }
948 }
949 #endif
950
951 /**
952  * @brief encodes all midi ports in the cache to events (silence)
953  * @param data
954  * @param offset
955  * @param nevents
956  */
957 void
958 AmdtpTransmitStreamProcessor::encodeMidiPortsSilence(quadlet_t *data,
959                                                      unsigned int offset,
960                                                      unsigned int nevents)
961 {
962     quadlet_t *target_event;
963     unsigned int i,j;
964
965     for (i = 0; i < m_nb_midi_ports; i++) {
966         struct _MIDI_port_cache &p = m_midi_ports.at(i);
967
968         for (j = p.location;j < nevents; j += 8) {
969             target_event = (quadlet_t *) (data + ((j * m_dimension) + p.position));
970             *target_event = htonl(IEC61883_AM824_SET_LABEL(0, IEC61883_AM824_LABEL_MIDI_NO_DATA));
971         }
972     }
973 }
974
975 /**
976  * @brief encodes all midi ports in the cache to events
977  * @param data
978  * @param offset
979  * @param nevents
980  */
981 void
982 AmdtpTransmitStreamProcessor::encodeMidiPorts(quadlet_t *data,
983                                               unsigned int offset,
984                                               unsigned int nevents)
985 {
986     quadlet_t *target_event;
987     unsigned int i,j;
988
989     for (i = 0; i < m_nb_midi_ports; i++) {
990         struct _MIDI_port_cache &p = m_midi_ports.at(i);
991         if (p.buffer && p.enabled) {
992             uint32_t *buffer = (quadlet_t *)(p.buffer);
993             buffer += offset;
994
995             for (j = p.location;j < nevents; j += 8) {
996                 target_event = (quadlet_t *) (data + ((j * m_dimension) + p.position));
997
998                 if ( *buffer & 0xFF000000 )   // we can send a byte
999                 {
1000                     quadlet_t tmpval;
1001                     tmpval = ((*buffer)<<16) & 0x00FF0000;
1002                     tmpval = IEC61883_AM824_SET_LABEL(tmpval, IEC61883_AM824_LABEL_MIDI_1X);
1003                     *target_event = htonl(tmpval);
1004
1005 //                     debugOutput ( DEBUG_LEVEL_VERBOSE, "MIDI port %s, pos=%u, loc=%u, nevents=%u, dim=%d\n",
1006 //                                p.port->getName().c_str(), p.position, p.location, nevents, m_dimension );
1007 //                     debugOutput ( DEBUG_LEVEL_VERBOSE, "base=%p, target=%p, value=%08X\n",
1008 //                                data, target_event, tmpval );
1009                 } else {
1010                     // can't send a byte, either because there is no byte,
1011                     // or because this would exceed the maximum rate
1012                     // FIXME: this can be ifdef optimized since it's a constant
1013                     *target_event = htonl(IEC61883_AM824_SET_LABEL(0, IEC61883_AM824_LABEL_MIDI_NO_DATA));
1014                 }
1015                 buffer+=8;
1016             }
1017         } else {
1018             for (j = p.location;j < nevents; j += 8) {
1019                 target_event = (quadlet_t *)(data + ((j * m_dimension) + p.position));
1020                 __builtin_prefetch(target_event, 1, 0); // prefetch events for write, no temporal locality
1021                 *target_event = htonl(IEC61883_AM824_SET_LABEL(0, IEC61883_AM824_LABEL_MIDI_NO_DATA));
1022             }
1023         }
1024     }
1025 }
1026
1027 bool
1028 AmdtpTransmitStreamProcessor::initPortCache() {
1029     // make use of the fact that audio ports are the first ports in
1030     // the cluster as per AMDTP. so we can sort the ports by position
1031     // and have very efficient lookups:
1032     // m_float_ports.at(i).buffer -> audio stream i buffer
1033     // for midi ports we simply cache all port info since they are (usually) not
1034     // that numerous
1035     m_nb_audio_ports = 0;
1036     m_audio_ports.clear();
1037    
1038     m_nb_midi_ports = 0;
1039     m_midi_ports.clear();
1040    
1041     for(PortVectorIterator it = m_Ports.begin();
1042         it != m_Ports.end();
1043         ++it )
1044     {
1045         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
1046         assert(pinfo); // this should not fail!!
1047
1048         switch( pinfo->getFormat() )
1049         {
1050             case AmdtpPortInfo::E_MBLA:
1051                 m_nb_audio_ports++;
1052                 break;
1053             case AmdtpPortInfo::E_SPDIF: // still unimplemented
1054                 break;
1055             case AmdtpPortInfo::E_Midi:
1056                 m_nb_midi_ports++;
1057                 break;
1058             default: // ignore
1059                 break;
1060         }
1061     }
1062
1063     unsigned int idx;
1064     for (idx = 0; idx < m_nb_audio_ports; idx++) {
1065         for(PortVectorIterator it = m_Ports.begin();
1066             it != m_Ports.end();
1067             ++it )
1068         {
1069             AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
1070             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
1071                         "idx %u: looking at port %s at position %u\n",
1072                         idx, (*it)->getName().c_str(), pinfo->getPosition());
1073             if(pinfo->getPosition() == idx) {
1074                 struct _MBLA_port_cache p;
1075                 p.port = dynamic_cast<AmdtpAudioPort *>(*it);
1076                 if(p.port == NULL) {
1077                     debugError("Port is not an AmdtpAudioPort!\n");
1078                     return false;
1079                 }
1080                 p.buffer = NULL; // to be filled by updatePortCache
1081                 #ifdef DEBUG
1082                 p.buffer_size = (*it)->getBufferSize();
1083                 #endif
1084
1085                 m_audio_ports.push_back(p);
1086                 debugOutput(DEBUG_LEVEL_VERBOSE,
1087                             "Cached port %s at position %u\n",
1088                             p.port->getName().c_str(), idx);
1089                 goto next_index;
1090             }
1091         }
1092         debugError("No MBLA port found for position %d\n", idx);
1093         return false;
1094 next_index:
1095         continue;
1096     }
1097
1098     for(PortVectorIterator it = m_Ports.begin();
1099         it != m_Ports.end();
1100         ++it )
1101     {
1102         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
1103         debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
1104                     "idx %u: looking at port %s at position %u, location %u\n",
1105                     idx, (*it)->getName().c_str(), pinfo->getPosition(), pinfo->getLocation());
1106         if ((*it)->getPortType() == Port::E_Midi) {
1107             struct _MIDI_port_cache p;
1108             p.port = dynamic_cast<AmdtpMidiPort *>(*it);
1109             if(p.port == NULL) {
1110                 debugError("Port is not an AmdtpMidiPort!\n");
1111                 return false;
1112             }
1113             p.position = pinfo->getPosition();
1114             p.location = pinfo->getLocation();
1115             p.buffer = NULL; // to be filled by updatePortCache
1116             #ifdef DEBUG
1117             p.buffer_size = (*it)->getBufferSize();
1118             #endif
1119
1120             m_midi_ports.push_back(p);
1121             debugOutput(DEBUG_LEVEL_VERBOSE,
1122                         "Cached port %s at position %u, location %u\n",
1123                         p.port->getName().c_str(), p.position, p.location);
1124         }
1125     }
1126
1127     return true;
1128 }
1129
1130 void
1131 AmdtpTransmitStreamProcessor::updatePortCache() {
1132     unsigned int idx;
1133     for (idx = 0; idx < m_nb_audio_ports; idx++) {
1134         struct _MBLA_port_cache& p = m_audio_ports.at(idx);
1135         AmdtpAudioPort *port = p.port;
1136         p.buffer = port->getBufferAddress();
1137         p.enabled = !port->isDisabled();
1138     }
1139     for (idx = 0; idx < m_nb_midi_ports; idx++) {
1140         struct _MIDI_port_cache& p = m_midi_ports.at(idx);
1141         AmdtpMidiPort *port = p.port;
1142         p.buffer = port->getBufferAddress();
1143         p.enabled = !port->isDisabled();
1144     }
1145 }
1146
1147 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.