root/trunk/libffado/src/libstreaming/generic/StreamProcessor.cpp

Revision 797, 62.9 kB (checked in by ppalmers, 13 years ago)

parameters for better latency performance

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 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 3 of the License, or
12  * (at your option) any later version.
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
26 #include "StreamProcessor.h"
27 #include "../StreamProcessorManager.h"
28
29 #include "devicemanager.h"
30
31 #include "libieee1394/ieee1394service.h"
32 #include "libieee1394/IsoHandlerManager.h"
33 #include "libieee1394/cycletimer.h"
34
35 #include "libutil/Time.h"
36
37 #include "libutil/Atomic.h"
38
39 #include <assert.h>
40 #include <math.h>
41
42 namespace Streaming {
43
44 IMPL_DEBUG_MODULE( StreamProcessor, StreamProcessor, DEBUG_LEVEL_VERBOSE );
45
46 StreamProcessor::StreamProcessor(FFADODevice &parent, enum eProcessorType type)
47     : m_processor_type ( type )
48     , m_state( ePS_Created )
49     , m_next_state( ePS_Invalid )
50     , m_cycle_to_switch_state( 0 )
51     , m_Parent( parent )
52     , m_1394service( parent.get1394Service() ) // local cache
53     , m_IsoHandlerManager( parent.get1394Service().getIsoHandlerManager() ) // local cache
54     , m_StreamProcessorManager( m_Parent.getDeviceManager().getStreamProcessorManager() ) // local cache
55     , m_channel( -1 )
56     , m_dropped(0)
57     , m_last_timestamp(0)
58     , m_last_timestamp2(0)
59     , m_scratch_buffer( NULL )
60     , m_scratch_buffer_size_bytes( 0 )
61     , m_ticks_per_frame( 0 )
62     , m_last_cycle( -1 )
63     , m_sync_delay( 0 )
64     , m_in_xrun( false )
65 {
66     // create the timestamped buffer and register ourselves as its client
67     m_data_buffer = new Util::TimestampedBuffer(this);
68 }
69
70 StreamProcessor::~StreamProcessor() {
71     m_StreamProcessorManager.unregisterProcessor(this);
72     if(!m_IsoHandlerManager.unregisterStream(this)) {
73         debugOutput(DEBUG_LEVEL_VERBOSE,"Could not unregister stream processor with the Iso manager\n");
74     }
75
76     if (m_data_buffer) delete m_data_buffer;
77     if (m_scratch_buffer) delete[] m_scratch_buffer;
78 }
79
80 uint64_t StreamProcessor::getTimeNow() {
81     return m_1394service.getCycleTimerTicks();
82 }
83
84 int StreamProcessor::getMaxFrameLatency() {
85     if (getType() == ePT_Receive) {
86         return (int)(m_IsoHandlerManager.getPacketLatencyForStream( this ) * TICKS_PER_CYCLE);
87     } else {
88         return (int)(m_IsoHandlerManager.getPacketLatencyForStream( this ) * TICKS_PER_CYCLE);
89     }
90 }
91
92 unsigned int
93 StreamProcessor::getNominalPacketsNeeded(unsigned int nframes)
94 {
95     unsigned int nominal_frames_per_second
96                     = m_StreamProcessorManager.getNominalRate();
97     uint64_t nominal_ticks_per_frame = TICKS_PER_SECOND / nominal_frames_per_second;
98     uint64_t nominal_ticks = nominal_ticks_per_frame * nframes;
99     uint64_t nominal_packets = nominal_ticks / TICKS_PER_CYCLE;
100     return nominal_packets;
101 }
102
103 unsigned int
104 StreamProcessor::getPacketsPerPeriod()
105 {
106     return getNominalPacketsNeeded(m_StreamProcessorManager.getPeriodSize());
107 }
108
109 unsigned int
110 StreamProcessor::getNbPacketsIsoXmitBuffer()
111 {
112     // the target is to have all of the transmit buffer (at period transfer) as ISO packets
113     // when one period is received, there will be approx (NbBuffers - 1) * period_size frames
114     // in the transmit buffer (the others are still to be put into the xmit frame buffer)
115     unsigned int packets_to_prebuffer = (getPacketsPerPeriod() * (m_StreamProcessorManager.getNbBuffers()-1));
116     debugOutput(DEBUG_LEVEL_VERBOSE, "Nominal prebuffer: %u\n", packets_to_prebuffer);
117    
118     // however we have to take into account the fact that there is some sync delay
119     // we assume that the SPM has indicated
120     // HACK: this counts on the fact that the latency for this stream will be the same as the
121     //       latency for the receive sync source
122     unsigned int est_sync_delay = getPacketsPerPeriod() / MINIMUM_INTERRUPTS_PER_PERIOD;
123     est_sync_delay += STREAMPROCESSORMANAGER_SIGNAL_DELAY_TICKS / TICKS_PER_CYCLE;
124     packets_to_prebuffer -= est_sync_delay;
125     debugOutput(DEBUG_LEVEL_VERBOSE, " correct for sync delay (%d): %u\n",
126                                      est_sync_delay,
127                                      packets_to_prebuffer);
128    
129     // only queue a part of the theoretical max in order not to have too much 'not ready' cycles
130     packets_to_prebuffer = (packets_to_prebuffer * MAX_ISO_XMIT_BUFFER_FILL_PCT * 1000) / 100000;
131     debugOutput(DEBUG_LEVEL_VERBOSE, " reduce to %d%%: %u\n",
132                                      MAX_ISO_XMIT_BUFFER_FILL_PCT, packets_to_prebuffer);
133    
134     return packets_to_prebuffer;
135 }
136
137 /***********************************************
138  * Buffer management and manipulation          *
139  ***********************************************/
140 void StreamProcessor::flush() {
141     m_IsoHandlerManager.flushHandlerForStream(this);
142 }
143
144 int StreamProcessor::getBufferFill() {
145     return m_data_buffer->getBufferFill();
146 }
147
148 int64_t
149 StreamProcessor::getTimeUntilNextPeriodSignalUsecs()
150 {
151     uint64_t time_at_period=getTimeAtPeriod();
152
153     // we delay the period signal with the sync delay
154     // this makes that the period signals lag a little compared to reality
155     // ISO buffering causes the packets to be received at max
156     // m_handler->getWakeupInterval() later than the time they were received.
157     // hence their payload is available this amount of time later. However, the
158     // period boundary is predicted based upon earlier samples, and therefore can
159     // pass before these packets are processed. Adding this extra term makes that
160     // the period boundary is signalled later
161     time_at_period = addTicks(time_at_period, m_StreamProcessorManager.getSyncSource().getSyncDelay());
162
163     uint64_t cycle_timer=m_1394service.getCycleTimerTicks();
164
165     // calculate the time until the next period
166     int32_t until_next=diffTicks(time_at_period,cycle_timer);
167
168     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "=> TAP=%11llu, CTR=%11llu, UTN=%11ld\n",
169         time_at_period, cycle_timer, until_next
170         );
171
172     // now convert to usecs
173     // don't use the mapping function because it only works
174     // for absolute times, not the relative time we are
175     // using here (which can also be negative).
176     return (int64_t)(((float)until_next) / TICKS_PER_USEC);
177 }
178
179 void
180 StreamProcessor::setSyncDelay(int d) {
181     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "Setting SP %p SyncDelay to %d ticks\n", this, d);
182     m_sync_delay = d;
183 }
184
185 uint64_t
186 StreamProcessor::getTimeAtPeriodUsecs()
187 {
188     return (uint64_t)((float)getTimeAtPeriod() * TICKS_PER_USEC);
189 }
190
191 uint64_t
192 StreamProcessor::getTimeAtPeriod()
193 {
194     if (getType() == ePT_Receive) {
195         ffado_timestamp_t next_period_boundary=m_data_buffer->getTimestampFromHead(m_StreamProcessorManager.getPeriodSize());
196    
197         #ifdef DEBUG
198         ffado_timestamp_t ts;
199         signed int fc;
200         m_data_buffer->getBufferTailTimestamp(&ts,&fc);
201    
202         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "=> NPD="TIMESTAMP_FORMAT_SPEC", LTS="TIMESTAMP_FORMAT_SPEC", FC=%5u, TPF=%f\n",
203             next_period_boundary, ts, fc, getTicksPerFrame()
204             );
205         #endif
206         return (uint64_t)next_period_boundary;
207     } else {
208         ffado_timestamp_t next_period_boundary=m_data_buffer->getTimestampFromTail((m_StreamProcessorManager.getNbBuffers()-1) * m_StreamProcessorManager.getPeriodSize());
209    
210         #ifdef DEBUG
211         ffado_timestamp_t ts;
212         signed int fc;
213         m_data_buffer->getBufferTailTimestamp(&ts,&fc);
214    
215         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "=> NPD="TIMESTAMP_FORMAT_SPEC", LTS="TIMESTAMP_FORMAT_SPEC", FC=%5u, TPF=%f\n",
216             next_period_boundary, ts, fc, getTicksPerFrame()
217             );
218         #endif
219         return (uint64_t)next_period_boundary;
220     }
221 }
222
223 float
224 StreamProcessor::getTicksPerFrame()
225 {
226     assert(m_data_buffer != NULL);
227     return m_data_buffer->getRate();
228 }
229
230 bool
231 StreamProcessor::canClientTransferFrames(unsigned int nbframes)
232 {
233     bool can_transfer;
234     unsigned int fc = m_data_buffer->getFrameCounter();
235     if (getType() == ePT_Receive) {
236         can_transfer = (fc >= nbframes);
237     } else {
238         // there has to be enough space to put the frames in
239         can_transfer = m_data_buffer->getBufferSize() - fc > nbframes;
240         // or the buffer is transparent
241         can_transfer |= m_data_buffer->isTransparent();
242     }
243    
244     #ifdef DEBUG
245     if (!can_transfer) {
246         debugWarning("(%p, %s) cannot transfer since fc == %u, nbframes == %u\n",
247             this, ePTToString(getType()), fc, nbframes);
248     }
249     #endif
250    
251     return can_transfer;
252 }
253
254 /***********************************************
255  * I/O API                                     *
256  ***********************************************/
257
258 // Packet transfer API
259 enum raw1394_iso_disposition
260 StreamProcessor::putPacket(unsigned char *data, unsigned int length,
261                            unsigned char channel, unsigned char tag, unsigned char sy,
262                            unsigned int cycle, unsigned int dropped) {
263     if(m_last_cycle == -1) {
264         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive (cycle = %u)\n", getTypeString(), this, cycle);
265     }
266
267     int dropped_cycles = 0;
268     if (m_last_cycle != (int)cycle && m_last_cycle != -1) {
269         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
270         if (dropped_cycles < 0) {
271             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d\n",
272                          this, dropped_cycles, cycle, m_last_cycle, dropped);
273         }
274         if (dropped_cycles > 0) {
275             debugWarning("(%p) dropped %d packets on cycle %u, 'dropped'=%u, cycle=%d, m_last_cycle=%d\n",
276                 this, dropped_cycles, cycle, dropped, cycle, m_last_cycle);
277             m_dropped += dropped_cycles;
278             m_in_xrun = true;
279             //flushDebugOutput();
280             //assert(0);
281         }
282     }
283     m_last_cycle = cycle;
284
285     // bypass based upon state
286     if (m_state == ePS_Invalid) {
287         debugError("Should not have state %s\n", ePSToString(m_state) );
288         return RAW1394_ISO_ERROR;
289     }
290     if (m_state == ePS_Created) {
291         return RAW1394_ISO_DEFER;
292     }
293
294     // store the previous timestamp
295     m_last_timestamp2 = m_last_timestamp;
296
297     // NOTE: synchronized switching is restricted to a 0.5 sec span (4000 cycles)
298     //       it happens on the first 'good' cycle for the wait condition
299     //       or on the first received cycle that is received afterwards (might be a problem)
300
301     // check whether we are waiting for a stream to be disabled
302     if(m_state == ePS_WaitingForStreamDisable) {
303         // we then check whether we have to switch on this cycle
304         if (diffCycles(cycle, m_cycle_to_switch_state) >= 0) {
305             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to DryRunning\n");
306             m_next_state = ePS_DryRunning;
307             if (!updateState()) { // we are allowed to change the state directly
308                 debugError("Could not update state!\n");
309                 return RAW1394_ISO_ERROR;
310             }
311         } else {
312             // not time to disable yet
313         }
314         // the received data can be discarded while waiting for the stream
315         // to be disabled
316         return RAW1394_ISO_OK;
317     }
318
319     // check whether we are waiting for a stream to be enabled
320     else if(m_state == ePS_WaitingForStreamEnable) {
321         // we then check whether we have to switch on this cycle
322         if (diffCycles(cycle, m_cycle_to_switch_state) >= 0) {
323             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to Running\n");
324             m_next_state = ePS_Running;
325             if (!updateState()) { // we are allowed to change the state directly
326                 debugError("Could not update state!\n");
327                 return RAW1394_ISO_ERROR;
328             }
329         } else {
330             // not time to enable yet
331         }
332         // we are dryRunning hence data should be processed in any case
333     }
334
335     // check the packet header
336     enum eChildReturnValue result = processPacketHeader(data, length, channel, tag, sy, cycle, dropped_cycles);
337     if (result == eCRV_OK) {
338         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "RECV: CY=%04u TS=%011llu\n",
339                 cycle, m_last_timestamp);
340         // update some accounting
341         m_last_good_cycle = cycle;
342         m_last_dropped = dropped_cycles;
343
344         // check whether we are waiting for a stream to startup
345         // this requires that the packet is good
346         if(m_state == ePS_WaitingForStream) {
347             // since we have a packet with an OK header,
348             // we can indicate that the stream started up
349
350             // we then check whether we have to switch on this cycle
351             if (diffCycles(cycle, m_cycle_to_switch_state) >= 0) {
352                 debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to DryRunning due to good packet\n");
353                 // hence go to the dryRunning state
354                 m_next_state = ePS_DryRunning;
355                 if (!updateState()) { // we are allowed to change the state directly
356                     debugError("Could not update state!\n");
357                     return RAW1394_ISO_ERROR;
358                 }
359             } else {
360                 // not time (yet) to switch state
361             }
362             // in both cases we don't want to process the data
363             return RAW1394_ISO_OK;
364         }
365
366         // check whether a state change has been requested
367         // note that only the wait state changes are synchronized with the cycles
368         else if(m_state != m_next_state) {
369             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state from %s to %s\n",
370                                              ePSToString(m_state), ePSToString(m_next_state));
371             // execute the requested change
372             if (!updateState()) { // we are allowed to change the state directly
373                 debugError("Could not update state!\n");
374                 return RAW1394_ISO_ERROR;
375             }
376         }
377
378         // handle dropped cycles
379         if(dropped_cycles) {
380             // they represent a discontinuity in the timestamps, and hence are
381             // to be dealt with
382             debugWarning("(%p) Correcting timestamp for dropped cycles, discarding packet...\n", this);
383             m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
384             if (m_state == ePS_Running) {
385                 // this is an xrun situation
386                 m_in_xrun = true;
387                 debugWarning("Should update state to WaitingForStreamDisable due to dropped packet xrun\n");
388                 m_cycle_to_switch_state = cycle + 1; // switch in the next cycle
389                 m_next_state = ePS_WaitingForStreamDisable;
390                 // execute the requested change
391                 if (!updateState()) { // we are allowed to change the state directly
392                     debugError("Could not update state!\n");
393                     return RAW1394_ISO_ERROR;
394                 }
395                 return RAW1394_ISO_DEFER;
396             }
397         }
398
399         // for all states that reach this we are allowed to
400         // do protocol specific data reception
401         enum eChildReturnValue result2 = processPacketData(data, length, channel, tag, sy, cycle, dropped_cycles);
402
403         // if an xrun occured, switch to the dryRunning state and
404         // allow for the xrun to be picked up
405         if (result2 == eCRV_XRun) {
406             debugWarning("processPacketData xrun\n");
407             m_in_xrun = true;
408             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to WaitingForStreamDisable due to data xrun\n");
409             m_cycle_to_switch_state = cycle+1; // switch in the next cycle
410             m_next_state = ePS_WaitingForStreamDisable;
411             // execute the requested change
412             if (!updateState()) { // we are allowed to change the state directly
413                 debugError("Could not update state!\n");
414                 return RAW1394_ISO_ERROR;
415             }
416             return RAW1394_ISO_DEFER;
417         } else if(result2 == eCRV_OK) {
418             // no problem here
419             return RAW1394_ISO_OK;
420         } else {
421             debugError("Invalid response\n");
422             return RAW1394_ISO_ERROR;
423         }
424     } else if(result == eCRV_Invalid) {
425         // apparently we don't have to do anything when the packets are not valid
426         return RAW1394_ISO_OK;
427     } else {
428         debugError("Invalid response\n");
429         return RAW1394_ISO_ERROR;
430     }
431     debugError("reached the unreachable\n");
432     return RAW1394_ISO_ERROR;
433 }
434
435 enum raw1394_iso_disposition
436 StreamProcessor::getPacket(unsigned char *data, unsigned int *length,
437                            unsigned char *tag, unsigned char *sy,
438                            int cycle, unsigned int dropped, unsigned int max_length) {
439     if (cycle<0) {
440         *tag = 0;
441         *sy = 0;
442         *length = 0;
443         return RAW1394_ISO_OK;
444     }
445
446     if(m_last_cycle == -1) {
447         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive (cycle = %d)\n", getTypeString(), this, cycle);
448     }
449
450     int dropped_cycles = 0;
451     if (m_last_cycle != cycle && m_last_cycle != -1) {
452         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
453         if (dropped_cycles < 0) {
454             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d\n",
455                          this, dropped_cycles, cycle, m_last_cycle, dropped);
456         }
457         if (dropped_cycles > 0) {
458             debugWarning("(%p) dropped %d packets on cycle %u (last_cycle=%u, dropped=%d)\n", this, dropped_cycles, cycle, m_last_cycle, dropped);
459             m_dropped += dropped_cycles;
460 //             flushDebugOutput();
461 //             assert(0);
462         }
463     }
464     if (cycle >= 0) {
465         m_last_cycle = cycle;
466     }
467
468     // bypass based upon state
469     if (m_state == ePS_Invalid) {
470         debugError("Should not have state %s\n", ePSToString(m_state) );
471         return RAW1394_ISO_ERROR;
472     }
473     if (m_state == ePS_Created) {
474         *tag = 0;
475         *sy = 0;
476         *length = 0;
477         return RAW1394_ISO_DEFER;
478     }
479
480     // normal processing
481     // note that we can't use getCycleTimer directly here,
482     // because packets are queued in advance. This means that
483     // we the packet we are constructing will be sent out
484     // on 'cycle', not 'now'.
485     unsigned int ctr = m_1394service.getCycleTimer();
486     int now_cycles = (int)CYCLE_TIMER_GET_CYCLES(ctr);
487
488     // the difference between the cycle this
489     // packet is intended for and 'now'
490     int cycle_diff = diffCycles(cycle, now_cycles);
491
492     if(cycle_diff < 0 && (m_state == ePS_Running || m_state == ePS_DryRunning)) {
493         debugWarning("Requesting packet for cycle %04d which is in the past (now=%04dcy)\n",
494             cycle, now_cycles);
495         if(m_state == ePS_Running) {
496             debugShowBackLogLines(200);
497 //             flushDebugOutput();
498 //             assert(0);
499             debugWarning("generatePacketData xrun\n");
500             m_in_xrun = true;
501             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to WaitingForStreamDisable due to data xrun\n");
502             m_next_state = ePS_WaitingForStreamDisable;
503             // execute the requested change
504             if (!updateState()) { // we are allowed to change the state directly
505                 debugError("Could not update state!\n");
506                 return RAW1394_ISO_ERROR;
507             }
508             goto send_empty_packet;
509         }
510     }
511
512     // store the previous timestamp
513     m_last_timestamp2 = m_last_timestamp;
514
515     // NOTE: synchronized switching is restricted to a 0.5 sec span (4000 cycles)
516     //       it happens on the first 'good' cycle for the wait condition
517     //       or on the first received cycle that is received afterwards (might be a problem)
518
519     // check whether we are waiting for a stream to be disabled
520     if(m_state == ePS_WaitingForStreamDisable) {
521         // we then check whether we have to switch on this cycle
522         if (diffCycles(cycle, m_cycle_to_switch_state) >= 0) {
523             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to DryRunning\n");
524             m_next_state = ePS_DryRunning;
525             if (!updateState()) { // we are allowed to change the state directly
526                 debugError("Could not update state!\n");
527                 return RAW1394_ISO_ERROR;
528             }
529         } else {
530             // not time to disable yet
531         }
532     }
533     // check whether we are waiting for a stream to be enabled
534     else if(m_state == ePS_WaitingForStreamEnable) {
535         // we then check whether we have to switch on this cycle
536         if (diffCycles(cycle, m_cycle_to_switch_state) >= 0) {
537             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to Running\n");
538             m_next_state = ePS_Running;
539             if (!updateState()) { // we are allowed to change the state directly
540                 debugError("Could not update state!\n");
541                 return RAW1394_ISO_ERROR;
542             }
543         } else {
544             // not time to enable yet
545         }
546         // we are dryRunning hence data should be processed in any case
547     }
548     // check whether we are waiting for a stream to startup
549     else if(m_state == ePS_WaitingForStream) {
550         // as long as the cycle parameter is not in sync with
551         // the current time, the stream is considered not
552         // to be 'running'
553         // we then check whether we have to switch on this cycle
554         if ((cycle_diff >= 0) && (diffCycles(cycle, m_cycle_to_switch_state) >= 0)) {
555             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to WaitingForStream to DryRunning\n");
556             // hence go to the dryRunning state
557             m_next_state = ePS_DryRunning;
558             if (!updateState()) { // we are allowed to change the state directly
559                 debugError("Could not update state!\n");
560                 return RAW1394_ISO_ERROR;
561             }
562         } else {
563             // not time (yet) to switch state
564         }
565     }
566     else if(m_state == ePS_Running) {
567         // check the packet header
568         enum eChildReturnValue result = generatePacketHeader(data, length, tag, sy, cycle, dropped_cycles, max_length);
569         if (result == eCRV_Packet || result == eCRV_Defer) {
570             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT: CY=%04u TS=%011llu\n",
571                     cycle, m_last_timestamp);
572             // update some accounting
573             m_last_good_cycle = cycle;
574             m_last_dropped = dropped_cycles;
575
576             // check whether a state change has been requested
577             // note that only the wait state changes are synchronized with the cycles
578             if(m_state != m_next_state) {
579                 debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state from %s to %s\n",
580                                                 ePSToString(m_state), ePSToString(m_next_state));
581                 // execute the requested change
582                 if (!updateState()) { // we are allowed to change the state directly
583                     debugError("Could not update state!\n");
584                     return RAW1394_ISO_ERROR;
585                 }
586             }
587
588             enum eChildReturnValue result2 = generatePacketData(data, length, tag, sy, cycle, dropped_cycles, max_length);
589             // if an xrun occured, switch to the dryRunning state and
590             // allow for the xrun to be picked up
591             if (result2 == eCRV_XRun) {
592                 debugWarning("generatePacketData xrun\n");
593                 m_in_xrun = true;
594                 debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to WaitingForStreamDisable due to data xrun\n");
595                 m_cycle_to_switch_state = cycle+1; // switch in the next cycle
596                 m_next_state = ePS_WaitingForStreamDisable;
597                 // execute the requested change
598                 if (!updateState()) { // we are allowed to change the state directly
599                     debugError("Could not update state!\n");
600                     return RAW1394_ISO_ERROR;
601                 }
602                 goto send_empty_packet;
603             }
604             // skip queueing packets if we detect that there are not enough frames
605             // available
606             if(result2 == eCRV_Defer || result == eCRV_Defer)
607                 return RAW1394_ISO_DEFER;
608             else
609                 return RAW1394_ISO_OK;
610         } else if (result == eCRV_XRun) { // pick up the possible xruns
611             debugWarning("generatePacketHeader xrun\n");
612             m_in_xrun = true;
613             debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state to WaitingForStreamDisable due to header xrun\n");
614             m_next_state = ePS_WaitingForStreamDisable;
615             // execute the requested change
616             if (!updateState()) { // we are allowed to change the state directly
617                 debugError("Could not update state!\n");
618                 return RAW1394_ISO_ERROR;
619             }
620         } else if (result == eCRV_EmptyPacket) {
621             if(m_state != m_next_state) {
622                 debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state from %s to %s\n",
623                                                 ePSToString(m_state), ePSToString(m_next_state));
624                 // execute the requested change
625                 if (!updateState()) { // we are allowed to change the state directly
626                     debugError("Could not update state!\n");
627                     return RAW1394_ISO_ERROR;
628                 }
629             }
630             goto send_empty_packet;
631         } else if (result == eCRV_Again) {
632             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "have to retry cycle %d\n", cycle);
633             if(m_state != m_next_state) {
634                 debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state from %s to %s\n",
635                                                 ePSToString(m_state), ePSToString(m_next_state));
636                 // execute the requested change
637                 if (!updateState()) { // we are allowed to change the state directly
638                     debugError("Could not update state!\n");
639                     return RAW1394_ISO_ERROR;
640                 }
641             }
642             usleep(125); // only when using thread-per-handler
643             return RAW1394_ISO_AGAIN;
644 //             generateSilentPacketHeader(data, length, tag, sy, cycle, dropped_cycles, max_length);
645 //             generateSilentPacketData(data, length, tag, sy, cycle, dropped_cycles, max_length);
646 //             return RAW1394_ISO_DEFER;
647         } else {
648             debugError("Invalid return value: %d\n", result);
649             return RAW1394_ISO_ERROR;
650         }
651     }
652     // we are not running, so send an empty packet
653     // we should generate a valid packet any time
654 send_empty_packet:
655     // note that only the wait state changes are synchronized with the cycles
656     if(m_state != m_next_state) {
657         debugOutput(DEBUG_LEVEL_VERBOSE, "Should update state from %s to %s\n",
658                                         ePSToString(m_state), ePSToString(m_next_state));
659         // execute the requested change
660         if (!updateState()) { // we are allowed to change the state directly
661             debugError("Could not update state!\n");
662             return RAW1394_ISO_ERROR;
663         }
664     }
665
666     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "XMIT EMPTY: CY=%04u\n", cycle);
667     generateSilentPacketHeader(data, length, tag, sy, cycle, dropped_cycles, max_length);
668     generateSilentPacketData(data, length, tag, sy, cycle, dropped_cycles, max_length);
669     return RAW1394_ISO_OK;
670 }
671
672
673 // Frame Transfer API
674 /**
675  * Transfer a block of frames from the event buffer to the port buffers
676  * @param nbframes number of frames to transfer
677  * @param ts the timestamp that the LAST frame in the block should have
678  * @return
679  */
680 bool StreamProcessor::getFrames(unsigned int nbframes, int64_t ts) {
681     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "%p.getFrames(%d, %11llu)", nbframes, ts);
682     assert( getType() == ePT_Receive );
683     if(isDryRunning()) return getFramesDry(nbframes, ts);
684     else return getFramesWet(nbframes, ts);
685 }
686
687 bool StreamProcessor::getFramesWet(unsigned int nbframes, int64_t ts) {
688 // FIXME: this should be done somewhere else
689 #ifdef DEBUG
690     uint64_t ts_expected;
691     signed int fc;
692     int32_t lag_ticks;
693     float lag_frames;
694
695     // in order to sync up multiple received streams, we should
696     // use the ts parameter. It specifies the time of the block's
697     // last sample.
698     float srate = m_StreamProcessorManager.getSyncSource().getTicksPerFrame();
699     assert(srate != 0.0);
700     int64_t this_block_length_in_ticks = (int64_t)(((float)nbframes) * srate);
701
702     ffado_timestamp_t ts_head_tmp;
703     m_data_buffer->getBufferHeadTimestamp(&ts_head_tmp, &fc);
704     ts_expected = addTicks((uint64_t)ts_head_tmp, this_block_length_in_ticks);
705
706     lag_ticks = diffTicks(ts, ts_expected);
707     lag_frames = (((float)lag_ticks) / srate);
708     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "stream (%p): drifts %6d ticks = %10.5f frames (rate=%10.5f), %lld, %llu, %d\n",
709                  this, lag_ticks, lag_frames, srate, ts, ts_expected, fc);
710     if (lag_frames >= 1.0) {
711         // the stream lags
712         debugWarning( "stream (%p): lags  with %6d ticks = %10.5f frames (rate=%10.5f), %lld, %llu, %d\n",
713                       this, lag_ticks, lag_frames, srate, ts, ts_expected, fc);
714     } else if (lag_frames <= -1.0) {
715         // the stream leads
716         debugWarning( "stream (%p): leads with %6d ticks = %10.5f frames (rate=%10.5f), %lld, %llu, %d\n",
717                       this, lag_ticks, lag_frames, srate, ts, ts_expected, fc);
718     }
719 #endif
720     // ask the buffer to process nbframes of frames
721     // using it's registered client's processReadBlock(),
722     // which should be ours
723     m_data_buffer->blockProcessReadFrames(nbframes);
724     return true;
725 }
726
727 bool StreamProcessor::getFramesDry(unsigned int nbframes, int64_t ts)
728 {
729     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "stream (%p): dry run %d frames (@ ts=%lld)\n",
730                  this, nbframes, ts);
731     // dry run on this side means that we put silence in all enabled ports
732     // since there is do data put into the ringbuffer in the dry-running state
733     return provideSilenceBlock(nbframes, 0);
734 }
735
736 bool
737 StreamProcessor::dropFrames(unsigned int nbframes, int64_t ts)
738 {
739     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "StreamProcessor::dropFrames(%d, %lld)\n", nbframes, ts);
740     return m_data_buffer->dropFrames(nbframes);
741 }
742
743 bool StreamProcessor::putFrames(unsigned int nbframes, int64_t ts)
744 {
745     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "%p.putFrames(%d, %11llu)", nbframes, ts);
746     assert( getType() == ePT_Transmit );
747     if(isDryRunning()) return putFramesDry(nbframes, ts);
748     else return putFramesWet(nbframes, ts);
749 }
750
751 bool
752 StreamProcessor::putFramesWet(unsigned int nbframes, int64_t ts)
753 {
754     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "StreamProcessor::putFramesWet(%d, %llu)\n", nbframes, ts);
755     // transfer the data
756     m_data_buffer->blockProcessWriteFrames(nbframes, ts);
757     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, " New timestamp: %llu\n", ts);
758     return true; // FIXME: what about failure?
759 }
760
761 bool
762 StreamProcessor::putFramesDry(unsigned int nbframes, int64_t ts)
763 {
764     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "StreamProcessor::putFramesDry(%d, %llu)\n", nbframes, ts);
765     // do nothing
766     return true;
767 }
768
769 bool
770 StreamProcessor::putSilenceFrames(unsigned int nbframes, int64_t ts)
771 {
772     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE, "StreamProcessor::putSilenceFrames(%d, %llu)\n", nbframes, ts);
773
774     size_t bytes_per_frame = getEventSize() * getEventsPerFrame();
775     unsigned int scratch_buffer_size_frames = m_scratch_buffer_size_bytes / bytes_per_frame;
776
777     if (nbframes > scratch_buffer_size_frames) {
778         debugError("nframes (%u) > scratch_buffer_size_frames (%u)\n",
779                    nbframes, scratch_buffer_size_frames);
780     }
781
782     assert(m_scratch_buffer);
783     if(!transmitSilenceBlock((char *)m_scratch_buffer, nbframes, 0)) {
784         debugError("Could not prepare silent block\n");
785         return false;
786     }
787     if(!m_data_buffer->writeFrames(nbframes, (char *)m_scratch_buffer, ts)) {
788         debugError("Could not write silent block\n");
789         return false;
790     }
791     return true;
792 }
793
794 bool
795 StreamProcessor::shiftStream(int nbframes)
796 {
797     if(nbframes == 0) return true;
798     if(nbframes > 0) {
799         return m_data_buffer->dropFrames(nbframes);
800     } else {
801         bool result = true;
802         while(nbframes++) {
803             result &= m_data_buffer->writeDummyFrame();
804         }
805         return result;
806     }
807 }
808
809 /**
810  * @brief write silence events to the stream ringbuffers.
811  */
812 bool StreamProcessor::provideSilenceBlock(unsigned int nevents, unsigned int offset)
813 {
814     bool no_problem=true;
815     for ( PortVectorIterator it = m_PeriodPorts.begin();
816           it != m_PeriodPorts.end();
817           ++it ) {
818         if((*it)->isDisabled()) {continue;};
819
820         //FIXME: make this into a static_cast when not DEBUG?
821         Port *port=dynamic_cast<Port *>(*it);
822
823         switch(port->getPortType()) {
824
825         case Port::E_Audio:
826             if(provideSilenceToPort(static_cast<AudioPort *>(*it), offset, nevents)) {
827                 debugWarning("Could not put silence into to port %s",(*it)->getName().c_str());
828                 no_problem=false;
829             }
830             break;
831         // midi is a packet based port, don't process
832         //    case MotuPortInfo::E_Midi:
833         //        break;
834
835         default: // ignore
836             break;
837         }
838     }
839     return no_problem;
840 }
841
842 int
843 StreamProcessor::provideSilenceToPort(
844                        AudioPort *p, unsigned int offset, unsigned int nevents)
845 {
846     unsigned int j=0;
847     switch(p->getDataType()) {
848         default:
849         case Port::E_Int24:
850             {
851                 quadlet_t *buffer=(quadlet_t *)(p->getBufferAddress());
852                 assert(nevents + offset <= p->getBufferSize());
853                 buffer+=offset;
854
855                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
856                     *(buffer)=0;
857                     buffer++;
858                 }
859             }
860             break;
861         case Port::E_Float:
862             {
863                 float *buffer=(float *)(p->getBufferAddress());
864                 assert(nevents + offset <= p->getBufferSize());
865                 buffer+=offset;
866
867                 for(j = 0; j < nevents; j += 1) { // decode max nsamples
868                     *buffer = 0.0;
869                     buffer++;
870                 }
871             }
872             break;
873     }
874     return 0;
875 }
876
877 /***********************************************
878  * State related API                           *
879  ***********************************************/
880 bool StreamProcessor::init()
881 {
882     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "init...\n");
883
884     if(!m_IsoHandlerManager.registerStream(this)) {
885         debugOutput(DEBUG_LEVEL_VERBOSE,"Could not register stream processor with the Iso manager\n");
886         return false;
887     }
888     if(!m_StreamProcessorManager.registerProcessor(this)) {
889         debugOutput(DEBUG_LEVEL_VERBOSE,"Could not register stream processor with the SP manager\n");
890         return false;
891     }
892
893     // initialization can be done without requesting it
894     // from the packet loop
895     m_next_state = ePS_Created;
896     return true;
897 }
898
899 bool StreamProcessor::prepare()
900 {
901     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepare SP (%p)...\n", this);
902
903     // make the scratch buffer one period of frames long
904     m_scratch_buffer_size_bytes = m_StreamProcessorManager.getPeriodSize() * getEventsPerFrame() * getEventSize();
905     debugOutput( DEBUG_LEVEL_VERBOSE, " Allocate scratch buffer of %d quadlets\n");
906     if(m_scratch_buffer) delete[] m_scratch_buffer;
907     m_scratch_buffer = new byte_t[m_scratch_buffer_size_bytes];
908     if(m_scratch_buffer == NULL) {
909         debugFatal("Could not allocate scratch buffer\n");
910         return false;
911     }
912
913     if (!prepareChild()) {
914         debugFatal("Could not prepare child\n");
915         return false;
916     }
917
918     debugOutput( DEBUG_LEVEL_VERBOSE, "Prepared for:\n");
919     debugOutput( DEBUG_LEVEL_VERBOSE, " Samplerate: %d\n",
920              m_StreamProcessorManager.getNominalRate());
921     debugOutput( DEBUG_LEVEL_VERBOSE, " PeriodSize: %d, NbBuffers: %d\n",
922              m_StreamProcessorManager.getPeriodSize(), m_StreamProcessorManager.getNbBuffers());
923     debugOutput( DEBUG_LEVEL_VERBOSE, " Port: %d, Channel: %d\n",
924              m_1394service.getPort(), m_channel);
925
926     // initialization can be done without requesting it
927     // from the packet loop
928     m_next_state = ePS_Stopped;
929     return updateState();
930 }
931
932 bool
933 StreamProcessor::scheduleStateTransition(enum eProcessorState state, uint64_t time_instant)
934 {
935     // first set the time, since in the packet loop we first check m_state == m_next_state before
936     // using the time
937     m_cycle_to_switch_state = TICKS_TO_CYCLES(time_instant);
938     m_next_state = state;
939     return true;
940 }
941
942 bool
943 StreamProcessor::waitForState(enum eProcessorState state, unsigned int timeout_ms)
944 {
945     debugOutput(DEBUG_LEVEL_VERBOSE, "Waiting for state %s\n", ePSToString(state));
946     int cnt = timeout_ms;
947     while (m_state != state && cnt) {
948         SleepRelativeUsec(1000);
949         cnt--;
950     }
951     if(cnt==0) {
952         debugOutput(DEBUG_LEVEL_VERBOSE, " Timeout\n");
953         return false;
954     }
955     return true;
956 }
957
958 bool StreamProcessor::scheduleStartDryRunning(int64_t t) {
959     uint64_t tx;
960     if (t < 0) {
961         tx = addTicks(m_1394service.getCycleTimerTicks(), 200 * TICKS_PER_CYCLE);
962     } else {
963         tx = t;
964     }
965     uint64_t start_handler_ticks = substractTicks(tx, 100 * TICKS_PER_CYCLE);
966
967     debugOutput(DEBUG_LEVEL_VERBOSE,"for %s SP (%p)\n", ePTToString(getType()), this);
968     uint64_t now = m_1394service.getCycleTimerTicks();
969     debugOutput(DEBUG_LEVEL_VERBOSE,"  Now                   : %011llu (%03us %04uc %04ut)\n",
970                           now,
971                           (unsigned int)TICKS_TO_SECS(now),
972                           (unsigned int)TICKS_TO_CYCLES(now),
973                           (unsigned int)TICKS_TO_OFFSET(now));
974     debugOutput(DEBUG_LEVEL_VERBOSE,"  Start at              : %011llu (%03us %04uc %04ut)\n",
975                           tx,
976                           (unsigned int)TICKS_TO_SECS(tx),
977                           (unsigned int)TICKS_TO_CYCLES(tx),
978                           (unsigned int)TICKS_TO_OFFSET(tx));
979     if (m_state == ePS_Stopped) {
980         if(!m_IsoHandlerManager.startHandlerForStream(
981                                         this, TICKS_TO_CYCLES(start_handler_ticks))) {
982             debugError("Could not start handler for SP %p\n", this);
983             return false;
984         }
985         return scheduleStateTransition(ePS_WaitingForStream, tx);
986     } else if (m_state == ePS_Running) {
987         return scheduleStateTransition(ePS_WaitingForStreamDisable, tx);
988     } else {
989         debugError("Cannot switch to ePS_DryRunning from %s\n", ePSToString(m_state));
990         return false;
991     }
992 }
993
994 bool StreamProcessor::scheduleStartRunning(int64_t t) {
995     uint64_t tx;
996     if (t < 0) {
997         tx = addTicks(m_1394service.getCycleTimerTicks(), 200 * TICKS_PER_CYCLE);
998     } else {
999         tx = t;
1000     }
1001     debugOutput(DEBUG_LEVEL_VERBOSE,"for %s SP (%p)\n", ePTToString(getType()), this);
1002     uint64_t now = m_1394service.getCycleTimerTicks();
1003     debugOutput(DEBUG_LEVEL_VERBOSE,"  Now                   : %011llu (%03us %04uc %04ut)\n",
1004                           now,
1005                           (unsigned int)TICKS_TO_SECS(now),
1006                           (unsigned int)TICKS_TO_CYCLES(now),
1007                           (unsigned int)TICKS_TO_OFFSET(now));
1008     debugOutput(DEBUG_LEVEL_VERBOSE,"  Start at              : %011llu (%03us %04uc %04ut)\n",
1009                           tx,
1010                           (unsigned int)TICKS_TO_SECS(tx),
1011                           (unsigned int)TICKS_TO_CYCLES(tx),
1012                           (unsigned int)TICKS_TO_OFFSET(tx));
1013     return scheduleStateTransition(ePS_WaitingForStreamEnable, tx);
1014 }
1015
1016 bool StreamProcessor::scheduleStopDryRunning(int64_t t) {
1017     uint64_t tx;
1018     if (t < 0) {
1019         tx = addTicks(m_1394service.getCycleTimerTicks(), 200 * TICKS_PER_CYCLE);
1020     } else {
1021         tx = t;
1022     }
1023     debugOutput(DEBUG_LEVEL_VERBOSE,"for %s SP (%p)\n", ePTToString(getType()), this);
1024     uint64_t now = m_1394service.getCycleTimerTicks();
1025     debugOutput(DEBUG_LEVEL_VERBOSE,"  Now                   : %011llu (%03us %04uc %04ut)\n",
1026                           now,
1027                           (unsigned int)TICKS_TO_SECS(now),
1028                           (unsigned int)TICKS_TO_CYCLES(now),
1029                           (unsigned int)TICKS_TO_OFFSET(now));
1030     debugOutput(DEBUG_LEVEL_VERBOSE,"  Stop at               : %011llu (%03us %04uc %04ut)\n",
1031                           tx,
1032                           (unsigned int)TICKS_TO_SECS(tx),
1033                           (unsigned int)TICKS_TO_CYCLES(tx),
1034                           (unsigned int)TICKS_TO_OFFSET(tx));
1035
1036     return scheduleStateTransition(ePS_Stopped, tx);
1037 }
1038
1039 bool StreamProcessor::scheduleStopRunning(int64_t t) {
1040     uint64_t tx;
1041     if (t < 0) {
1042         tx = addTicks(m_1394service.getCycleTimerTicks(), 200 * TICKS_PER_CYCLE);
1043     } else {
1044         tx = t;
1045     }
1046     debugOutput(DEBUG_LEVEL_VERBOSE,"for %s SP (%p)\n", ePTToString(getType()), this);
1047     uint64_t now = m_1394service.getCycleTimerTicks();
1048     debugOutput(DEBUG_LEVEL_VERBOSE,"  Now                   : %011llu (%03us %04uc %04ut)\n",
1049                           now,
1050                           (unsigned int)TICKS_TO_SECS(now),
1051                           (unsigned int)TICKS_TO_CYCLES(now),
1052                           (unsigned int)TICKS_TO_OFFSET(now));
1053     debugOutput(DEBUG_LEVEL_VERBOSE,"  Stop at               : %011llu (%03us %04uc %04ut)\n",
1054                           tx,
1055                           (unsigned int)TICKS_TO_SECS(tx),
1056                           (unsigned int)TICKS_TO_CYCLES(tx),
1057                           (unsigned int)TICKS_TO_OFFSET(tx));
1058     return scheduleStateTransition(ePS_WaitingForStreamDisable, tx);
1059 }
1060
1061 bool StreamProcessor::startDryRunning(int64_t t) {
1062     if(!scheduleStartDryRunning(t)) {
1063         debugError("Could not schedule transition\n");
1064         return false;
1065     }
1066     if(!waitForState(ePS_DryRunning, 2000)) {
1067         debugError(" Timeout while waiting for %s\n", ePSToString(ePS_DryRunning));
1068         return false;
1069     }
1070     return true;
1071 }
1072
1073 bool StreamProcessor::startRunning(int64_t t) {
1074     if(!scheduleStartRunning(t)) {
1075         debugError("Could not schedule transition\n");
1076         return false;
1077     }
1078     if(!waitForState(ePS_Running, 2000)) {
1079         debugError(" Timeout while waiting for %s\n", ePSToString(ePS_Running));
1080         return false;
1081     }
1082     return true;
1083 }
1084
1085 bool StreamProcessor::stopDryRunning(int64_t t) {
1086     if(!scheduleStopDryRunning(t)) {
1087         debugError("Could not schedule transition\n");
1088         return false;
1089     }
1090     if(!waitForState(ePS_Stopped, 2000)) {
1091         debugError(" Timeout while waiting for %s\n", ePSToString(ePS_Stopped));
1092         return false;
1093     }
1094     return true;
1095 }
1096
1097 bool StreamProcessor::stopRunning(int64_t t) {
1098     if(!scheduleStopRunning(t)) {
1099         debugError("Could not schedule transition\n");
1100         return false;
1101     }
1102     if(!waitForState(ePS_DryRunning, 2000)) {
1103         debugError(" Timeout while waiting for %s\n", ePSToString(ePS_DryRunning));
1104         return false;
1105     }
1106     return true;
1107 }
1108
1109
1110 // internal state API
1111
1112 /**
1113  * @brief Enter the ePS_Stopped state
1114  * @return true if successful, false if not
1115  *
1116  * @pre none
1117  *
1118  * @post the buffer and the isostream are ready for use.
1119  * @post all dynamic structures have been allocated successfully
1120  * @post the buffer is transparent and empty, and all parameters are set
1121  *       to the correct initial/nominal values.
1122  *
1123  */
1124 bool
1125 StreamProcessor::doStop()
1126 {
1127     float ticks_per_frame;
1128     unsigned int ringbuffer_size_frames = (m_StreamProcessorManager.getNbBuffers() + 1) * m_StreamProcessorManager.getPeriodSize();
1129
1130     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1131     bool result = true;
1132
1133     switch(m_state) {
1134         case ePS_Created:
1135             assert(m_data_buffer);
1136             // object just created
1137             result = m_data_buffer->init();
1138
1139             // prepare the framerate estimate
1140             ticks_per_frame = (TICKS_PER_SECOND*1.0) / ((float)m_StreamProcessorManager.getNominalRate());
1141             m_ticks_per_frame = ticks_per_frame;
1142             debugOutput(DEBUG_LEVEL_VERBOSE,"Initializing remote ticks/frame to %f\n", ticks_per_frame);
1143
1144             // initialize internal buffer
1145             result &= m_data_buffer->setBufferSize(ringbuffer_size_frames);
1146
1147             result &= m_data_buffer->setEventSize( getEventSize() );
1148             result &= m_data_buffer->setEventsPerFrame( getEventsPerFrame() );
1149             if(getType() == ePT_Receive) {
1150                 result &= m_data_buffer->setUpdatePeriod( getNominalFramesPerPacket() );
1151             } else {
1152                 result &= m_data_buffer->setUpdatePeriod( m_StreamProcessorManager.getPeriodSize() );
1153             }
1154             result &= m_data_buffer->setNominalRate(ticks_per_frame);
1155             result &= m_data_buffer->setWrapValue(128L*TICKS_PER_SECOND);
1156             result &= m_data_buffer->prepare(); // FIXME: the name
1157
1158             // set the parameters of ports we can:
1159             // we want the audio ports to be period buffered,
1160             // and the midi ports to be packet buffered
1161             for ( PortVectorIterator it = m_Ports.begin();
1162                 it != m_Ports.end();
1163                 ++it )
1164             {
1165                 debugOutput(DEBUG_LEVEL_VERBOSE, "Setting up port %s\n",(*it)->getName().c_str());
1166                 if(!(*it)->setBufferSize(m_StreamProcessorManager.getPeriodSize())) {
1167                     debugFatal("Could not set buffer size to %d\n",m_StreamProcessorManager.getPeriodSize());
1168                     return false;
1169                 }
1170                 switch ((*it)->getPortType()) {
1171                     case Port::E_Audio:
1172                         if(!(*it)->setSignalType(Port::E_PeriodSignalled)) {
1173                             debugFatal("Could not set signal type to PeriodSignalling");
1174                             return false;
1175                         }
1176                         // buffertype and datatype are dependant on the API
1177                         debugWarning("---------------- ! Doing hardcoded dummy setup ! --------------\n");
1178                         // buffertype and datatype are dependant on the API
1179                         if(!(*it)->setBufferType(Port::E_PointerBuffer)) {
1180                             debugFatal("Could not set buffer type");
1181                             return false;
1182                         }
1183                         if(!(*it)->useExternalBuffer(true)) {
1184                             debugFatal("Could not set external buffer usage");
1185                             return false;
1186                         }
1187                         if(!(*it)->setDataType(Port::E_Float)) {
1188                             debugFatal("Could not set data type");
1189                             return false;
1190                         }
1191                         break;
1192                     case Port::E_Midi:
1193                         if(!(*it)->setSignalType(Port::E_PacketSignalled)) {
1194                             debugFatal("Could not set signal type to PacketSignalling");
1195                             return false;
1196                         }
1197                         // buffertype and datatype are dependant on the API
1198                         debugWarning("---------------- ! Doing hardcoded test setup ! --------------\n");
1199                         // buffertype and datatype are dependant on the API
1200                         if(!(*it)->setBufferType(Port::E_RingBuffer)) {
1201                             debugFatal("Could not set buffer type");
1202                             return false;
1203                         }
1204                         if(!(*it)->setDataType(Port::E_MidiEvent)) {
1205                             debugFatal("Could not set data type");
1206                             return false;
1207                         }
1208                         break;
1209                     default:
1210                         debugWarning("Unsupported port type specified\n");
1211                         break;
1212                 }
1213             }
1214             // the API specific settings of the ports should already be set,
1215             // as this is called from the processorManager->prepare()
1216             // so we can init the ports
1217             result &= PortManager::initPorts();
1218
1219             break;
1220         case ePS_DryRunning:
1221             if(!m_IsoHandlerManager.stopHandlerForStream(this)) {
1222                 debugError("Could not stop handler for SP %p\n", this);
1223                 return false;
1224             }
1225             break;
1226         default:
1227             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1228             return false;
1229     }
1230
1231     result &= m_data_buffer->clearBuffer(); // FIXME: don't like the reset() name
1232     // make the buffer transparent
1233     m_data_buffer->setTransparent(true);
1234
1235     // reset all ports
1236     result &= PortManager::preparePorts();
1237
1238     m_state = ePS_Stopped;
1239     #ifdef DEBUG
1240     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1241         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1242         dumpInfo();
1243     }
1244     #endif
1245     return result;
1246 }
1247
1248 /**
1249  * @brief Enter the ePS_WaitingForStream state
1250  * @return true if successful, false if not
1251  *
1252  * @pre all dynamic data structures are allocated successfully
1253  *
1254  * @post
1255  *
1256  */
1257 bool
1258 StreamProcessor::doWaitForRunningStream()
1259 {
1260     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1261     switch(m_state) {
1262         case ePS_Stopped:
1263             // we have to start waiting for an incoming stream
1264             // this basically means nothing, the state change will
1265             // be picked up by the packet iterator
1266             break;
1267         default:
1268             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1269             return false;
1270     }
1271     m_state = ePS_WaitingForStream;
1272     #ifdef DEBUG
1273     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1274         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1275         dumpInfo();
1276     }
1277     #endif
1278     return true;
1279 }
1280
1281 /**
1282  * @brief Enter the ePS_DryRunning state
1283  * @return true if successful, false if not
1284  *
1285  * @pre
1286  *
1287  * @post
1288  *
1289  */
1290 bool
1291 StreamProcessor::doDryRunning()
1292 {
1293     bool result = true;
1294     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1295     switch(m_state) {
1296         case ePS_WaitingForStream:
1297             // a running stream has been detected
1298             debugOutput(DEBUG_LEVEL_VERBOSE, "StreamProcessor %p started dry-running at cycle %d\n", this, m_last_cycle);
1299             if (getType() == ePT_Receive) {
1300                 // this to ensure that there is no discontinuity when starting to
1301                 // update the DLL based upon the received packets
1302                 m_data_buffer->setBufferTailTimestamp(m_last_timestamp);
1303             } else {
1304                 // FIXME: PC=master mode will have to do something here I guess...
1305             }
1306             break;
1307         case ePS_WaitingForStreamEnable: // when xrunning at startup
1308             result &= m_data_buffer->clearBuffer();
1309             m_data_buffer->setTransparent(true);
1310             break;
1311         case ePS_WaitingForStreamDisable:
1312             result &= m_data_buffer->clearBuffer();
1313             m_data_buffer->setTransparent(true);
1314             break;
1315         default:
1316             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1317             return false;
1318     }
1319     m_state = ePS_DryRunning;
1320     #ifdef DEBUG
1321     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1322         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1323         dumpInfo();
1324     }
1325     #endif
1326     return result;
1327 }
1328
1329 /**
1330  * @brief Enter the ePS_WaitingForStreamEnable state
1331  * @return true if successful, false if not
1332  *
1333  * @pre
1334  *
1335  * @post
1336  *
1337  */
1338 bool
1339 StreamProcessor::doWaitForStreamEnable()
1340 {
1341     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1342     unsigned int ringbuffer_size_frames;
1343     switch(m_state) {
1344         case ePS_DryRunning:
1345             // we have to start waiting for an incoming stream
1346             // this basically means nothing, the state change will
1347             // be picked up by the packet iterator
1348
1349             if(!m_data_buffer->clearBuffer()) { // FIXME: don't like the reset() name
1350                 debugError("Could not reset data buffer\n");
1351                 return false;
1352             }
1353             if (getType() == ePT_Transmit) {
1354                 ringbuffer_size_frames = m_StreamProcessorManager.getNbBuffers() * m_StreamProcessorManager.getPeriodSize();
1355                 debugOutput(DEBUG_LEVEL_VERBOSE, "Prefill transmit SP %p with %u frames\n", this, ringbuffer_size_frames);
1356                 // prefill the buffer
1357                 if(!transferSilence(ringbuffer_size_frames)) {
1358                     debugFatal("Could not prefill transmit stream\n");
1359                     return false;
1360                 }
1361             }
1362
1363             break;
1364         default:
1365             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1366             return false;
1367     }
1368     m_state = ePS_WaitingForStreamEnable;
1369     #ifdef DEBUG
1370     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1371         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1372         dumpInfo();
1373     }
1374     #endif
1375     return true;
1376 }
1377
1378 /**
1379  * @brief Enter the ePS_Running state
1380  * @return true if successful, false if not
1381  *
1382  * @pre
1383  *
1384  * @post
1385  *
1386  */
1387 bool
1388 StreamProcessor::doRunning()
1389 {
1390     bool result = true;
1391     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1392     switch(m_state) {
1393         case ePS_WaitingForStreamEnable:
1394             // a running stream has been detected
1395             debugOutput(DEBUG_LEVEL_VERBOSE, "StreamProcessor %p started running at cycle %d\n",
1396                                              this, m_last_cycle);
1397             m_in_xrun = false;
1398             m_data_buffer->setTransparent(false);
1399             break;
1400         default:
1401             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1402             return false;
1403     }
1404     m_state = ePS_Running;
1405     #ifdef DEBUG
1406     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1407         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1408         dumpInfo();
1409     }
1410     #endif
1411     return result;
1412 }
1413
1414 /**
1415  * @brief Enter the ePS_WaitingForStreamDisable state
1416  * @return true if successful, false if not
1417  *
1418  * @pre
1419  *
1420  * @post
1421  *
1422  */
1423 bool
1424 StreamProcessor::doWaitForStreamDisable()
1425 {
1426     debugOutput(DEBUG_LEVEL_VERBOSE, "Enter from state: %s\n", ePSToString(m_state));
1427     switch(m_state) {
1428         case ePS_Running:
1429             // the thread will do the transition
1430             break;
1431         default:
1432             debugError("Entry from invalid state: %s\n", ePSToString(m_state));
1433             return false;
1434     }
1435     m_state = ePS_WaitingForStreamDisable;
1436     #ifdef DEBUG
1437     if (getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
1438         debugOutput(DEBUG_LEVEL_VERBOSE, "State switch complete, dumping SP info...\n");
1439         dumpInfo();
1440     }
1441     #endif
1442     return true;
1443 }
1444
1445 /**
1446  * @brief Updates the state machine and calls the necessary transition functions
1447  * @return true if successful, false if not
1448  */
1449 bool StreamProcessor::updateState() {
1450     bool result = false;
1451     // copy the current state locally since it could change value,
1452     // and that's something we don't want to happen inbetween tests
1453     // if m_next_state changes during this routine, we know for sure
1454     // that the previous state change was at least attempted correctly.
1455     enum eProcessorState next_state = m_next_state;
1456
1457     debugOutput(DEBUG_LEVEL_VERBOSE, "Do state transition: %s => %s\n",
1458         ePSToString(m_state), ePSToString(next_state));
1459
1460     if (m_state == next_state) {
1461         debugWarning("ignoring identity state update from/to %s\n", ePSToString(m_state) );
1462         return true;
1463     }
1464
1465     // after creation, only initialization is allowed
1466     if (m_state == ePS_Created) {
1467         if(next_state != ePS_Stopped) {
1468             goto updateState_exit_with_error;
1469         }
1470         // do init here
1471         result = doStop();
1472         if (result) return true;
1473         else goto updateState_exit_change_failed;
1474     }
1475
1476     // after initialization, only WaitingForRunningStream is allowed
1477     if (m_state == ePS_Stopped) {
1478         if(next_state != ePS_WaitingForStream) {
1479             goto updateState_exit_with_error;
1480         }
1481         result = doWaitForRunningStream();
1482         if (result) return true;
1483         else goto updateState_exit_change_failed;
1484     }
1485
1486     // after WaitingForStream, only ePS_DryRunning is allowed
1487     // this means that the stream started running
1488     if (m_state == ePS_WaitingForStream) {
1489         if(next_state != ePS_DryRunning) {
1490             goto updateState_exit_with_error;
1491         }
1492         result = doDryRunning();
1493         if (result) return true;
1494         else goto updateState_exit_change_failed;
1495     }
1496
1497     // from ePS_DryRunning we can go to:
1498     //   - ePS_Stopped if something went wrong during DryRunning
1499     //   - ePS_WaitingForStreamEnable if there is a requested to enable
1500     if (m_state == ePS_DryRunning) {
1501         if((next_state != ePS_Stopped) &&
1502            (next_state != ePS_WaitingForStreamEnable)) {
1503             goto updateState_exit_with_error;
1504         }
1505         if (next_state == ePS_Stopped) {
1506             result = doStop();
1507         } else {
1508             result = doWaitForStreamEnable();
1509         }
1510         if (result) return true;
1511         else goto updateState_exit_change_failed;
1512     }
1513
1514     // from ePS_WaitingForStreamEnable we can go to:
1515     //   - ePS_DryRunning if something went wrong while waiting
1516     //   - ePS_Running if the stream enabled correctly
1517     if (m_state == ePS_WaitingForStreamEnable) {
1518         if((next_state != ePS_DryRunning) &&
1519            (next_state != ePS_Running)) {
1520             goto updateState_exit_with_error;
1521         }
1522         if (next_state == ePS_Stopped) {
1523             result = doDryRunning();
1524         } else {
1525             result = doRunning();
1526         }
1527         if (result) return true;
1528         else goto updateState_exit_change_failed;
1529     }
1530
1531     // from ePS_Running we can only start waiting for a disabled stream
1532     if (m_state == ePS_Running) {
1533         if(next_state != ePS_WaitingForStreamDisable) {
1534             goto updateState_exit_with_error;
1535         }
1536         result = doWaitForStreamDisable();
1537         if (result) return true;
1538         else goto updateState_exit_change_failed;
1539     }
1540
1541     // from ePS_WaitingForStreamDisable we can go to DryRunning
1542     if (m_state == ePS_WaitingForStreamDisable) {
1543         if(next_state != ePS_DryRunning) {
1544             goto updateState_exit_with_error;
1545         }
1546         result = doDryRunning();
1547         if (result) return true;
1548         else goto updateState_exit_change_failed;
1549     }
1550
1551     // if we arrive here there is an error
1552 updateState_exit_with_error:
1553     debugError("Invalid state transition: %s => %s\n",
1554         ePSToString(m_state), ePSToString(next_state));
1555     return false;
1556 updateState_exit_change_failed:
1557     debugError("State transition failed: %s => %s\n",
1558         ePSToString(m_state), ePSToString(next_state));
1559     return false;
1560 }
1561
1562 /***********************************************
1563  * Helper routines                             *
1564  ***********************************************/
1565 bool
1566 StreamProcessor::transferSilence(unsigned int nframes)
1567 {
1568     bool retval;
1569     signed int fc;
1570     ffado_timestamp_t ts_tail_tmp;
1571
1572     // prepare a buffer of silence
1573     char *dummybuffer = (char *)calloc(getEventSize(), nframes * getEventsPerFrame());
1574     transmitSilenceBlock(dummybuffer, nframes, 0);
1575
1576     m_data_buffer->getBufferTailTimestamp(&ts_tail_tmp, &fc);
1577     if (fc != 0) {
1578         debugWarning("Prefilling a buffer that already contains %d frames\n", fc);
1579     }
1580
1581     // add the silence data to the ringbuffer
1582     if(m_data_buffer->preloadFrames(nframes, dummybuffer, true)) {
1583         retval = true;
1584     } else {
1585         debugWarning("Could not write to event buffer\n");
1586         retval = false;
1587     }
1588     free(dummybuffer);
1589     return retval;
1590 }
1591
1592 /**
1593  * @brief convert a eProcessorState to a string
1594  * @param s the state
1595  * @return a char * describing the state
1596  */
1597 const char *
1598 StreamProcessor::ePSToString(enum eProcessorState s) {
1599     switch (s) {
1600         case ePS_Invalid: return "ePS_Invalid";
1601         case ePS_Created: return "ePS_Created";
1602         case ePS_Stopped: return "ePS_Stopped";
1603         case ePS_WaitingForStream: return "ePS_WaitingForStream";
1604         case ePS_DryRunning: return "ePS_DryRunning";
1605         case ePS_WaitingForStreamEnable: return "ePS_WaitingForStreamEnable";
1606         case ePS_Running: return "ePS_Running";
1607         case ePS_WaitingForStreamDisable: return "ePS_WaitingForStreamDisable";
1608         default: return "error: unknown state";
1609     }
1610 }
1611
1612 /**
1613  * @brief convert a eProcessorType to a string
1614  * @param t the type
1615  * @return a char * describing the state
1616  */
1617 const char *
1618 StreamProcessor::ePTToString(enum eProcessorType t) {
1619     switch (t) {
1620         case ePT_Receive: return "Receive";
1621         case ePT_Transmit: return "Transmit";
1622         default: return "error: unknown type";
1623     }
1624 }
1625
1626 /***********************************************
1627  * Debug                                       *
1628  ***********************************************/
1629 void
1630 StreamProcessor::dumpInfo()
1631 {
1632     debugOutputShort( DEBUG_LEVEL_NORMAL, " StreamProcessor %p:\n", this);
1633     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel  : %d, %d\n", m_1394service.getPort(), m_channel);
1634     uint64_t now = m_1394service.getCycleTimerTicks();
1635     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Now                   : %011llu (%03us %04uc %04ut)\n",
1636                         now,
1637                         (unsigned int)TICKS_TO_SECS(now),
1638                         (unsigned int)TICKS_TO_CYCLES(now),
1639                         (unsigned int)TICKS_TO_OFFSET(now));
1640     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Xrun?                 : %s\n", (m_in_xrun ? "True":"False"));
1641     if (m_state == m_next_state) {
1642         debugOutputShort( DEBUG_LEVEL_NORMAL, "  State                 : %s\n",
1643                                             ePSToString(m_state));
1644     } else {
1645         debugOutputShort( DEBUG_LEVEL_NORMAL, "  State                 : %s (Next: %s)\n",
1646                                               ePSToString(m_state), ePSToString(m_next_state));
1647         debugOutputShort( DEBUG_LEVEL_NORMAL, "    transition at       : %u\n", m_cycle_to_switch_state);
1648     }
1649     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer                : %p\n", m_data_buffer);
1650     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Framerate             : Nominal: %u, Sync: %f, Buffer %f\n",
1651                                           m_StreamProcessorManager.getNominalRate(),
1652                                           24576000.0/m_StreamProcessorManager.getSyncSource().m_data_buffer->getRate(),
1653                                           24576000.0/m_data_buffer->getRate());
1654     float d = getSyncDelay();
1655     debugOutputShort(DEBUG_LEVEL_NORMAL, "  Sync delay             : %f ticks (%f frames, %f cy)\n",
1656                                          d, d/getTicksPerFrame(),
1657                                          d/((float)TICKS_PER_CYCLE));
1658     m_data_buffer->dumpInfo();
1659 }
1660
1661 void
1662 StreamProcessor::setVerboseLevel(int l) {
1663     setDebugLevel(l);
1664     PortManager::setVerboseLevel(l);
1665     m_data_buffer->setVerboseLevel(l);
1666 }
1667
1668 } // end of namespace
Note: See TracBrowser for help on using the browser.