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

Revision 783, 61.0 kB (checked in by ppalmers, 13 years ago)

cleanup time/wait/sleep code

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