root/trunk/libffado/src/libieee1394/IsoHandler.cpp

Revision 930, 17.6 kB (checked in by ppalmers, 16 years ago)

Fix latency/reliability issue.
Preliminary tests indicate that this runs fine with
jackd -R -P60 -d firewire -v4 -p64 -n3
which corresponds to 331 frames of roundtrip latency on the quatafire.

For reference:
jackd -R -P60 -d freebob -p64 -n2
results in 355 frames for the same device

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 #include "config.h"
25
26 #include "IsoHandler.h"
27 #include "ieee1394service.h"
28
29 #include "libstreaming/generic/StreamProcessor.h"
30 #include "libutil/PosixThread.h"
31
32 #include <errno.h>
33 #include <netinet/in.h>
34 #include <assert.h>
35 #include <unistd.h>
36 #include <string.h>
37
38 #include <iostream>
39 using namespace std;
40 using namespace Streaming;
41
42 IMPL_DEBUG_MODULE( IsoHandler, IsoHandler, DEBUG_LEVEL_NORMAL );
43
44 /* the C callbacks */
45 enum raw1394_iso_disposition
46 IsoHandler::iso_transmit_handler(raw1394handle_t handle,
47         unsigned char *data, unsigned int *length,
48         unsigned char *tag, unsigned char *sy,
49         int cycle, unsigned int dropped1) {
50
51     IsoHandler *xmitHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
52     assert(xmitHandler);
53     unsigned int skipped = (dropped1 & 0xFFFF0000) >> 16;
54     unsigned int dropped = dropped1 & 0xFFFF;
55
56     return xmitHandler->getPacket(data, length, tag, sy, cycle, dropped, skipped);
57 }
58
59 enum raw1394_iso_disposition
60 IsoHandler::iso_receive_handler(raw1394handle_t handle, unsigned char *data,
61                         unsigned int length, unsigned char channel,
62                         unsigned char tag, unsigned char sy, unsigned int cycle,
63                         unsigned int dropped1) {
64
65     IsoHandler *recvHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
66     assert(recvHandler);
67
68     unsigned int skipped = (dropped1 & 0xFFFF0000) >> 16;
69     unsigned int dropped = dropped1 & 0xFFFF;
70
71     return recvHandler->putPacket(data, length, channel, tag, sy, cycle, dropped, skipped);
72 }
73
74 int IsoHandler::busreset_handler(raw1394handle_t handle, unsigned int generation)
75 {
76     debugOutput( DEBUG_LEVEL_VERBOSE, "Busreset happened, generation %d...\n", generation);
77
78     IsoHandler *handler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
79     assert(handler);
80     return handler->handleBusReset(generation);
81 }
82
83 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t)
84    : m_manager( manager )
85    , m_type ( t )
86    , m_handle( 0 )
87    , m_buf_packets( 400 )
88    , m_max_packet_size( 1024 )
89    , m_irq_interval( -1 )
90    , m_Client( 0 )
91    , m_speed( RAW1394_ISO_SPEED_400 )
92    , m_prebuffers( 0 )
93    , m_State( E_Created )
94 #ifdef DEBUG
95    , m_packets ( 0 )
96 #endif
97 {
98 }
99
100 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t,
101                        unsigned int buf_packets, unsigned int max_packet_size, int irq)
102    : m_manager( manager )
103    , m_type ( t )
104    , m_handle( 0 )
105    , m_buf_packets( buf_packets )
106    , m_max_packet_size( max_packet_size )
107    , m_irq_interval( irq )
108    , m_Client( 0 )
109    , m_speed( RAW1394_ISO_SPEED_400 )
110    , m_prebuffers( 0 )
111    , m_State( E_Created )
112 #ifdef DEBUG
113    , m_packets ( 0 )
114 #endif
115 {
116 }
117
118 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t, unsigned int buf_packets,
119                        unsigned int max_packet_size, int irq,
120                        enum raw1394_iso_speed speed)
121    : m_manager( manager )
122    , m_type ( t )
123    , m_handle( 0 )
124    , m_buf_packets( buf_packets )
125    , m_max_packet_size( max_packet_size )
126    , m_irq_interval( irq )
127    , m_Client( 0 )
128    , m_speed( speed )
129    , m_prebuffers( 0 )
130    , m_State( E_Created )
131 #ifdef DEBUG
132    , m_packets ( 0 )
133 #endif
134 {
135 }
136
137 IsoHandler::~IsoHandler() {
138 // Don't call until libraw1394's raw1394_new_handle() function has been
139 // fixed to correctly initialise the iso_packet_infos field.  Bug is
140 // confirmed present in libraw1394 1.2.1.  In any case,
141 // raw1394_destroy_handle() will do any iso system shutdown required.
142 //     raw1394_iso_shutdown(m_handle);
143     if(m_handle) {
144         if (m_State == E_Running) {
145             disable();
146         }
147         raw1394_destroy_handle(m_handle);
148     }
149 }
150
151 bool
152 IsoHandler::waitForClient()
153 {
154     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "waiting...\n");
155     if(m_Client) {
156         bool result;
157         if (m_type == eHT_Receive) {
158             result = m_Client->waitForProducePacket();
159         } else {
160             result = m_Client->waitForConsumePacket();
161         }
162         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
163         return result;
164     } else {
165         debugOutputExtreme(DEBUG_LEVEL_VERBOSE, " no client\n");
166     }
167     return false;
168 }
169
170 bool
171 IsoHandler::tryWaitForClient()
172 {
173     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "waiting...\n");
174     if(m_Client) {
175         bool result;
176         if (m_type == eHT_Receive) {
177             result = m_Client->canProducePacket();
178         } else {
179             result = m_Client->canConsumePacket();
180         }
181         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
182         return result;
183     } else {
184         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " no client\n");
185     }
186     return false;
187 }
188 /*
189 bool
190 IsoHandler::Execute()
191 {
192     debugOutputExtreme( DEBUG_LEVEL_VERY_VERBOSE, "%p: Execute thread...\n", this);
193
194     // bypass if not running
195     if (m_State != E_Running) {
196         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: not polling since not running...\n", this);
197         usleep(m_poll_timeout * 1000);
198         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: done sleeping...\n", this);
199         return true;
200     }
201
202     // wait for the availability of frames in the client
203     // (blocking for transmit handlers)
204     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) Waiting for Client activity...\n", this, getTypeString());
205     if (waitForClient()) {
206 #if ISOHANDLER_USE_POLL
207         bool result = true;
208         while(result && m_Client && tryWaitForClient()) {
209             int err = poll(&m_poll_fd, 1, m_poll_timeout);
210             if (err == -1) {
211                 if (errno == EINTR) {
212                     return true;
213                 }
214                 debugFatal("%p, poll error: %s\n", this, strerror (errno));
215                 return false;
216             }
217
218             if(m_poll_fd.revents & (POLLIN)) {
219                 result=iterate();
220                 if(!result) {
221                     debugOutput( DEBUG_LEVEL_VERBOSE,
222                                 "IsoHandler (%p): Failed to iterate handler\n",
223                                 this);
224                 }
225             } else {
226                 if (m_poll_fd.revents & POLLERR) {
227                     debugWarning("error on fd for %p\n", this);
228                 }
229                 if (m_poll_fd.revents & POLLHUP) {
230                     debugWarning("hangup on fd for %p\n",this);
231                 }
232                 break;
233             }
234         }
235         return result;
236 #else
237         // iterate() is blocking if no 1394 data is available
238         // so poll'ing is not really necessary
239         bool result = true;
240         while(result && m_Client && tryWaitForClient()) {
241             result = iterate();
242 //             if (getType() == eHT_Receive) {
243 //                 debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) Iterate returned: %d\n",
244 //                             this, (m_type==eHT_Receive?"Receive":"Transmit"), result);
245 //             }
246         }
247         return result;
248 #endif
249     } else {
250         debugError("waitForClient() failed.\n");
251         return false;
252     }
253 }*/
254
255 bool
256 IsoHandler::iterate() {
257     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) Iterating ISO handler...\n",
258                 this, getTypeString());
259     if(m_State == E_Running) {
260 #if ISOHANDLER_FLUSH_BEFORE_ITERATE
261         flush();
262 #endif
263         if(raw1394_loop_iterate(m_handle)) {
264             debugError( "IsoHandler (%p): Failed to iterate handler: %s\n",
265                         this, strerror(errno));
266             return false;
267         }
268         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) done interating ISO handler...\n",
269                            this, getTypeString());
270         return true;
271     } else {
272         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Not iterating a non-running handler...\n",
273                     this, getTypeString());
274         return false;
275     }
276 }
277
278 bool
279 IsoHandler::init()
280 {
281     debugOutput( DEBUG_LEVEL_VERBOSE, "IsoHandler (%p) enter...\n",this);
282     // check the state
283     if(m_State != E_Created) {
284         debugError("Incorrect state, expected E_Created, got %d\n",(int)m_State);
285         return false;
286     }
287
288     // the main handle for the ISO traffic
289     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
290     if ( !m_handle ) {
291         if ( !errno ) {
292             debugError("libraw1394 not compatible\n");
293         } else {
294             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
295             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
296         }
297         return false;
298     }
299     raw1394_set_userdata(m_handle, static_cast<void *>(this));
300
301     // bus reset handling
302     if(raw1394_busreset_notify (m_handle, RAW1394_NOTIFY_ON)) {
303         debugWarning("Could not enable busreset notification.\n");
304         debugWarning(" Error message: %s\n",strerror(errno));
305         debugWarning("Continuing without bus reset support.\n");
306     } else {
307         // apparently this cannot fail
308         raw1394_set_bus_reset_handler(m_handle, busreset_handler);
309     }
310
311     // update the internal state
312     m_State=E_Initialized;
313     return true;
314 }
315
316 bool IsoHandler::disable()
317 {
318     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) enter...\n",
319                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
320
321     // check state
322     if(m_State == E_Prepared) return true;
323     if(m_State != E_Running) {
324         debugError("Incorrect state, expected E_Running, got %d\n",(int)m_State);
325         return false;
326     }
327
328     // this is put here to try and avoid the
329     // Runaway context problem
330     // don't know if it will help though.
331     raw1394_iso_xmit_sync(m_handle);
332     raw1394_iso_stop(m_handle);
333     m_State = E_Prepared;
334     return true;
335 }
336
337 /**
338  * Bus reset handler
339  *
340  * @return ?
341  */
342
343 int
344 IsoHandler::handleBusReset(unsigned int generation)
345 {
346     debugOutput( DEBUG_LEVEL_VERBOSE, "bus reset...\n");
347
348     #define CSR_CYCLE_TIME            0x200
349     #define CSR_REGISTER_BASE  0xfffff0000000ULL
350     // do a simple read on ourself in order to update the internal structures
351     // this avoids read failures after a bus reset
352     quadlet_t buf=0;
353     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
354                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
355     return 0;
356 }
357
358 void IsoHandler::dumpInfo()
359 {
360     int channel=-1;
361     if (m_Client) channel=m_Client->getChannel();
362
363     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
364             getTypeString());
365     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
366             m_manager.get1394Service().getPort(), channel);
367     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
368             m_buf_packets, m_max_packet_size, m_irq_interval);
369     if (this->getType() == eHT_Transmit) {
370         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed, PreBuffers...........: %2d, %2d\n",
371                                             m_speed, m_prebuffers);
372     }
373 }
374
375 void IsoHandler::setVerboseLevel(int l)
376 {
377     setDebugLevel(l);
378 }
379
380 bool IsoHandler::registerStream(StreamProcessor *stream)
381 {
382     assert(stream);
383     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
384
385     if (m_Client) {
386             debugFatal( "Generic IsoHandlers can have only one client\n");
387             return false;
388     }
389     m_Client=stream;
390     return true;
391 }
392
393 bool IsoHandler::unregisterStream(StreamProcessor *stream)
394 {
395     assert(stream);
396     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
397
398     if(stream != m_Client) {
399             debugFatal( "no client registered\n");
400             return false;
401     }
402     m_Client=0;
403     return true;
404 }
405
406 void IsoHandler::flush()
407 {
408     if(m_type == eHT_Receive) {
409         raw1394_iso_recv_flush(m_handle);
410     } else {
411         // do nothing
412     }
413 }
414
415 // ISO packet interface
416 enum raw1394_iso_disposition IsoHandler::putPacket(
417                     unsigned char *data, unsigned int length,
418                     unsigned char channel, unsigned char tag, unsigned char sy,
419                     unsigned int cycle, unsigned int dropped, unsigned int skipped) {
420
421     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
422                        "received packet: length=%d, channel=%d, cycle=%d\n",
423                        length, channel, cycle);
424     #ifdef DEBUG
425     m_packets++;
426     if (length > m_max_packet_size) {
427         debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
428                      this, getTypeString(), length, m_max_packet_size);
429     }
430     #endif
431     if(m_Client) {
432         return m_Client->putPacket(data, length, channel, tag, sy, cycle, dropped, skipped);
433     }
434
435     return RAW1394_ISO_OK;
436 }
437
438
439 enum raw1394_iso_disposition
440 IsoHandler::getPacket(unsigned char *data, unsigned int *length,
441                       unsigned char *tag, unsigned char *sy,
442                       int cycle, unsigned int dropped, unsigned int skipped) {
443
444     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
445                        "sending packet: length=%d, cycle=%d\n",
446                        *length, cycle);
447     #ifdef DEBUG
448     m_packets++;
449     #endif
450     if(m_Client) {
451         enum raw1394_iso_disposition retval;
452         retval = m_Client->getPacket(data, length, tag, sy, cycle, dropped, skipped, m_max_packet_size);
453         #ifdef DEBUG
454         if (*length > m_max_packet_size) {
455             debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
456                          this, getTypeString(), *length, m_max_packet_size);
457         }
458         #endif
459         return retval;
460     }
461     *tag = 0;
462     *sy = 0;
463     *length = 0;
464     return RAW1394_ISO_OK;
465 }
466
467 bool IsoHandler::prepare()
468 {
469     // check the state
470     if(m_State != E_Initialized) {
471         debugError("Incorrect state, expected E_Initialized, got %d\n",(int)m_State);
472         return false;
473     }
474
475     // Don't call until libraw1394's raw1394_new_handle() function has been
476     // fixed to correctly initialise the iso_packet_infos field.  Bug is
477     // confirmed present in libraw1394 1.2.1.
478     //     raw1394_iso_shutdown(m_handle);
479     m_State = E_Prepared;
480
481     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
482     dumpInfo();
483     if (getType() == eHT_Receive) {
484         if(m_irq_interval > 1) {
485             if(raw1394_iso_recv_init(m_handle,
486                                     iso_receive_handler,
487                                     m_buf_packets,
488                                     m_max_packet_size,
489                                     m_Client->getChannel(),
490 //                                     RAW1394_DMA_BUFFERFILL,
491                                     RAW1394_DMA_PACKET_PER_BUFFER,
492                                     m_irq_interval)) {
493                 debugFatal("Could not do receive initialisation (DMA_BUFFERFILL)!\n" );
494                 debugFatal("  %s\n",strerror(errno));
495                 return false;
496             }
497         } else {
498             if(raw1394_iso_recv_init(m_handle,
499                                     iso_receive_handler,
500                                     m_buf_packets,
501                                     m_max_packet_size,
502                                     m_Client->getChannel(),
503                                     RAW1394_DMA_PACKET_PER_BUFFER,
504                                     m_irq_interval)) {
505                 debugFatal("Could not do receive initialisation (PACKET_PER_BUFFER)!\n" );
506                 debugFatal("  %s\n",strerror(errno));
507                 return false;
508             }
509         }
510         return true;
511     } else {
512         if(raw1394_iso_xmit_init(m_handle,
513                                 iso_transmit_handler,
514                                 m_buf_packets,
515                                 m_max_packet_size,
516                                 m_Client->getChannel(),
517                                 m_speed,
518                                 m_irq_interval)) {
519             debugFatal("Could not do xmit initialisation!\n" );
520             return false;
521         }
522         return true;
523     }
524 }
525
526 bool IsoHandler::enable(int cycle)
527 {
528     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
529     // check the state
530     if(m_State != E_Prepared) {
531         if(!prepare()) {
532             debugFatal("Could not prepare handler\n");
533             return false;
534         }
535     }
536
537     if (getType() == eHT_Receive) {
538         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
539             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
540             dumpInfo();
541             return false;
542         }
543     } else {
544         if(raw1394_iso_xmit_start(m_handle, cycle, m_prebuffers)) {
545             debugFatal("Could not start xmit handler (%s)\n",strerror(errno));
546             dumpInfo();
547             return false;
548         }
549     }
550
551     m_State = E_Running;
552     return true;
553 }
554
555 /**
556  * @brief convert a EHandlerType to a string
557  * @param t the type
558  * @return a char * describing the state
559  */
560 const char *
561 IsoHandler::eHTToString(enum EHandlerType t) {
562     switch (t) {
563         case eHT_Receive: return "Receive";
564         case eHT_Transmit: return "Transmit";
565         default: return "error: unknown type";
566     }
567 }
Note: See TracBrowser for help on using the browser.