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

Revision 753, 17.3 kB (checked in by ppalmers, 16 years ago)

have separate threads for every handler

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