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

Revision 841, 19.2 kB (checked in by ppalmers, 14 years ago)

fix single ISO thread operation (1394 stack seems to be thread-unsafe)

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 #ifndef __FFADO_STREAMPROCESSOR__
25 #define __FFADO_STREAMPROCESSOR__
26
27 #include "ffadodevice.h"
28
29 #include "PortManager.h"
30
31 #include "libutil/StreamStatistics.h"
32 #include "libutil/TimestampedBuffer.h"
33 #include "libutil/OptionContainer.h"
34
35 #include "debugmodule/debugmodule.h"
36 #include <semaphore.h>
37
38 class Ieee1394Service;
39 class IsoHandlerManager;
40
41 namespace Streaming {
42
43     class StreamProcessorManager;
44 /*!
45 \brief Class providing a generic interface for Stream Processors
46
47  A stream processor multiplexes or demultiplexes an ISO stream into a
48  collection of ports. This class should be subclassed, and the relevant
49  functions should be overloaded.
50
51 */
52 class StreamProcessor : public PortManager,
53                         public Util::TimestampedBufferClient,
54                         public Util::OptionContainer
55 {
56 public:
57     ///> the streamprocessor type
58     enum eProcessorType {
59         ePT_Receive,
60         ePT_Transmit
61     };
62     ///> returns the type of the streamprocessor
63     virtual enum eProcessorType getType() { return m_processor_type; };
64 private:
65     // this can only be set by the constructor
66     enum eProcessorType m_processor_type;
67     // pretty printing
68     const char *ePTToString(enum eProcessorType);
69 protected:
70     ///> the state the streamprocessor is in
71     enum eProcessorState {
72         ePS_Invalid,
73         ePS_Created,
74         // ePS_WaitingToStop, FIXME: this will be needed for the MOTU's
75         ePS_Stopped,
76         ePS_WaitingForStream,
77         ePS_DryRunning,
78         ePS_WaitingForStreamEnable,
79         ePS_Running,
80         ePS_WaitingForStreamDisable,
81     };
82
83     ///> set the SP state to a specific value
84     void setState(enum eProcessorState);
85     ///> get the SP state
86     enum eProcessorState getState() {return m_state;};
87 private:
88     enum eProcessorState m_state;
89     // state switching
90     enum eProcessorState m_next_state;
91     unsigned int m_cycle_to_switch_state;
92     bool updateState();
93     // pretty printing
94     const char *ePSToString(enum eProcessorState);
95
96     bool doStop();
97     bool doWaitForRunningStream();
98     bool doDryRunning();
99     bool doWaitForStreamEnable();
100     bool doRunning();
101     bool doWaitForStreamDisable();
102
103     bool scheduleStateTransition(enum eProcessorState state, uint64_t time_instant);
104     bool waitForState(enum eProcessorState state, unsigned int timeout);
105
106 public: //--- state stuff
107     bool isRunning()
108             {return m_state == ePS_Running;};
109     bool isDryRunning()
110             {return m_state == ePS_DryRunning;};
111     bool isStopped()
112             {return m_state == ePS_Stopped;};
113     bool isWaitingForStream()
114             {return m_state == ePS_WaitingForStream;};
115
116     // these schedule and wait for the state transition
117     bool startDryRunning(int64_t time_to_start_at);
118     bool startRunning(int64_t time_to_start_at);
119     bool stopDryRunning(int64_t time_to_stop_at);
120     bool stopRunning(int64_t time_to_stop_at);
121
122     // these only schedule the transition
123     bool scheduleStartDryRunning(int64_t time_to_start_at);
124     bool scheduleStartRunning(int64_t time_to_start_at);
125     bool scheduleStopDryRunning(int64_t time_to_stop_at);
126     bool scheduleStopRunning(int64_t time_to_stop_at);
127
128     // the main difference between init and prepare is that when prepare is called,
129     // the SP is registered to a manager (FIXME: can't it be called by the manager?)
130     bool init();
131     bool prepare();
132
133 public: // constructor/destructor
134     StreamProcessor(FFADODevice &parent, enum eProcessorType type);
135     virtual ~StreamProcessor();
136 protected:
137     FFADODevice&                m_Parent;
138     Ieee1394Service&            m_1394service;
139     IsoHandlerManager&          m_IsoHandlerManager;
140     StreamProcessorManager&     m_StreamProcessorManager;
141     unsigned int                m_local_node_id;
142
143 public: // the public receive/transmit functions
144     // the transmit interface accepts frames and provides packets
145     // implement these for a transmit SP
146     // leave default for a receive SP
147
148     // the receive interface accepts packets and provides frames
149     // these are implemented by the parent SP
150     enum raw1394_iso_disposition
151         putPacket(unsigned char *data, unsigned int length,
152                   unsigned char channel, unsigned char tag, unsigned char sy,
153                   unsigned int cycle, unsigned int dropped);
154
155     enum raw1394_iso_disposition
156     getPacket(unsigned char *data, unsigned int *length,
157                 unsigned char *tag, unsigned char *sy,
158                 int cycle, unsigned int dropped, unsigned int max_length);
159
160     bool getFrames(unsigned int nbframes, int64_t ts); ///< transfer the buffer contents to the client
161     bool putFrames(unsigned int nbframes, int64_t ts); ///< transfer the client contents to the buffer
162
163     unsigned int getSignalPeriod() {return m_signal_period;};
164     bool setSignalPeriod(unsigned int p) {m_signal_period=p; return true;};
165     /**
166      * @brief waits for a 'signal' (blocking)
167      *
168      * a 'signal' is:
169      * when type==Receive:
170      *  - one signal_period of frames is present in the buffer
171      *    (received by the iso side)
172      *  - an error has occurred (xrun, iso error, ...)
173      * when type==Transmit:
174      *  - at least one signal_period of frames are present in the buffer
175      *    (have been written into it by the client)
176      *  - an error occurred
177      *
178      * @return true if the 'signal' is available, false if error
179      */
180     bool waitForSignal();
181
182     /**
183      * @brief checks for a 'signal' (non-blocking)
184      *
185      * a 'signal' is:
186      * when type==Receive:
187      *  - one signal_period of frames is present in the buffer
188      *    (received by the iso side)
189      *  - an error has occurred (xrun, iso error, ...)
190      * when type==Transmit:
191      *  - at least one signal_period of frames are present in the buffer
192      *    (have been written into it by the client)
193      *  - an error occurred
194      *
195      * @return true if the 'signal' is available, false if not (or error)
196      */
197     bool tryWaitForSignal();
198
199     /**
200      * @brief can a SP process (queue, dequeue) packets at this moment?
201      *
202      *
203      * @return true if packet processing makes sense
204      */
205     bool canProcessPackets();
206
207     /**
208      * @brief drop nframes from the internal buffer as if they were transferred to the client side
209      *
210      * Gets nframes of frames from the buffer as done by getFrames(), but does not transfer them
211      * to the client side. Instead they are discarded.
212      *
213      * @param nframes number of frames
214      * @return true if the operation was successful
215      */
216     bool dropFrames(unsigned int nframes, int64_t ts);
217
218     /**
219      * @brief put silence frames into the internal buffer
220      *
221      * Puts nframes of frames into the buffer as done by putFrames(), but does not transfer them
222      * from the client side. Instead, silent frames are used.
223      *
224      * @param nframes number of frames
225      * @return true if the operation was successful
226      */
227     bool putSilenceFrames(unsigned int nbframes, int64_t ts);
228
229     /**
230      * @brief Shifts the stream with the specified number of frames
231      *
232      * Used to align several streams to each other. It comes down to
233      * making sure the head timestamp corresponds to the timestamp of
234      * one master stream
235      *
236      * @param nframes the number of frames to shift
237      * @return true if successful
238      */
239     bool shiftStream(int nframes);
240
241     /**
242      * @brief tries to fill/sink the stream as far as possible
243      */
244     void flush();
245
246 protected: // the helper receive/transmit functions
247     enum eChildReturnValue {
248         eCRV_OK,
249         eCRV_Invalid,
250         eCRV_Packet,
251         eCRV_EmptyPacket,
252         eCRV_XRun,
253         eCRV_Again,
254         eCRV_Defer,
255     };
256     // to be implemented by the children
257     // the following methods are to be implemented by receive SP subclasses
258     virtual enum eChildReturnValue processPacketHeader(unsigned char *data, unsigned int length,
259                                      unsigned char channel, unsigned char tag,
260                                      unsigned char sy, unsigned int cycle,
261                                      unsigned int dropped)
262         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
263     virtual enum eChildReturnValue processPacketData(unsigned char *data, unsigned int length,
264                                    unsigned char channel, unsigned char tag,
265                                    unsigned char sy, unsigned int cycle,
266                                    unsigned int dropped)
267         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
268     virtual bool processReadBlock(char *data, unsigned int nevents, unsigned int offset)
269         {debugWarning("call not allowed\n"); return false;};
270
271     // the following methods are to be implemented by transmit SP subclasses
272     virtual enum eChildReturnValue generatePacketHeader(unsigned char *data, unsigned int *length,
273                                       unsigned char *tag, unsigned char *sy,
274                                       int cycle, unsigned int dropped,
275                                       unsigned int max_length)
276         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
277     virtual enum eChildReturnValue generatePacketData(unsigned char *data, unsigned int *length,
278                                     unsigned char *tag, unsigned char *sy,
279                                     int cycle, unsigned int dropped,
280                                     unsigned int max_length)
281         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
282     virtual enum eChildReturnValue generateSilentPacketHeader(unsigned char *data, unsigned int *length,
283                                             unsigned char *tag, unsigned char *sy,
284                                             int cycle, unsigned int dropped,
285                                             unsigned int max_length)
286         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
287     virtual enum eChildReturnValue generateSilentPacketData(unsigned char *data, unsigned int *length,
288                                           unsigned char *tag, unsigned char *sy,
289                                           int cycle, unsigned int dropped,
290                                           unsigned int max_length)
291         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
292     virtual bool processWriteBlock(char *data, unsigned int nevents, unsigned int offset)
293         {debugWarning("call not allowed\n"); return false;};
294     virtual bool transmitSilenceBlock(char *data, unsigned int nevents, unsigned int offset)
295         {debugWarning("call not allowed\n"); return false;};
296 protected: // some generic helpers
297     int provideSilenceToPort(Port *p, unsigned int offset, unsigned int nevents);
298     bool provideSilenceBlock(unsigned int nevents, unsigned int offset);
299
300 private:
301     bool getFramesDry(unsigned int nbframes, int64_t ts);
302     bool getFramesWet(unsigned int nbframes, int64_t ts);
303     bool putFramesDry(unsigned int nbframes, int64_t ts);
304     bool putFramesWet(unsigned int nbframes, int64_t ts);
305
306     bool transferSilence(unsigned int size);
307
308 public:
309     // move to private?
310     bool xrunOccurred() { return m_in_xrun; };
311
312 // the ISO interface (can we get rid of this?)
313 public:
314     int getChannel() {return m_channel;};
315     bool setChannel(int c)
316         {m_channel = c; return true;};
317
318     virtual unsigned int getNbPacketsIsoXmitBuffer();
319     virtual unsigned int getPacketsPerPeriod();
320     virtual unsigned int getMaxPacketSize() = 0;
321 private:
322     int m_channel;
323
324 protected: // FIXME: move to private
325     uint64_t m_dropped; /// FIXME:debug
326     uint64_t m_last_dropped; /// FIXME:debug
327     int m_last_good_cycle; /// FIXME:debug
328     uint64_t m_last_timestamp; /// last timestamp (in ticks)
329     uint64_t m_last_timestamp2; /// last timestamp (in ticks)
330     bool m_correct_last_timestamp;
331     uint64_t m_last_timestamp_at_period_ticks; // FIXME: still used?
332
333 //--- data buffering and accounting
334 public:
335     void getBufferHeadTimestamp ( ffado_timestamp_t *ts, signed int *fc )
336         {m_data_buffer->getBufferHeadTimestamp(ts, fc);};
337     void getBufferTailTimestamp ( ffado_timestamp_t *ts, signed int *fc )
338         {m_data_buffer->getBufferTailTimestamp(ts, fc);};
339
340     void setBufferTailTimestamp ( ffado_timestamp_t new_timestamp )
341         {m_data_buffer->setBufferTailTimestamp(new_timestamp);};
342     void setBufferHeadTimestamp ( ffado_timestamp_t new_timestamp )
343         {m_data_buffer->setBufferHeadTimestamp(new_timestamp);};
344 protected:
345     Util::TimestampedBuffer *m_data_buffer;
346     // the scratch buffer is temporary buffer space that can be
347     // used by any function. It's pre-allocated when the SP is created.
348     // the purpose is to avoid allocation of memory (or heap/stack) in
349     // an RT context
350     byte_t*         m_scratch_buffer;
351     size_t          m_scratch_buffer_size_bytes;
352
353 protected:
354     // frame counter & sync stuff
355     public:
356         /**
357          * @brief Can this StreamProcessor handle a transfer of nframes frames?
358          *
359          * this function indicates if the streamprocessor can handle a transfer of
360          * nframes frames. It is used to detect underruns-to-be.
361          *
362          * @param nframes number of frames
363          * @return true if the StreamProcessor can handle this amount of frames
364          *         false if it can't
365          */
366         bool canClientTransferFrames(unsigned int nframes);
367
368         /**
369          * \brief return the time until the next period boundary should be signaled (in microseconds)
370          *
371          * Return the time until the next period boundary signal. If this StreamProcessor
372          * is the current synchronization source, this function is called to
373          * determine when a buffer transfer can be made. When this value is
374          * smaller than 0, a period boundary is assumed to be crossed, hence a
375          * transfer can be made.
376          *
377          * \return the time in usecs
378          */
379         int64_t getTimeUntilNextPeriodSignalUsecs();
380         /**
381          * \brief return the time of the next period boundary (in microseconds)
382          *
383          * Returns the time of the next period boundary, in microseconds. The
384          * goal of this function is to determine the exact point of the period
385          * boundary. This is assumed to be the point at which the buffer transfer should
386          * take place, meaning that it can be used as a reference timestamp for transmitting
387          * StreamProcessors
388          *
389          * \return the time in usecs
390          */
391         uint64_t getTimeAtPeriodUsecs();
392
393         /**
394          * \brief return the time of the next period boundary (in internal units)
395          *
396          * The same as getTimeAtPeriodUsecs() but in internal units.
397          *
398          * @return the time in internal units
399          */
400         uint64_t getTimeAtPeriod();
401
402         uint64_t getTimeNow(); // FIXME: should disappear
403
404
405         /**
406          * Returns the sync delay. This is the time a syncsource
407          * delays a period signal, e.g. to cope with buffering.
408          * @return the sync delay
409          */
410         unsigned int getSyncDelay() {return m_sync_delay;};
411         /**
412          * sets the sync delay
413          * @param d sync delay
414          */
415         void setSyncDelay(unsigned int d);
416
417         /**
418          * @brief get the maximal frame latency
419          *
420          * The maximum frame latency is the maximum time that will elapse
421          * between the frame being received by the 1394 stack, and the moment this
422          * frame is presented to the StreamProcessor.
423          *
424          * For transmit SP's this is the maximum time that a frame is requested by
425          * the handler ahead of the time the frame is intended to be transmitted.
426          *
427          * This is useful to figure out how longer than the actual reception time
428          * we have to wait before trying to read the frame from the SP.
429          *
430          * @return maximal frame latency
431          */
432         int getMaxFrameLatency();
433
434         float getTicksPerFrame();
435
436         int getLastCycle() {return m_last_cycle;};
437
438         int getBufferFill();
439
440         // Child implementation interface
441         /**
442         * @brief prepare the child SP
443         * @return true if successful, false otherwise
444         * @pre the m_manager pointer points to a valid manager
445         * @post getEventsPerFrame() returns the correct value
446         * @post getEventSize() returns the correct value
447         * @post getUpdatePeriod() returns the correct value
448         * @post processPacketHeader(...) can be called
449         * @post processPacketData(...) can be called
450         */
451         virtual bool prepareChild() = 0;
452         /**
453          * @brief get the number of events contained in one frame
454          * @return the number of events contained in one frame
455          */
456         virtual unsigned int getEventsPerFrame() = 0;
457
458         /**
459          * @brief get the size of one frame in bytes
460          * @return the size of one frame in bytes
461          */
462         virtual unsigned int getEventSize() = 0;
463
464         /**
465          * @brief get the nominal number of frames in a packet
466          *
467          * This is the amount of frames that is nominally present
468          * in one packet. It is recommended that in the receive handler
469          * you write this amount of frames when a valid packet has
470          * been received. (although this is not mandatory)
471          *
472          * @return the nominal number of frames in a packet
473          */
474         virtual unsigned int getNominalFramesPerPacket() = 0;
475
476         /**
477          * @brief get the nominal number of packets needed for a certain amount of frames
478          * @return the nominal number of packet necessary
479          */
480         virtual unsigned int getNominalPacketsNeeded(unsigned int nframes);
481
482         /**
483          * @brief returns the actual frame rate as calculated by the SP's DLL
484          * @return the actual frame rate as detected by the DLL
485          */
486         float getActualRate()
487             {return m_data_buffer->getRate();};
488
489     protected:
490         float m_ticks_per_frame;
491         int m_last_cycle;
492         unsigned int m_sync_delay;
493     private:
494         bool m_in_xrun;
495         sem_t m_signal_semaphore;
496         unsigned int m_signal_period;
497         unsigned int m_signal_offset;
498
499 public:
500     // debug stuff
501     virtual void dumpInfo();
502     virtual void setVerboseLevel(int l);
503     const char *getStateString()
504         {return ePSToString(getState());};
505     const char *getTypeString()
506         {return ePTToString(getType());};
507     StreamStatistics m_PacketStat;
508     StreamStatistics m_PeriodStat;
509     StreamStatistics m_WakeupStat;
510     DECLARE_DEBUG_MODULE;
511 };
512
513 }
514
515 #endif /* __FFADO_STREAMPROCESSOR__ */
516
517
Note: See TracBrowser for help on using the browser.