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

Revision 1036, 17.2 kB (checked in by ppalmers, 13 years ago)

remove cycle var where not needed. calculate full pkt_ctr in IsoHandler?

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