root/branches/ppalmers-streaming/src/libstreaming/generic/StreamProcessor.h

Revision 729, 16.5 kB (checked in by ppalmers, 14 years ago)

some more transmit tweaks

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 library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License version 2.1, as published by the Free Software Foundation;
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21  * MA 02110-1301 USA
22  */
23
24 #ifndef __FFADO_STREAMPROCESSOR__
25 #define __FFADO_STREAMPROCESSOR__
26
27 #include "IsoStream.h"
28 #include "PortManager.h"
29
30 #include "libutil/StreamStatistics.h"
31 #include "libutil/TimestampedBuffer.h"
32 #include "libutil/OptionContainer.h"
33
34 #include "debugmodule/debugmodule.h"
35
36 #include <pthread.h>
37
38 namespace Streaming {
39
40     class StreamProcessorManager;
41 /*!
42 \brief Class providing a generic interface for Stream Processors
43
44  A stream processor multiplexes or demultiplexes an ISO stream into a
45  collection of ports. This class should be subclassed, and the relevant
46  functions should be overloaded.
47
48 */
49 class StreamProcessor : public IsoStream,
50                         public PortManager,
51                         public Util::TimestampedBufferClient,
52                         public Util::OptionContainer
53 {
54
55     friend class StreamProcessorManager; // FIXME: get rid of this
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(enum eProcessorType type, int port);
134     virtual ~StreamProcessor();
135
136 public: // the public receive/transmit functions
137     // the transmit interface accepts frames and provides packets
138     // implement these for a transmit SP
139     // leave default for a receive SP
140
141     // the receive interface accepts packets and provides frames
142     // these are implemented by the parent SP
143     enum raw1394_iso_disposition
144         putPacket(unsigned char *data, unsigned int length,
145                   unsigned char channel, unsigned char tag, unsigned char sy,
146                   unsigned int cycle, unsigned int dropped);
147
148     enum raw1394_iso_disposition
149     getPacket(unsigned char *data, unsigned int *length,
150                 unsigned char *tag, unsigned char *sy,
151                 int cycle, unsigned int dropped, unsigned int max_length);
152
153     bool getFrames(unsigned int nbframes, int64_t ts); ///< transfer the buffer contents to the client
154     bool putFrames(unsigned int nbframes, int64_t ts); ///< transfer the client contents to the buffer
155
156     /**
157      * @brief drop nframes from the internal buffer as if they were transferred to the client side
158      *
159      * Gets nframes of frames from the buffer as done by getFrames(), but does not transfer them
160      * to the client side. Instead they are discarded.
161      *
162      * @param nframes number of frames
163      * @return true if the operation was successful
164      */
165     bool dropFrames(unsigned int nframes, int64_t ts);
166
167     /**
168      * @brief put silence frames into the internal buffer
169      *
170      * Puts nframes of frames into the buffer as done by putFrames(), but does not transfer them
171      * from the client side. Instead, silent frames are used.
172      *
173      * @param nframes number of frames
174      * @return true if the operation was successful
175      */
176     bool putSilenceFrames(unsigned int nbframes, int64_t ts);
177    
178     /**
179      * @brief Shifts the stream with the specified number of frames
180      *
181      * Used to align several streams to each other. It comes down to
182      * making sure the head timestamp corresponds to the timestamp of
183      * one master stream
184      *
185      * @param nframes the number of frames to shift
186      * @return true if successful
187      */
188     bool shiftStream(int nframes);
189 protected: // the helper receive/transmit functions
190     enum eChildReturnValue {
191         eCRV_OK,
192         eCRV_Invalid,
193         eCRV_Packet,
194         eCRV_EmptyPacket,
195         eCRV_XRun,
196         eCRV_Again,
197     };
198     // to be implemented by the children
199     // the following methods are to be implemented by receive SP subclasses
200     virtual enum eChildReturnValue processPacketHeader(unsigned char *data, unsigned int length,
201                                      unsigned char channel, unsigned char tag,
202                                      unsigned char sy, unsigned int cycle,
203                                      unsigned int dropped)
204         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
205     virtual enum eChildReturnValue processPacketData(unsigned char *data, unsigned int length,
206                                    unsigned char channel, unsigned char tag,
207                                    unsigned char sy, unsigned int cycle,
208                                    unsigned int dropped)
209         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
210     virtual bool processReadBlock(char *data, unsigned int nevents, unsigned int offset)
211         {debugWarning("call not allowed\n"); return false;};
212     virtual bool provideSilenceBlock(unsigned int nevents, unsigned int offset)
213         {debugWarning("call not allowed\n"); return false;};
214
215     // the following methods are to be implemented by transmit SP subclasses
216     virtual enum eChildReturnValue generatePacketHeader(unsigned char *data, unsigned int *length,
217                                       unsigned char *tag, unsigned char *sy,
218                                       int cycle, unsigned int dropped,
219                                       unsigned int max_length)
220         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
221     virtual enum eChildReturnValue generatePacketData(unsigned char *data, unsigned int *length,
222                                     unsigned char *tag, unsigned char *sy,
223                                     int cycle, unsigned int dropped,
224                                     unsigned int max_length)
225         {debugWarning("call not allowed\n"); return eCRV_Invalid;};
226     virtual enum eChildReturnValue generateSilentPacketHeader(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 generateSilentPacketData(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 bool processWriteBlock(char *data, unsigned int nevents, unsigned int offset)
237         {debugWarning("call not allowed\n"); return false;};
238     virtual bool transmitSilenceBlock(char *data, unsigned int nevents, unsigned int offset)
239         {debugWarning("call not allowed\n"); return false;};
240
241 private:
242     bool getFramesDry(unsigned int nbframes, int64_t ts);
243     bool getFramesWet(unsigned int nbframes, int64_t ts);
244     bool putFramesDry(unsigned int nbframes, int64_t ts);
245     bool putFramesWet(unsigned int nbframes, int64_t ts);
246
247     bool transferSilence(unsigned int size);
248
249     // move to private?
250     bool xrunOccurred() { return m_in_xrun; };
251
252 protected: // FIXME: move to private
253     uint64_t m_dropped; /// FIXME:debug
254     uint64_t m_last_dropped; /// FIXME:debug
255     int m_last_good_cycle; /// FIXME:debug
256     uint64_t m_last_timestamp; /// last timestamp (in ticks)
257     uint64_t m_last_timestamp2; /// last timestamp (in ticks)
258     uint64_t m_last_timestamp_at_period_ticks;
259
260 //--- data buffering and accounting
261 public:
262     void getBufferHeadTimestamp ( ffado_timestamp_t *ts, signed int *fc )
263         {m_data_buffer->getBufferHeadTimestamp(ts, fc);};
264     void getBufferTailTimestamp ( ffado_timestamp_t *ts, signed int *fc )
265         {m_data_buffer->getBufferTailTimestamp(ts, fc);};
266
267     void setBufferTailTimestamp ( ffado_timestamp_t new_timestamp )
268         {m_data_buffer->setBufferTailTimestamp(new_timestamp);};
269     void setBufferHeadTimestamp ( ffado_timestamp_t new_timestamp )
270         {m_data_buffer->setBufferHeadTimestamp(new_timestamp);};
271 protected:
272     Util::TimestampedBuffer *m_data_buffer;
273     // the scratch buffer is temporary buffer space that can be
274     // used by any function. It's pre-allocated when the SP is created.
275     // the purpose is to avoid allocation of memory (or heap/stack) in
276     // an RT context
277     byte_t*         m_scratch_buffer;
278     size_t          m_scratch_buffer_size_bytes;
279 protected:
280     StreamProcessorManager *m_manager;
281
282     // frame counter & sync stuff
283     public:
284         /**
285          * @brief Can this StreamProcessor handle a transfer of nframes frames?
286          *
287          * this function indicates if the streamprocessor can handle a transfer of
288          * nframes frames. It is used to detect underruns-to-be.
289          *
290          * @param nframes number of frames
291          * @return true if the StreamProcessor can handle this amount of frames
292          *         false if it can't
293          */
294         bool canClientTransferFrames(unsigned int nframes);
295
296         /**
297          * \brief return the time until the next period boundary should be signaled (in microseconds)
298          *
299          * Return the time until the next period boundary signal. If this StreamProcessor
300          * is the current synchronization source, this function is called to
301          * determine when a buffer transfer can be made. When this value is
302          * smaller than 0, a period boundary is assumed to be crossed, hence a
303          * transfer can be made.
304          *
305          * \return the time in usecs
306          */
307         int64_t getTimeUntilNextPeriodSignalUsecs();
308         /**
309          * \brief return the time of the next period boundary (in microseconds)
310          *
311          * Returns the time of the next period boundary, in microseconds. The
312          * goal of this function is to determine the exact point of the period
313          * boundary. This is assumed to be the point at which the buffer transfer should
314          * take place, meaning that it can be used as a reference timestamp for transmitting
315          * StreamProcessors
316          *
317          * \return the time in usecs
318          */
319         uint64_t getTimeAtPeriodUsecs();
320
321         /**
322          * \brief return the time of the next period boundary (in internal units)
323          *
324          * The same as getTimeAtPeriodUsecs() but in internal units.
325          *
326          * @return the time in internal units
327          */
328         uint64_t getTimeAtPeriod();
329
330         uint64_t getTimeNow(); // FIXME: should disappear
331
332
333         /**
334          * Returns the sync delay. This is the time a syncsource
335          * delays a period signal, e.g. to cope with buffering.
336          * @return the sync delay
337          */
338         int getSyncDelay() {return m_sync_delay;};
339         /**
340          * sets the sync delay
341          * @param d sync delay
342          */
343         void setSyncDelay(int d);
344
345         /**
346          * @brief get the maximal frame latency
347          *
348          * The maximum frame latency is the maximum time that will elapse
349          * between the frame being received by the 1394 stack, and the moment this
350          * frame is presented to the StreamProcessor.
351          *
352          * For transmit SP's this is the maximum time that a frame is requested by
353          * the handler ahead of the time the frame is intended to be transmitted.
354          *
355          * This is useful to figure out how longer than the actual reception time
356          * we have to wait before trying to read the frame from the SP.
357          *
358          * @return maximal frame latency
359          */
360         int getMaxFrameLatency();
361
362         float getTicksPerFrame();
363
364         int getLastCycle() {return m_last_cycle;};
365
366         int getBufferFill();
367
368         // Child implementation interface
369         /**
370         * @brief prepare the child SP
371         * @return true if successful, false otherwise
372         * @pre the m_manager pointer points to a valid manager
373         * @post getEventsPerFrame() returns the correct value
374         * @post getEventSize() returns the correct value
375         * @post getUpdatePeriod() returns the correct value
376         * @post processPacketHeader(...) can be called
377         * @post processPacketData(...) can be called
378         */
379         virtual bool prepareChild() = 0;
380         /**
381          * @brief get the number of events contained in one frame
382          * @return the number of events contained in one frame
383          */
384         virtual unsigned int getEventsPerFrame() = 0;
385
386         /**
387          * @brief get the size of one frame in bytes
388          * @return the size of one frame in bytes
389          */
390         virtual unsigned int getEventSize() = 0;
391
392         /**
393          * @brief get the nominal number of frames in a packet
394          * @return the nominal number of frames in a packet
395          */
396         virtual unsigned int getNominalFramesPerPacket() = 0;
397
398         /**
399          * @brief get the nominal number of packets needed for a certain amount of frames
400          * @return the nominal number of packet necessary
401          */
402         virtual unsigned int getNominalPacketsNeeded(unsigned int nframes) = 0;
403
404     protected:
405         float m_ticks_per_frame;
406         int m_last_cycle;
407         int m_sync_delay;
408     private:
409         bool m_in_xrun;
410
411 protected: // SPM related
412     void setManager(StreamProcessorManager *manager) {m_manager=manager;};
413     void clearManager() {m_manager=NULL;};
414
415 public:
416     // debug stuff
417     virtual void dumpInfo();
418     virtual void setVerboseLevel(int l);
419     const char *getStateString()
420         {return ePSToString(getState());};
421     const char *getTypeString()
422         {return ePTToString(getType());};
423     StreamStatistics m_PacketStat;
424     StreamStatistics m_PeriodStat;
425     StreamStatistics m_WakeupStat;
426     DECLARE_DEBUG_MODULE;
427 };
428
429 }
430
431 #endif /* __FFADO_STREAMPROCESSOR__ */
432
433
Note: See TracBrowser for help on using the browser.