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

Revision 766, 17.4 kB (checked in by ppalmers, 13 years ago)

introduce local references to frequently used objects

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