root/branches/api-cleanup/src/libstreaming/generic/StreamProcessor.cpp

Revision 809, 66.5 kB (checked in by ppalmers, 14 years ago)

First round of cleanup:
- make Ports auto-register to a PortManager?
- remove the different 'signal' types, everything is now period-signaled.
- removed obsolete streaming test programs

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