root/branches/api-cleanup/src/libieee1394/IsoHandler.cpp

Revision 821, 18.2 kB (checked in by ppalmers, 16 years ago)

make xrun hanling more robust

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