root/branches/api-cleanup/src/libstreaming/generic/StreamProcessor.h

Revision 809, 19.0 kB (checked in by ppalmers, 14 years ago)

First round of cleanup:
- make Ports auto-register to a PortManager?
- remove the different 'signal' types, everything is now period-signaled.
- removed obsolete streaming test programs

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