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

Revision 759, 16.1 kB (checked in by ppalmers, 13 years ago)

fix streaming problem

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