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

Revision 803, 17.3 kB (checked in by ppalmers, 13 years ago)

more reliable streaming. hackish, but a start for a better implementation

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_VERY_VERBOSE, "waiting...\n");
177     if(m_Client) {
178         bool result = m_Client->waitForFrames();
179         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
180         return result;
181     }
182     return false;
183 }
184
185 bool
186 IsoHandler::tryWaitForClient()
187 {
188     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "waiting...\n");
189     if(m_Client) {
190         bool result = m_Client->tryWaitForFrames();
191         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
192         return result;
193     }
194     return false;
195 }
196
197 bool
198 IsoHandler::Execute()
199 {
200     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "%p: Execute thread...\n", this);
201
202     // bypass if not running
203     if (m_State != E_Running) {
204         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: not polling since not running...\n", this);
205         usleep(m_poll_timeout * 1000);
206         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: done sleeping...\n", this);
207         return true;
208     }
209
210     // wait for the availability of frames in the client
211     // (blocking)
212     if (getType()==eHT_Receive || waitForClient()) {
213
214 #if ISOHANDLER_USE_POLL
215         uint64_t poll_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
216         err = poll(&m_poll_fd, 1, m_poll_timeout);
217         uint64_t poll_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
218         if (err == -1) {
219             if (errno == EINTR) {
220                 return true;
221             }
222             debugFatal("%p, poll error: %s\n", this, strerror (errno));
223             return false;
224         }
225         uint64_t iter_enter=0;
226         uint64_t iter_exit=0;
227         if(m_poll_fd.revents & (POLLIN)) {
228             iter_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
229             if(!iterate()) {
230                 debugOutput( DEBUG_LEVEL_VERBOSE,
231                             "IsoHandler (%p): Failed to iterate handler\n",
232                             this);
233                 return false;
234             }
235             iter_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
236         } else {
237             if (m_poll_fd.revents & POLLERR) {
238                 debugWarning("error on fd for %p\n", this);
239             }
240             if (m_poll_fd.revents & POLLHUP) {
241                 debugWarning("hangup on fd for %p\n",this);
242             }
243         }
244         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "(%c %p) poll took %lldus, iterate took %lldus\n",
245                     (getType()==eHT_Receive?'R':'X'), this,
246                     poll_exit-poll_enter, iter_exit-iter_enter);
247         return true;
248 #else
249         // iterate blocks if no 1394 data is available
250         // so poll'ing is not really necessary
251         bool result = iterate();
252         //usleep(125);
253         return result;
254 #endif
255     } else {
256         debugError("waitForClient() failed.\n");
257         return false;
258     }
259 }
260
261 bool
262 IsoHandler::iterate() {
263     //flush();
264     if(raw1394_loop_iterate(m_handle)) {
265         debugOutput( DEBUG_LEVEL_VERBOSE,
266                     "IsoHandler (%p): Failed to iterate handler: %s\n",
267                     this,strerror(errno));
268         return false;
269     }
270     return true;
271 }
272
273 bool
274 IsoHandler::setThreadParameters(bool rt, int priority) {
275     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
276     if (priority > 98) priority = 98; // cap the priority
277     m_realtime = rt;
278     m_priority = priority;
279
280     if (m_Thread) {
281         if (m_realtime) {
282             m_Thread->AcquireRealTime(m_priority);
283         } else {
284             m_Thread->DropRealTime();
285         }
286     }
287     return true;
288 }
289
290 bool
291 IsoHandler::init()
292 {
293     debugOutput( DEBUG_LEVEL_VERBOSE, "IsoHandler (%p) enter...\n",this);
294     // check the state
295     if(m_State != E_Created) {
296         debugError("Incorrect state, expected E_Created, got %d\n",(int)m_State);
297         return false;
298     }
299
300     // the main handle for the ISO traffic
301     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
302     if ( !m_handle ) {
303         if ( !errno ) {
304             debugError("libraw1394 not compatible\n");
305         } else {
306             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
307             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
308         }
309         return false;
310     }
311     raw1394_set_userdata(m_handle, static_cast<void *>(this));
312
313     // bus reset handling
314     if(raw1394_busreset_notify (m_handle, RAW1394_NOTIFY_ON)) {
315         debugWarning("Could not enable busreset notification.\n");
316         debugWarning(" Error message: %s\n",strerror(errno));
317         debugWarning("Continuing without bus reset support.\n");
318     } else {
319         // apparently this cannot fail
320         raw1394_set_bus_reset_handler(m_handle, busreset_handler);
321     }
322
323 #if ISOHANDLER_PER_HANDLER_THREAD
324     // create a thread to iterate ourselves
325     debugOutput( DEBUG_LEVEL_VERBOSE, "Start thread for %p...\n", this);
326     m_Thread = new Util::PosixThread(this, m_realtime, m_priority,
327                                      PTHREAD_CANCEL_DEFERRED);
328     if(!m_Thread) {
329         debugFatal("No thread\n");
330         return false;
331     }
332     if (m_Thread->Start() != 0) {
333         debugFatal("Could not start update thread\n");
334         return false;
335     }
336 #endif
337
338     // update the internal state
339     m_State=E_Initialized;
340     return true;
341 }
342
343 bool IsoHandler::disable()
344 {
345     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
346
347     // check state
348     if(m_State == E_Prepared) return true;
349     if(m_State != E_Running) {
350         debugError("Incorrect state, expected E_Running, got %d\n",(int)m_State);
351         return false;
352     }
353
354     m_poll_fd.events = 0;
355
356     // this is put here to try and avoid the
357     // Runaway context problem
358     // don't know if it will help though.
359     raw1394_iso_xmit_sync(m_handle);
360     raw1394_iso_stop(m_handle);
361     m_State = E_Prepared;
362     return true;
363 }
364
365 /**
366  * Bus reset handler
367  *
368  * @return ?
369  */
370
371 int
372 IsoHandler::handleBusReset(unsigned int generation)
373 {
374     debugOutput( DEBUG_LEVEL_VERBOSE, "bus reset...\n");
375
376     #define CSR_CYCLE_TIME            0x200
377     #define CSR_REGISTER_BASE  0xfffff0000000ULL
378     // do a simple read on ourself in order to update the internal structures
379     // this avoids read failures after a bus reset
380     quadlet_t buf=0;
381     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
382                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
383     return 0;
384 }
385
386 void IsoHandler::dumpInfo()
387 {
388     int channel=-1;
389     if (m_Client) channel=m_Client->getChannel();
390
391     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
392             (this->getType() == eHT_Receive ? "Receive" : "Transmit"));
393     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
394             m_manager.get1394Service().getPort(), channel);
395     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
396             m_buf_packets, m_max_packet_size, m_irq_interval);
397     if (this->getType() == eHT_Transmit) {
398         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed, PreBuffers...........: %2d, %2d\n",
399                                             m_speed, m_prebuffers);
400     }
401     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Packet count................: %10d (%5d dropped)\n",
402             this->getPacketCount(), this->getDroppedCount());
403 }
404
405 void IsoHandler::setVerboseLevel(int l)
406 {
407     setDebugLevel(l);
408     if(m_Thread) m_Thread->setVerboseLevel(l);
409 }
410
411 bool IsoHandler::registerStream(StreamProcessor *stream)
412 {
413     assert(stream);
414     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
415
416     if (m_Client) {
417             debugFatal( "Generic IsoHandlers can have only one client\n");
418             return false;
419     }
420     m_Client=stream;
421     return true;
422 }
423
424 bool IsoHandler::unregisterStream(StreamProcessor *stream)
425 {
426     assert(stream);
427     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
428
429     if(stream != m_Client) {
430             debugFatal( "no client registered\n");
431             return false;
432     }
433     m_Client=0;
434     return true;
435 }
436
437 void IsoHandler::flush()
438 {
439     if(m_type == eHT_Receive) {
440         raw1394_iso_recv_flush(m_handle);
441     } else {
442         // do nothing
443     }
444 }
445
446 // ISO packet interface
447 enum raw1394_iso_disposition IsoHandler::putPacket(
448                     unsigned char *data, unsigned int length,
449                     unsigned char channel, unsigned char tag, unsigned char sy,
450                     unsigned int cycle, unsigned int dropped) {
451
452     debugOutput( DEBUG_LEVEL_VERY_VERBOSE,
453                  "received packet: length=%d, channel=%d, cycle=%d\n",
454                  length, channel, cycle );
455     m_packetcount++;
456     m_dropped += dropped;
457
458     if(m_Client) {
459         return m_Client->putPacket(data, length, channel, tag, sy, cycle, dropped);
460     }
461
462     return RAW1394_ISO_OK;
463 }
464
465
466 enum raw1394_iso_disposition IsoHandler::getPacket(
467                     unsigned char *data, unsigned int *length,
468                     unsigned char *tag, unsigned char *sy,
469                     int cycle, unsigned int dropped) {
470
471     debugOutput( DEBUG_LEVEL_ULTRA_VERBOSE,
472                     "sending packet: length=%d, cycle=%d\n",
473                     *length, cycle );
474     m_packetcount++;
475     m_dropped += dropped;
476
477     if(m_Client) {
478         return m_Client->getPacket(data, length, tag, sy, cycle, dropped, m_max_packet_size);
479     }
480     return RAW1394_ISO_OK;
481 }
482
483 bool IsoHandler::prepare()
484 {
485     // check the state
486     if(m_State != E_Initialized) {
487         debugError("Incorrect state, expected E_Initialized, got %d\n",(int)m_State);
488         return false;
489     }
490
491     // Don't call until libraw1394's raw1394_new_handle() function has been
492     // fixed to correctly initialise the iso_packet_infos field.  Bug is
493     // confirmed present in libraw1394 1.2.1.
494     //     raw1394_iso_shutdown(m_handle);
495     m_State = E_Prepared;
496
497     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
498     dumpInfo();
499     if (getType() == eHT_Receive) {
500         if(m_irq_interval > 1) {
501             if(raw1394_iso_recv_init(m_handle,
502                                     iso_receive_handler,
503                                     m_buf_packets,
504                                     m_max_packet_size,
505                                     m_Client->getChannel(),
506 //                                     RAW1394_DMA_BUFFERFILL,
507                                     RAW1394_DMA_PACKET_PER_BUFFER,
508                                     m_irq_interval)) {
509                 debugFatal("Could not do receive initialisation (DMA_BUFFERFILL)!\n" );
510                 debugFatal("  %s\n",strerror(errno));
511                 return false;
512             }
513         } else {
514             if(raw1394_iso_recv_init(m_handle,
515                                     iso_receive_handler,
516                                     m_buf_packets,
517                                     m_max_packet_size,
518                                     m_Client->getChannel(),
519                                     RAW1394_DMA_PACKET_PER_BUFFER,
520                                     m_irq_interval)) {
521                 debugFatal("Could not do receive initialisation (PACKET_PER_BUFFER)!\n" );
522                 debugFatal("  %s\n",strerror(errno));
523                 return false;
524             }
525         }
526         return true;
527     } else {
528         if(raw1394_iso_xmit_init(m_handle,
529                                 iso_transmit_handler,
530                                 m_buf_packets,
531                                 m_max_packet_size,
532                                 m_Client->getChannel(),
533                                 m_speed,
534                                 m_irq_interval)) {
535             debugFatal("Could not do xmit initialisation!\n" );
536             return false;
537         }
538         return true;
539     }
540 }
541
542 bool IsoHandler::enable(int cycle)
543 {
544     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
545     // check the state
546     if(m_State != E_Prepared) {
547         if(!prepare()) {
548             debugFatal("Could not prepare handler\n");
549             return false;
550         }
551     }
552
553     if (getType() == eHT_Receive) {
554         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
555             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
556             dumpInfo();
557             return false;
558         }
559     } else {
560         if(raw1394_iso_xmit_start(m_handle, cycle, m_prebuffers)) {
561             debugFatal("Could not start xmit handler (%s)\n",strerror(errno));
562             dumpInfo();
563             return false;
564         }
565     }
566
567     m_poll_fd.events = POLLIN;
568     m_State = E_Running;
569     return true;
570 }
Note: See TracBrowser for help on using the browser.