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

Revision 715, 31.7 kB (checked in by ppalmers, 15 years ago)

some more cleaning

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 "AmdtpTransmitStreamProcessor.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 /* transmit */
43 AmdtpTransmitStreamProcessor::AmdtpTransmitStreamProcessor(int port, int dimension)
44         : StreamProcessor(ePT_Transmit, port)
45         , m_dimension(dimension)
46         , m_last_timestamp(0)
47         , m_dbc(0)
48         , m_ringbuffer_size_frames(0)
49 {}
50
51 /**
52  * @return
53  */
54 bool AmdtpTransmitStreamProcessor::init() {
55
56     debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing (%p)...\n", this);
57     // call the parent init
58     // this has to be done before allocating the buffers,
59     // because this sets the buffersizes from the processormanager
60     if(!StreamProcessor::init()) {
61         debugFatal("Could not do base class init (%p)\n",this);
62         return false;
63     }
64     return true;
65 }
66
67 enum raw1394_iso_disposition
68 AmdtpTransmitStreamProcessor::getPacket(unsigned char *data, unsigned int *length,
69                   unsigned char *tag, unsigned char *sy,
70                   int cycle, unsigned int dropped, unsigned int max_length) {
71     struct iec61883_packet *packet = (struct iec61883_packet *) data;
72
73     if (cycle<0) {
74         debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,"Xmit handler for cycle %d, (running=%d)\n",
75             cycle, m_running);
76         *tag = 0;
77         *sy = 0;
78         *length=0;
79         return RAW1394_ISO_OK;
80     }
81
82     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,"Xmit handler for cycle %d, (running=%d)\n",
83         cycle, m_running);
84
85     if (addCycles(m_last_cycle, 1) != cycle) {
86         debugWarning("(%p) Dropped %d packets on cycle %d\n", diffCycles(cycle,m_last_cycle)-1, cycle);
87     }
88
89     m_last_cycle=cycle;
90
91 #ifdef DEBUG
92     if(dropped>0) {
93         debugWarning("Dropped %d packets on cycle %d\n",dropped, cycle);
94     }
95 #endif
96
97     // calculate & preset common values
98
99     /* Our node ID can change after a bus reset, so it is best to fetch
100      * our node ID for each packet. */
101     packet->sid = getNodeId() & 0x3f;
102
103     packet->dbs = m_dimension;
104     packet->fn = 0;
105     packet->qpc = 0;
106     packet->sph = 0;
107     packet->reserved = 0;
108     packet->dbc = m_dbc;
109     packet->eoh1 = 2;
110     packet->fmt = IEC61883_FMT_AMDTP;
111
112     *tag = IEC61883_TAG_WITH_CIP;
113     *sy = 0;
114
115     // determine if we want to send a packet or not
116     // note that we can't use getCycleTimer directly here,
117     // because packets are queued in advance. This means that
118     // we the packet we are constructing will be sent out
119     // on 'cycle', not 'now'.
120     unsigned int ctr=m_handler->getCycleTimer();
121     int now_cycles = (int)CYCLE_TIMER_GET_CYCLES(ctr);
122
123     // the difference between the cycle this
124     // packet is intended for and 'now'
125     int cycle_diff = diffCycles(cycle, now_cycles);
126
127 #ifdef DEBUG
128     if(m_running && (cycle_diff < 0)) {
129         debugWarning("Requesting packet for cycle %04d which is in the past (now=%04dcy)\n",
130             cycle, now_cycles);
131     }
132
133     // keep track of the lag
134     m_PacketStat.mark(cycle_diff);
135 #endif
136
137     // as long as the cycle parameter is not in sync with
138     // the current time, the stream is considered not
139     // to be 'running'
140     // NOTE: this works only at startup
141     if (!m_running && cycle_diff >= 0 && cycle >= 0) {
142             debugOutput(DEBUG_LEVEL_VERBOSE, "Xmit StreamProcessor %p started running at cycle %d\n",this, cycle);
143             m_running=true;
144     }
145
146     signed int fc;
147     uint64_t presentation_time;
148     unsigned int presentation_cycle;
149     int cycles_until_presentation;
150
151     uint64_t transmit_at_time;
152     unsigned int transmit_at_cycle;
153     int cycles_until_transmit;
154
155     // FIXME: should become a define
156     // the absolute minimum number of cycles we want to transmit
157     // a packet ahead of the presentation time. The nominal time
158     // the packet is transmitted ahead of the presentation time is
159     // given by TRANSMIT_TRANSFER_DELAY (in ticks), but in case we
160     // are too late for that, this constant defines how late we can
161     // be.
162     const int min_cycles_before_presentation = 1;
163     // FIXME: should become a define
164     // the absolute maximum number of cycles we want to transmit
165     // a packet ahead of the ideal transmit time. The nominal time
166     // the packet is transmitted ahead of the presentation time is
167     // given by TRANSMIT_TRANSFER_DELAY (in ticks), but we can send
168     // packets early if we want to. (not completely according to spec)
169     const int max_cycles_to_transmit_early = 5;
170
171     if( !m_running || !m_data_buffer->isEnabled() ) {
172         debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
173                     "Not running (%d) or buffer not enabled (enabled=%d)\n",
174                     m_running, m_data_buffer->isEnabled());
175
176         // not running or not enabled
177         goto send_empty_packet;
178     }
179
180 try_block_of_frames:
181     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "Try for cycle %d\n", cycle);
182     // check whether the packet buffer has packets for us to send.
183     // the base timestamp is the one of the next sample in the buffer
184     ffado_timestamp_t ts_head_tmp;
185     m_data_buffer->getBufferHeadTimestamp(&ts_head_tmp, &fc); // thread safe
186
187     // the timestamp gives us the time at which we want the sample block
188     // to be output by the device
189     presentation_time=(uint64_t)ts_head_tmp;
190
191     // now we calculate the time when we have to transmit the sample block
192     transmit_at_time = substractTicks(presentation_time, TRANSMIT_TRANSFER_DELAY);
193
194     // calculate the cycle this block should be presented in
195     // (this is just a virtual calculation since at that time it should
196     //  already be in the device's buffer)
197     presentation_cycle = (unsigned int)(TICKS_TO_CYCLES( presentation_time ));
198
199     // calculate the cycle this block should be transmitted in
200     transmit_at_cycle = (unsigned int)(TICKS_TO_CYCLES( transmit_at_time ));
201
202     // we can check whether this cycle is within the 'window' we have
203     // to send this packet.
204     // first calculate the number of cycles left before presentation time
205     cycles_until_presentation = diffCycles( presentation_cycle, cycle );
206
207     // we can check whether this cycle is within the 'window' we have
208     // to send this packet.
209     // first calculate the number of cycles left before presentation time
210     cycles_until_transmit = diffCycles( transmit_at_cycle, cycle );
211
212     // two different options:
213     // 1) there are not enough frames for one packet
214     //      => determine wether this is a problem, since we might still
215     //         have some time to send it
216     // 2) there are enough packets
217     //      => determine whether we have to send them in this packet
218     if (fc < (signed int)m_syt_interval) {
219         m_PacketStat.signal(0);
220         // not enough frames in the buffer,
221         debugOutput(DEBUG_LEVEL_VERBOSE,
222                     "Insufficient frames: N=%02d, CY=%04u, TC=%04u, CUT=%04d\n",
223                     fc, cycle, transmit_at_cycle, cycles_until_transmit);
224         // we can still postpone the queueing of the packets
225         // if we are far enough ahead of the presentation time
226         if( cycles_until_presentation <= min_cycles_before_presentation ) {
227             m_PacketStat.signal(1);
228             // we are too late
229             // meaning that we in some sort of xrun state
230             // signal xrun situation ??HERE??
231             m_xruns++;
232             // we send an empty packet on this cycle
233             goto send_empty_packet; // UGLY but effective
234         } else {
235             m_PacketStat.signal(2);
236             // there is still time left to send the packet
237             // we want the system to give this packet another go
238 //             goto try_packet_again; // UGLY but effective
239             // unfortunatly the try_again doesn't work very well,
240             // so we'll have to either usleep(one cycle) and goto try_block_of_frames
241            
242             // or just fill this with an empty packet
243             // if we have to do this too often, the presentation time will
244             // get too close and we're in trouble
245             goto send_empty_packet; // UGLY but effective
246         }
247     } else {
248         m_PacketStat.signal(3);
249         // there are enough frames, so check the time they are intended for
250         // all frames have a certain 'time window' in which they can be sent
251         // this corresponds to the range of the timestamp mechanism:
252         // we can send a packet 15 cycles in advance of the 'presentation time'
253         // in theory we can send the packet up till one cycle before the presentation time,
254         // however this is not very smart.
255        
256         // There are 3 options:
257         // 1) the frame block is too early
258         //      => send an empty packet
259         // 2) the frame block is within the window
260         //      => send it
261         // 3) the frame block is too late
262         //      => discard (and raise xrun?)
263         //         get next block of frames and repeat
264        
265         if (cycles_until_transmit <= max_cycles_to_transmit_early) {
266             m_PacketStat.signal(4);
267             // it's time send the packet
268             goto send_packet; // UGLY but effective
269         } else if (cycles_until_transmit < 0) {
270             // we are too late
271             debugOutput(DEBUG_LEVEL_VERBOSE,
272                         "Too late: CY=%04u, TC=%04u, CUT=%04d, TSP=%011llu (%04u)\n",
273                         cycle,
274                         transmit_at_cycle, cycles_until_transmit,
275                         presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
276
277             // however, if we can send this sufficiently before the presentation
278             // time, it could be harmless.
279             // NOTE: dangerous since the device has no way of reporting that it didn't get
280             //       this packet on time.
281             if ( cycles_until_presentation <= min_cycles_before_presentation ) {
282                 m_PacketStat.signal(5);
283                 // we are not that late and can still try to transmit the packet
284                 goto send_packet; // UGLY but effective
285             } else { // definitely too late
286                 m_PacketStat.signal(6);
287                 // remove the samples
288                 m_data_buffer->dropFrames(m_syt_interval);
289                 // signal some xrun situation ??HERE??
290                 m_xruns++;
291                 // try a new block of frames
292                 goto try_block_of_frames; // UGLY but effective
293             }
294         } else {
295             m_PacketStat.signal(7);
296             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
297                         "Too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
298                         cycle,
299                         transmit_at_cycle, cycles_until_transmit,
300                         transmit_at_time, (unsigned int)TICKS_TO_CYCLES(transmit_at_time),
301                         presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
302             #ifdef DEBUG
303             if (cycles_until_transmit > max_cycles_to_transmit_early + 1) {
304                 debugOutput(DEBUG_LEVEL_VERBOSE,
305                             "Way too early: CY=%04u, TC=%04u, CUT=%04d, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
306                             cycle,
307                             transmit_at_cycle, cycles_until_transmit,
308                             transmit_at_time, (unsigned int)TICKS_TO_CYCLES(transmit_at_time),
309                             presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
310             }
311             #endif
312             // we are too early, send only an empty packet
313             goto send_empty_packet; // UGLY but effective
314         }
315     }
316
317     debugFatal("Should never reach this code!\n");
318     return RAW1394_ISO_ERROR;
319
320 send_empty_packet:
321     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT NONE: CY=%04u, TSP=%011llu (%04u)\n",
322             cycle,
323             presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
324
325     m_dbc += fillNoDataPacketHeader(packet, length);
326     return RAW1394_ISO_DEFER;
327
328 send_packet:
329     if (m_data_buffer->readFrames(m_syt_interval, (char *)(data + 8))) {
330         m_dbc += fillDataPacketHeader(packet, length, presentation_time);
331
332         // process all ports that should be handled on a per-packet base
333         // this is MIDI for AMDTP (due to the need of DBC)
334         if (!encodePacketPorts((quadlet_t *)(data+8), m_syt_interval, packet->dbc)) {
335             debugWarning("Problem encoding Packet Ports\n");
336         }
337
338         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT DATA: CY=%04u, TST=%011llu (%04u), TSP=%011llu (%04u)\n",
339             cycle,
340             transmit_at_time, (unsigned int)TICKS_TO_CYCLES(transmit_at_time),
341             presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
342
343         return RAW1394_ISO_OK;
344     }
345
346 // the ISO AGAIN does not work very well...
347 // try_packet_again:
348 //
349 //     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT RETRY: CY=%04u, TSP=%011llu (%04u)\n",
350 //             cycle,
351 //             presentation_time, (unsigned int)TICKS_TO_CYCLES(presentation_time));
352 //     return RAW1394_ISO_AGAIN;
353
354     // else:
355     debugFatal("This is impossible, since we checked the buffer size before!\n");
356     return RAW1394_ISO_ERROR;
357 }
358
359 unsigned int AmdtpTransmitStreamProcessor::fillDataPacketHeader(
360         struct iec61883_packet *packet, unsigned int* length,
361         uint32_t ts) {
362
363     packet->fdf = m_fdf;
364
365     // convert the timestamp to SYT format
366     uint16_t timestamp_SYT = TICKS_TO_SYT(ts);
367     packet->syt = ntohs(timestamp_SYT);
368
369     *length = m_syt_interval*sizeof(quadlet_t)*m_dimension + 8;
370
371     return m_syt_interval;
372 }
373
374 unsigned int AmdtpTransmitStreamProcessor::fillNoDataPacketHeader(
375         struct iec61883_packet *packet, unsigned int* length) {
376
377     // no-data packets have syt=0xFFFF
378     // and have the usual amount of events as dummy data (?)
379     packet->fdf = IEC61883_FDF_NODATA;
380     packet->syt = 0xffff;
381
382     // FIXME: either make this a setting or choose
383     bool send_payload=true;
384     if(send_payload) {
385         // this means no-data packets with payload (DICE doesn't like that)
386         *length = 2*sizeof(quadlet_t) + m_syt_interval * m_dimension * sizeof(quadlet_t);
387         return m_syt_interval;
388     } else {
389         // dbc is not incremented
390         // this means no-data packets without payload
391         *length = 2*sizeof(quadlet_t);
392         return 0;
393     }
394 }
395
396 bool AmdtpTransmitStreamProcessor::prefill() {
397
398     debugOutput( DEBUG_LEVEL_VERBOSE, "Prefill transmit buffers...\n");
399
400     if(!transferSilence(m_ringbuffer_size_frames)) {
401         debugFatal("Could not prefill transmit stream\n");
402         return false;
403     }
404
405     return true;
406 }
407
408 bool AmdtpTransmitStreamProcessor::reset() {
409
410     debugOutput( DEBUG_LEVEL_VERBOSE, "Resetting...\n");
411
412     // reset the statistics
413     m_PeriodStat.reset();
414     m_PacketStat.reset();
415     m_WakeupStat.reset();
416
417     m_data_buffer->setTickOffset(0);
418
419     // reset all non-device specific stuff
420     // i.e. the iso stream and the associated ports
421     if(!StreamProcessor::reset()) {
422         debugFatal("Could not do base class reset\n");
423         return false;
424     }
425
426     // we should prefill the event buffer
427     if (!prefill()) {
428         debugFatal("Could not prefill buffers\n");
429         return false;
430     }
431
432     return true;
433 }
434
435 bool AmdtpTransmitStreamProcessor::prepare() {
436     m_PeriodStat.setName("XMT PERIOD");
437     m_PacketStat.setName("XMT PACKET");
438     m_WakeupStat.setName("XMT WAKEUP");
439
440     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing (%p)...\n", this);
441
442     // prepare all non-device specific stuff
443     // i.e. the iso stream and the associated ports
444     if(!StreamProcessor::prepare()) {
445         debugFatal("Could not prepare base class\n");
446         return false;
447     }
448
449     switch (m_manager->getNominalRate()) {
450     case 32000:
451         m_syt_interval = 8;
452         m_fdf = IEC61883_FDF_SFC_32KHZ;
453         break;
454     case 44100:
455         m_syt_interval = 8;
456         m_fdf = IEC61883_FDF_SFC_44K1HZ;
457         break;
458     default:
459     case 48000:
460         m_syt_interval = 8;
461         m_fdf = IEC61883_FDF_SFC_48KHZ;
462         break;
463     case 88200:
464         m_syt_interval = 16;
465         m_fdf = IEC61883_FDF_SFC_88K2HZ;
466         break;
467     case 96000:
468         m_syt_interval = 16;
469         m_fdf = IEC61883_FDF_SFC_96KHZ;
470         break;
471     case 176400:
472         m_syt_interval = 32;
473         m_fdf = IEC61883_FDF_SFC_176K4HZ;
474         break;
475     case 192000:
476         m_syt_interval = 32;
477         m_fdf = IEC61883_FDF_SFC_192KHZ;
478         break;
479     }
480
481     iec61883_cip_init (
482         &m_cip_status,
483         IEC61883_FMT_AMDTP,
484         m_fdf,
485         m_manager->getNominalRate(),
486         m_dimension,
487         m_syt_interval);
488
489     // prepare the framerate estimate
490     float ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_manager->getNominalRate());
491     m_ticks_per_frame=ticks_per_frame;
492
493     // initialize internal buffer
494     m_ringbuffer_size_frames=m_manager->getNbBuffers() * m_manager->getPeriodSize();
495
496     assert(m_data_buffer);
497     m_data_buffer->setBufferSize(m_ringbuffer_size_frames * 2);
498     m_data_buffer->setEventSize(sizeof(quadlet_t));
499     m_data_buffer->setEventsPerFrame(m_dimension);
500
501     m_data_buffer->setUpdatePeriod(m_manager->getPeriodSize());
502     m_data_buffer->setNominalRate(ticks_per_frame);
503
504     m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
505
506     m_data_buffer->prepare();
507
508     // set the parameters of ports we can:
509     // we want the audio ports to be period buffered,
510     // and the midi ports to be packet buffered
511     for ( PortVectorIterator it = m_Ports.begin();
512           it != m_Ports.end();
513           ++it )
514     {
515         debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
516         if(!(*it)->setBufferSize(m_manager->getPeriodSize())) {
517             debugFatal("Could not set buffer size to %d\n",m_manager->getPeriodSize());
518             return false;
519         }
520
521
522         switch ((*it)->getPortType()) {
523             case Port::E_Audio:
524                 if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
525                     debugFatal("Could not set signal type to PeriodSignalling");
526                     return false;
527                 }
528                 debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
529                 // buffertype and datatype are dependant on the API
530                 if(!(*it)->setBufferType(Port::E_PointerBuffer)) {
531                     debugFatal("Could not set buffer type");
532                     return false;
533                 }
534                 if(!(*it)->useExternalBuffer(true)) {
535                     debugFatal("Could not set external buffer usage");
536                     return false;
537                 }
538
539                 if(!(*it)->setDataType(Port::E_Float)) {
540                     debugFatal("Could not set data type");
541                     return false;
542                 }
543
544
545                 break;
546             case Port::E_Midi:
547                 if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
548                     debugFatal("Could not set signal type to PeriodSignalling");
549                     return false;
550                 }
551
552                 // we use a timing unit of 10ns
553                 // this makes sure that for the max syt interval
554                 // we don't have rounding, and keeps the numbers low
555                 // we have 1 slot every 8 events
556                 // we have syt_interval events per packet
557                 // => syt_interval/8 slots per packet
558                 // packet rate is 8000pkt/sec => interval=125us
559                 // so the slot interval is (1/8000)/(syt_interval/8)
560                 // or: 1/(1000 * syt_interval) sec
561                 // which is 1e9/(1000*syt_interval) nsec
562                 // or 100000/syt_interval 'units'
563                 // the event interval is fixed to 320us = 32000 'units'
564                 if(!(*it)->useRateControl(true,(100000/m_syt_interval),32000, false)) {
565                     debugFatal("Could not set signal type to PeriodSignalling");
566                     return false;
567                 }
568
569                 // buffertype and datatype are dependant on the API
570                 debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
571                 // buffertype and datatype are dependant on the API
572                 if(!(*it)->setBufferType(Port::E_RingBuffer)) {
573                     debugFatal("Could not set buffer type");
574                     return false;
575                 }
576                 if(!(*it)->setDataType(Port::E_MidiEvent)) {
577                     debugFatal("Could not set data type");
578                     return false;
579                 }
580                 break;
581             default:
582                 debugWarning("Unsupported port type specified\n");
583                 break;
584         }
585     }
586
587     // the API specific settings of the ports should already be set,
588     // as this is called from the processorManager->prepare()
589     // so we can init the ports
590     if(!initPorts()) {
591         debugFatal("Could not initialize ports!\n");
592         return false;
593     }
594
595     if(!preparePorts()) {
596         debugFatal("Could not initialize ports!\n");
597         return false;
598     }
599
600     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepared for:\n");
601     debugOutput( DEBUG_LEVEL_VERBOSE, " Samplerate: %d, FDF: %d, DBS: %d, SYT: %d\n",
602              m_manager->getNominalRate(),m_fdf,m_dimension,m_syt_interval);
603     debugOutput( DEBUG_LEVEL_VERBOSE, " PeriodSize: %d, NbBuffers: %d\n",
604              m_manager->getPeriodSize(), m_manager->getNbBuffers());
605     debugOutput( DEBUG_LEVEL_VERBOSE, " Port: %d, Channel: %d\n",
606              m_port,m_channel);
607
608     return true;
609
610 }
611
612 bool AmdtpTransmitStreamProcessor::prepareForStart() {
613     return true;
614 }
615
616 bool AmdtpTransmitStreamProcessor::prepareForStop() {
617     return true;
618 }
619
620 bool AmdtpTransmitStreamProcessor::prepareForEnable(uint64_t time_to_enable_at) {
621
622     if (!StreamProcessor::prepareForEnable(time_to_enable_at)) {
623         debugError("StreamProcessor::prepareForEnable failed\n");
624         return false;
625     }
626
627     return true;
628 }
629
630 unsigned int
631 AmdtpTransmitStreamProcessor::getPacketsPerPeriod()
632 {
633     return (m_manager->getPeriodSize())/m_syt_interval;
634 }
635
636 bool AmdtpTransmitStreamProcessor::transferSilence(unsigned int nframes) {
637     bool retval;
638     signed int fc;
639     ffado_timestamp_t ts_tail_tmp;
640     uint64_t ts_tail;
641    
642     // prepare a buffer of silence
643     char *dummybuffer=(char *)calloc(sizeof(quadlet_t),nframes*m_dimension);
644     transmitSilenceBlock(dummybuffer, nframes, 0);
645
646    
647     m_data_buffer->getBufferTailTimestamp(&ts_tail_tmp, &fc);
648     if (fc != 0) {
649         debugWarning("Prefilling a buffer that already contains %d frames\n", fc);
650     }
651
652     ts_tail = (uint64_t)ts_tail_tmp;
653     // modify the timestamp such that it makes sense
654     ts_tail = addTicks(ts_tail, (uint64_t)(nframes * getTicksPerFrame()));
655     // add the silence data to the ringbuffer
656     if(m_data_buffer->writeFrames(nframes, dummybuffer, ts_tail)) {
657         retval=true;
658     } else {
659         debugWarning("Could not write to event buffer\n");
660         retval=false;
661     }
662
663     free(dummybuffer);
664
665     return retval;
666 }
667
668 bool AmdtpTransmitStreamProcessor::putFrames(unsigned int nbframes, int64_t ts) {
669     m_PeriodStat.mark(m_data_buffer->getBufferFill());
670     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "AmdtpTransmitStreamProcessor::putFrames(%d, %llu)\n", nbframes, ts);
671
672     // transfer the data
673     m_data_buffer->blockProcessWriteFrames(nbframes, ts);
674
675     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, " New timestamp: %llu\n", ts);
676
677     return true; // FIXME: what about failure?
678 }
679
680 bool AmdtpTransmitStreamProcessor::putFramesDry(unsigned int nbframes, int64_t ts) {
681     m_PeriodStat.mark(m_data_buffer->getBufferFill());
682     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "AmdtpTransmitStreamProcessor::putFramesDry(%d, %llu)\n", nbframes, ts);
683
684     bool retval;
685     char dummybuffer[sizeof(quadlet_t)*nbframes*m_dimension];
686
687     transmitSilenceBlock(dummybuffer, nbframes, 0);
688     // add the silence data to the ringbuffer
689     if(m_data_buffer->writeFrames(nbframes, dummybuffer, ts)) {
690         retval=true;
691     } else {
692         debugWarning("Could not write %u events to event buffer\n", nbframes);
693         retval=false;
694     }
695
696     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, " New timestamp: %llu\n", ts);
697     return retval;
698 }
699
700 /*
701  * write received events to the stream ringbuffers.
702  */
703
704 bool AmdtpTransmitStreamProcessor::processWriteBlock(char *data,
705                        unsigned int nevents, unsigned int offset)
706 {
707     bool no_problem=true;
708
709     for ( PortVectorIterator it = m_PeriodPorts.begin();
710           it != m_PeriodPorts.end();
711           ++it )
712     {
713
714         if((*it)->isDisabled()) {continue;};
715
716         //FIXME: make this into a static_cast when not DEBUG?
717
718         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
719         assert(pinfo); // this should not fail!!
720
721         switch(pinfo->getFormat()) {
722         case AmdtpPortInfo::E_MBLA:
723             if(encodePortToMBLAEvents(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
724                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
725                 no_problem=false;
726             }
727             break;
728         case AmdtpPortInfo::E_SPDIF: // still unimplemented
729             break;
730         default: // ignore
731             break;
732         }
733     }
734     return no_problem;
735
736 }
737
738 int AmdtpTransmitStreamProcessor::transmitSilenceBlock(char *data,
739                        unsigned int nevents, unsigned int offset)
740 {
741     int problem=0;
742
743     for ( PortVectorIterator it = m_PeriodPorts.begin();
744           it != m_PeriodPorts.end();
745           ++it )
746     {
747
748         //FIXME: make this into a static_cast when not DEBUG?
749
750         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
751         assert(pinfo); // this should not fail!!
752
753         switch(pinfo->getFormat()) {
754         case AmdtpPortInfo::E_MBLA:
755             if(encodeSilencePortToMBLAEvents(static_cast<AmdtpAudioPort *>(*it), (quadlet_t *)data, offset, nevents)) {
756                 debugWarning("Could not encode port %s to MBLA events",(*it)->getName().c_str());
757                 problem=1;
758             }
759             break;
760         case AmdtpPortInfo::E_SPDIF: // still unimplemented
761             break;
762         default: // ignore
763             break;
764         }
765     }
766     return problem;
767
768 }
769
770 /**
771  * @brief decode a packet for the packet-based ports
772  *
773  * @param data Packet data
774  * @param nevents number of events in data (including events of other ports & port types)
775  * @param dbc DataBlockCount value for this packet
776  * @return true if all successfull
777  */
778 bool AmdtpTransmitStreamProcessor::encodePacketPorts(quadlet_t *data, unsigned int nevents, unsigned int dbc)
779 {
780     bool ok=true;
781     quadlet_t byte;
782
783     quadlet_t *target_event=NULL;
784     unsigned int j;
785
786     for ( PortVectorIterator it = m_PacketPorts.begin();
787           it != m_PacketPorts.end();
788           ++it )
789     {
790
791 #ifdef DEBUG
792         AmdtpPortInfo *pinfo=dynamic_cast<AmdtpPortInfo *>(*it);
793         assert(pinfo); // this should not fail!!
794
795         // the only packet type of events for AMDTP is MIDI in mbla
796         assert(pinfo->getFormat()==AmdtpPortInfo::E_Midi);
797 #endif
798
799         AmdtpMidiPort *mp=static_cast<AmdtpMidiPort *>(*it);
800
801         // we encode this directly (no function call) due to the high frequency
802         /* idea:
803         spec says: current_midi_port=(dbc+j)%8;
804         => if we start at (dbc+stream->location-1)%8,
805         we'll start at the right event for the midi port.
806         => if we increment j with 8, we stay at the right event.
807         */
808         // FIXME: as we know in advance how big a packet is (syt_interval) we can
809         //        predict how much loops will be present here
810         // first prefill the buffer with NO_DATA's on all time muxed channels
811
812         for(j = (dbc & 0x07)+mp->getLocation(); j < nevents; j += 8) {
813            
814             quadlet_t tmpval;
815            
816             target_event=(quadlet_t *)(data + ((j * m_dimension) + mp->getPosition()));
817            
818             if(mp->canRead()) { // we can send a byte
819                 mp->readEvent(&byte);
820                 byte &= 0xFF;
821                 tmpval=htonl(
822                     IEC61883_AM824_SET_LABEL((byte)<<16,
823                                              IEC61883_AM824_LABEL_MIDI_1X));
824
825                 debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "MIDI port %s, pos=%d, loc=%d, dbc=%d, nevents=%d, dim=%d\n",
826                     mp->getName().c_str(), mp->getPosition(), mp->getLocation(), dbc, nevents, m_dimension);
827                 debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "base=%p, target=%p, value=%08X\n",
828                     data, target_event, tmpval);
829                    
830             } else {
831                 // can't send a byte, either because there is no byte,
832                 // or because this would exceed the maximum rate
833                 tmpval=htonl(
834                     IEC61883_AM824_SET_LABEL(0,IEC61883_AM824_LABEL_MIDI_NO_DATA));
835             }
836            
837             *target_event=tmpval;
838         }
839
840     }
841
842     return ok;
843 }
844
845
846 int AmdtpTransmitStreamProcessor::encodePortToMBLAEvents(AmdtpAudioPort *p, quadlet_t *data,
847                        unsigned int offset, unsigned int nevents)
848 {
849     unsigned int j=0;
850
851     quadlet_t *target_event;
852
853     target_event=(quadlet_t *)(data + p->getPosition());
854
855     switch(p->getDataType()) {
856         default:
857         case Port::E_Int24:
858             {
859                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
860
861                 assert(nevents + offset <= p->getBufferSize());
862
863                 buffer+=offset;
864
865                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
866                     *target_event = htonl((*(buffer) & 0x00FFFFFF) | 0x40000000);
867                     buffer++;
868                     target_event += m_dimension;
869                 }
870             }
871             break;
872         case Port::E_Float:
873             {
874                 const float multiplier = (float)(0x7FFFFF00);
875                 float *buffer=(float *)(p->getBufferAddress());
876
877                 assert(nevents + offset <= p->getBufferSize());
878
879                 buffer+=offset;
880
881                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
882
883                     // don't care for overflow
884                     float v = *buffer * multiplier;  // v: -231 .. 231
885                     unsigned int tmp = ((int)v);
886                     *target_event = htonl((tmp >> 8) | 0x40000000);
887
888                     buffer++;
889                     target_event += m_dimension;
890                 }
891             }
892             break;
893     }
894
895     return 0;
896 }
897 int AmdtpTransmitStreamProcessor::encodeSilencePortToMBLAEvents(AmdtpAudioPort *p, quadlet_t *data,
898                        unsigned int offset, unsigned int nevents)
899 {
900     unsigned int j=0;
901
902     quadlet_t *target_event;
903
904     target_event=(quadlet_t *)(data + p->getPosition());
905
906     switch(p->getDataType()) {
907         default:
908         case Port::E_Int24:
909         case Port::E_Float:
910             {
911                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
912                     *target_event = htonl(0x40000000);
913                     target_event += m_dimension;
914                 }
915             }
916             break;
917     }
918
919     return 0;
920 }
921
922 } // end of namespace Streaming
Note: See TracBrowser for help on using the browser.