]> git.sesse.net Git - vlc/blob - modules/access/vcd/cdrom.c
Remove unneeded msg_Error about memory failure.
[vlc] / modules / access / vcd / cdrom.c
1 /****************************************************************************
2  * cdrom.c: cdrom tools
3  *****************************************************************************
4  * Copyright (C) 1998-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Johan Bilien <jobi@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_access.h>
35
36 #ifdef HAVE_UNISTD_H
37 #   include <unistd.h>
38 #endif
39
40 #include <errno.h>
41 #ifdef HAVE_SYS_TYPES_H
42 #   include <sys/types.h>
43 #endif
44 #ifdef HAVE_SYS_STAT_H
45 #   include <sys/stat.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #   include <fcntl.h>
49 #endif
50
51 #if defined( SYS_BSDI )
52 #   include <dvd.h>
53 #elif defined ( __APPLE__ )
54 #   include <CoreFoundation/CFBase.h>
55 #   include <IOKit/IOKitLib.h>
56 #   include <IOKit/storage/IOCDTypes.h>
57 #   include <IOKit/storage/IOCDMedia.h>
58 #   include <IOKit/storage/IOCDMediaBSDClient.h>
59 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
60 #   include <sys/inttypes.h>
61 #   include <sys/cdio.h>
62 #   include <sys/scsiio.h>
63 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
64 #   include <sys/cdio.h>
65 #   include <sys/cdrio.h>
66 #elif defined( WIN32 )
67 #   include <windows.h>
68 #   include <winioctl.h>
69 #elif defined (__linux__)
70 #   include <sys/ioctl.h>
71 #   include <linux/cdrom.h>
72 #else
73 #   error FIXME
74 #endif
75
76 #include "cdrom_internals.h"
77 #include "cdrom.h"
78 #include <vlc_charset.h>
79
80 /*****************************************************************************
81  * ioctl_Open: Opens a VCD device or file and returns an opaque handle
82  *****************************************************************************/
83 vcddev_t *ioctl_Open( vlc_object_t *p_this, const char *psz_dev )
84 {
85     int i_ret;
86     int b_is_file;
87     vcddev_t *p_vcddev;
88 #ifndef WIN32
89     struct stat fileinfo;
90 #endif
91
92     if( !psz_dev ) return NULL;
93
94     /*
95      *  Initialize structure with default values
96      */
97     p_vcddev = (vcddev_t *)malloc( sizeof(vcddev_t) );
98     if( p_vcddev == NULL )
99         return NULL;
100     p_vcddev->i_vcdimage_handle = -1;
101     p_vcddev->psz_dev = NULL;
102     b_is_file = 1;
103
104     /*
105      *  Check if we are dealing with a device or a file (vcd image)
106      */
107 #ifdef WIN32
108     if( (strlen( psz_dev ) == 2 && psz_dev[1] == ':') )
109     {
110         b_is_file = 0;
111     }
112
113 #else
114     if( stat( psz_dev, &fileinfo ) < 0 )
115     {
116         free( p_vcddev );
117         return NULL;
118     }
119
120     /* Check if this is a block/char device */
121     if( S_ISBLK( fileinfo.st_mode ) || S_ISCHR( fileinfo.st_mode ) )
122         b_is_file = 0;
123 #endif
124
125     if( b_is_file )
126     {
127         i_ret = OpenVCDImage( p_this, psz_dev, p_vcddev );
128     }
129     else
130     {
131         /*
132          *  open the vcd device
133          */
134
135 #ifdef WIN32
136         i_ret = win32_vcd_open( p_this, psz_dev, p_vcddev );
137 #else
138         p_vcddev->i_device_handle = -1;
139         p_vcddev->i_device_handle = open( psz_dev, O_RDONLY | O_NONBLOCK );
140         i_ret = (p_vcddev->i_device_handle == -1) ? -1 : 0;
141 #endif
142     }
143
144     if( i_ret == 0 )
145     {
146         p_vcddev->psz_dev = (char *)strdup( psz_dev );
147     }
148     else
149     {
150         free( p_vcddev );
151         p_vcddev = NULL;
152     }
153
154     return p_vcddev;
155 }
156
157 /*****************************************************************************
158  * ioctl_Close: Closes an already opened VCD device or file.
159  *****************************************************************************/
160 void ioctl_Close( vlc_object_t * p_this, vcddev_t *p_vcddev )
161 {
162     free( p_vcddev->psz_dev );
163
164     if( p_vcddev->i_vcdimage_handle != -1 )
165     {
166         /*
167          *  vcd image mode
168          */
169
170         CloseVCDImage( p_this, p_vcddev );
171         return;
172     }
173
174     /*
175      *  vcd device mode
176      */
177
178 #ifdef WIN32
179     if( p_vcddev->h_device_handle )
180         CloseHandle( p_vcddev->h_device_handle );
181     if( p_vcddev->hASPI )
182         FreeLibrary( (HMODULE)p_vcddev->hASPI );
183 #else
184     if( p_vcddev->i_device_handle != -1 )
185         close( p_vcddev->i_device_handle );
186 #endif
187 }
188
189 /*****************************************************************************
190  * ioctl_GetTracksMap: Read the Table of Content, fill in the pp_sectors map
191  *                     if pp_sectors is not null and return the number of
192  *                     tracks available.
193  *****************************************************************************/
194 int ioctl_GetTracksMap( vlc_object_t *p_this, const vcddev_t *p_vcddev,
195                         int **pp_sectors )
196 {
197     int i_tracks = 0;
198
199     if( p_vcddev->i_vcdimage_handle != -1 )
200     {
201         /*
202          *  vcd image mode
203          */
204
205         i_tracks = p_vcddev->i_tracks;
206
207         if( pp_sectors )
208         {
209             *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
210             if( *pp_sectors == NULL )
211                 return 0;
212             memcpy( *pp_sectors, p_vcddev->p_sectors,
213                     (i_tracks + 1) * sizeof(int) );
214         }
215
216         return i_tracks;
217     }
218     else
219     {
220
221         /*
222          *  vcd device mode
223          */
224
225 #if defined( __APPLE__ )
226
227         CDTOC *pTOC;
228         int i_descriptors;
229
230         if( ( pTOC = darwin_getTOC( p_this, p_vcddev ) ) == NULL )
231         {
232             msg_Err( p_this, "failed to get the TOC" );
233             return 0;
234         }
235
236         i_descriptors = CDTOCGetDescriptorCount( pTOC );
237         i_tracks = darwin_getNumberOfTracks( pTOC, i_descriptors );
238
239         if( pp_sectors )
240         {
241             int i, i_leadout = -1;
242             CDTOCDescriptor *pTrackDescriptors;
243             u_char track;
244
245             *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
246             if( *pp_sectors == NULL )
247             {
248                 darwin_freeTOC( pTOC );
249                 return 0;
250             }
251
252             pTrackDescriptors = pTOC->descriptors;
253
254             for( i_tracks = 0, i = 0; i < i_descriptors; i++ )
255             {
256                 track = pTrackDescriptors[i].point;
257
258                 if( track == 0xA2 )
259                     i_leadout = i;
260
261                 if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
262                     continue;
263
264                 (*pp_sectors)[i_tracks++] =
265                     CDConvertMSFToLBA( pTrackDescriptors[i].p );
266             }
267
268             if( i_leadout == -1 )
269             {
270                 msg_Err( p_this, "leadout not found" );
271                 free( *pp_sectors );
272                 darwin_freeTOC( pTOC );
273                 return 0;
274             }
275
276             /* set leadout sector */
277             (*pp_sectors)[i_tracks] =
278                 CDConvertMSFToLBA( pTrackDescriptors[i_leadout].p );
279         }
280
281         darwin_freeTOC( pTOC );
282
283 #elif defined( WIN32 )
284         if( p_vcddev->hASPI )
285         {
286             HANDLE hEvent;
287             struct SRB_ExecSCSICmd ssc;
288             uint8_t p_tocheader[ 4 ];
289
290             /* Create the transfer completion event */
291             hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
292             if( hEvent == NULL )
293             {
294                 return -1;
295             }
296
297             memset( &ssc, 0, sizeof( ssc ) );
298
299             ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
300             ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
301             ssc.SRB_HaId        = LOBYTE( p_vcddev->i_sid );
302             ssc.SRB_Target      = HIBYTE( p_vcddev->i_sid );
303             ssc.SRB_SenseLen    = SENSE_LEN;
304
305             ssc.SRB_PostProc = (LPVOID) hEvent;
306             ssc.SRB_CDBLen      = 10;
307
308             /* Operation code */
309             ssc.CDBByte[ 0 ] = READ_TOC;
310
311             /* Format */
312             ssc.CDBByte[ 2 ] = READ_TOC_FORMAT_TOC;
313
314             /* Starting track */
315             ssc.CDBByte[ 6 ] = 0;
316
317             /* Allocation length and buffer */
318             ssc.SRB_BufLen = sizeof( p_tocheader );
319             ssc.SRB_BufPointer  = p_tocheader;
320             ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
321             ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
322
323             /* Initiate transfer */
324             ResetEvent( hEvent );
325             p_vcddev->lpSendCommand( (void*) &ssc );
326
327             /* If the command has still not been processed, wait until it's
328              * finished */
329             if( ssc.SRB_Status == SS_PENDING )
330                 WaitForSingleObject( hEvent, INFINITE );
331
332             /* check that the transfer went as planned */
333             if( ssc.SRB_Status != SS_COMP )
334             {
335                 CloseHandle( hEvent );
336                 return 0;
337             }
338
339             i_tracks = p_tocheader[3] - p_tocheader[2] + 1;
340
341             if( pp_sectors )
342             {
343                 int i, i_toclength;
344                 uint8_t *p_fulltoc;
345
346                 i_toclength = 4 /* header */ + p_tocheader[0] +
347                               ((unsigned int)p_tocheader[1] << 8);
348
349                 p_fulltoc = malloc( i_toclength );
350                 *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
351
352                 if( *pp_sectors == NULL || p_fulltoc == NULL )
353                 {
354                     free( *pp_sectors );
355                     free( p_fulltoc );
356                     CloseHandle( hEvent );
357                     return 0;
358                 }
359
360                 /* Allocation length and buffer */
361                 ssc.SRB_BufLen = i_toclength;
362                 ssc.SRB_BufPointer  = p_fulltoc;
363                 ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
364                 ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
365
366                 /* Initiate transfer */
367                 ResetEvent( hEvent );
368                 p_vcddev->lpSendCommand( (void*) &ssc );
369
370                 /* If the command has still not been processed, wait until it's
371                  * finished */
372                 if( ssc.SRB_Status == SS_PENDING )
373                     WaitForSingleObject( hEvent, INFINITE );
374
375                 /* check that the transfer went as planned */
376                 if( ssc.SRB_Status != SS_COMP )
377                     i_tracks = 0;
378
379                 for( i = 0 ; i <= i_tracks ; i++ )
380                 {
381                     int i_index = 8 + 8 * i;
382                     (*pp_sectors)[ i ] = ((int)p_fulltoc[ i_index ] << 24) +
383                                          ((int)p_fulltoc[ i_index+1 ] << 16) +
384                                          ((int)p_fulltoc[ i_index+2 ] << 8) +
385                                          (int)p_fulltoc[ i_index+3 ];
386
387                     msg_Dbg( p_this, "p_sectors: %i, %i", i, (*pp_sectors)[i]);
388                 }
389
390                 free( p_fulltoc );
391             }
392
393             CloseHandle( hEvent );
394
395         }
396         else
397         {
398             DWORD dwBytesReturned;
399             CDROM_TOC cdrom_toc;
400
401             if( DeviceIoControl( p_vcddev->h_device_handle,
402                                  IOCTL_CDROM_READ_TOC,
403                                  NULL, 0, &cdrom_toc, sizeof(CDROM_TOC),
404                                  &dwBytesReturned, NULL ) == 0 )
405             {
406                 msg_Err( p_this, "could not read TOCHDR" );
407                 return 0;
408             }
409
410             i_tracks = cdrom_toc.LastTrack - cdrom_toc.FirstTrack + 1;
411
412             if( pp_sectors )
413             {
414                 int i;
415
416                 *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
417                 if( *pp_sectors == NULL )
418                     return 0;
419
420                 for( i = 0 ; i <= i_tracks ; i++ )
421                 {
422                     (*pp_sectors)[ i ] = MSF_TO_LBA2(
423                                            cdrom_toc.TrackData[i].Address[1],
424                                            cdrom_toc.TrackData[i].Address[2],
425                                            cdrom_toc.TrackData[i].Address[3] );
426                     msg_Dbg( p_this, "p_sectors: %i, %i", i, (*pp_sectors)[i]);
427                 }
428             }
429         }
430
431 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) \
432        || defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
433         struct ioc_toc_header tochdr;
434         struct ioc_read_toc_entry toc_entries;
435
436         if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCHEADER, &tochdr )
437             == -1 )
438         {
439             msg_Err( p_this, "could not read TOCHDR" );
440             return 0;
441         }
442
443         i_tracks = tochdr.ending_track - tochdr.starting_track + 1;
444
445         if( pp_sectors )
446         {
447              int i;
448
449              *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
450              if( *pp_sectors == NULL )
451                  return 0;
452
453              toc_entries.address_format = CD_LBA_FORMAT;
454              toc_entries.starting_track = 0;
455              toc_entries.data_len = ( i_tracks + 1 ) *
456                                         sizeof( struct cd_toc_entry );
457              toc_entries.data = (struct cd_toc_entry *)
458                                     malloc( toc_entries.data_len );
459              if( toc_entries.data == NULL )
460              {
461                  free( *pp_sectors );
462                  return 0;
463              }
464
465              /* Read the TOC */
466              if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCENTRYS,
467                         &toc_entries ) == -1 )
468              {
469                  msg_Err( p_this, "could not read the TOC" );
470                  free( *pp_sectors );
471                  free( toc_entries.data );
472                  return 0;
473              }
474
475              /* Fill the p_sectors structure with the track/sector matches */
476              for( i = 0 ; i <= i_tracks ; i++ )
477              {
478 #if defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
479                  /* FIXME: is this ok? */
480                  (*pp_sectors)[ i ] = toc_entries.data[i].addr.lba;
481 #else
482                  (*pp_sectors)[ i ] = ntohl( toc_entries.data[i].addr.lba );
483 #endif
484              }
485         }
486 #else
487         struct cdrom_tochdr   tochdr;
488         struct cdrom_tocentry tocent;
489
490         /* First we read the TOC header */
491         if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCHDR, &tochdr )
492             == -1 )
493         {
494             msg_Err( p_this, "could not read TOCHDR" );
495             return 0;
496         }
497
498         i_tracks = tochdr.cdth_trk1 - tochdr.cdth_trk0 + 1;
499
500         if( pp_sectors )
501         {
502             int i;
503
504             *pp_sectors = malloc( (i_tracks + 1) * sizeof(int) );
505             if( *pp_sectors == NULL )
506                 return 0;
507
508             /* Fill the p_sectors structure with the track/sector matches */
509             for( i = 0 ; i <= i_tracks ; i++ )
510             {
511                 tocent.cdte_format = CDROM_LBA;
512                 tocent.cdte_track =
513                     ( i == i_tracks ) ? CDROM_LEADOUT : tochdr.cdth_trk0 + i;
514
515                 if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCENTRY,
516                            &tocent ) == -1 )
517                 {
518                     msg_Err( p_this, "could not read TOCENTRY" );
519                     free( *pp_sectors );
520                     return 0;
521                 }
522
523                 (*pp_sectors)[ i ] = tocent.cdte_addr.lba;
524             }
525         }
526 #endif
527
528         return i_tracks;
529     }
530 }
531
532 /****************************************************************************
533  * ioctl_ReadSector: Read VCD or CDDA sectors
534  ****************************************************************************/
535 int ioctl_ReadSectors( vlc_object_t *p_this, const vcddev_t *p_vcddev,
536                        int i_sector, uint8_t *p_buffer, int i_nb, int i_type )
537 {
538     uint8_t *p_block;
539     int i;
540
541     if( i_type == VCD_TYPE ) p_block = malloc( VCD_SECTOR_SIZE * i_nb );
542     else p_block = p_buffer;
543
544     if( p_vcddev->i_vcdimage_handle != -1 )
545     {
546         /*
547          *  vcd image mode
548          */
549         if( lseek( p_vcddev->i_vcdimage_handle, i_sector * VCD_SECTOR_SIZE,
550                    SEEK_SET ) == -1 )
551         {
552             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
553             if( i_type == VCD_TYPE ) free( p_block );
554             return -1;
555         }
556
557         if( read( p_vcddev->i_vcdimage_handle, p_block, VCD_SECTOR_SIZE * i_nb)
558             == -1 )
559         {
560             msg_Err( p_this, "Could not read sector %d", i_sector );
561             if( i_type == VCD_TYPE ) free( p_block );
562             return -1;
563         }
564
565     }
566     else
567     {
568
569         /*
570          *  vcd device mode
571          */
572
573 #if defined( __APPLE__ )
574         dk_cd_read_t cd_read;
575
576         memset( &cd_read, 0, sizeof(cd_read) );
577
578         cd_read.offset = i_sector * VCD_SECTOR_SIZE;
579         cd_read.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader |
580                              kCDSectorAreaSubHeader | kCDSectorAreaUser |
581                              kCDSectorAreaAuxiliary;
582         cd_read.sectorType = kCDSectorTypeUnknown;
583
584         cd_read.buffer = p_block;
585         cd_read.bufferLength = VCD_SECTOR_SIZE * i_nb;
586
587         if( ioctl( p_vcddev->i_device_handle, DKIOCCDREAD, &cd_read ) == -1 )
588         {
589             msg_Err( p_this, "could not read block %d", i_sector );
590             if( i_type == VCD_TYPE ) free( p_block );
591             return -1;
592         }
593
594 #elif defined( WIN32 )
595         if( p_vcddev->hASPI )
596         {
597             HANDLE hEvent;
598             struct SRB_ExecSCSICmd ssc;
599
600             /* Create the transfer completion event */
601             hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
602             if( hEvent == NULL )
603             {
604                 if( i_type == VCD_TYPE ) free( p_block );
605                 return -1;
606             }
607
608             memset( &ssc, 0, sizeof( ssc ) );
609
610             ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
611             ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
612             ssc.SRB_HaId        = LOBYTE( p_vcddev->i_sid );
613             ssc.SRB_Target      = HIBYTE( p_vcddev->i_sid );
614             ssc.SRB_SenseLen    = SENSE_LEN;
615
616             ssc.SRB_PostProc = (LPVOID) hEvent;
617             ssc.SRB_CDBLen      = 12;
618
619             /* Operation code */
620             ssc.CDBByte[ 0 ] = READ_CD;
621
622             /* Sector type */
623             ssc.CDBByte[ 1 ] = i_type == VCD_TYPE ? SECTOR_TYPE_MODE2_FORM2 :
624                                                     SECTOR_TYPE_CDDA;
625
626             /* Start of LBA */
627             ssc.CDBByte[ 2 ] = ( i_sector >> 24 ) & 0xff;
628             ssc.CDBByte[ 3 ] = ( i_sector >> 16 ) & 0xff;
629             ssc.CDBByte[ 4 ] = ( i_sector >>  8 ) & 0xff;
630             ssc.CDBByte[ 5 ] = ( i_sector       ) & 0xff;
631
632             /* Transfer length */
633             ssc.CDBByte[ 6 ] = ( i_nb >> 16 ) & 0xff;
634             ssc.CDBByte[ 7 ] = ( i_nb >> 8  ) & 0xff;
635             ssc.CDBByte[ 8 ] = ( i_nb       ) & 0xff;
636
637             /* Data selection */
638             ssc.CDBByte[ 9 ] = i_type == VCD_TYPE ? READ_CD_RAW_MODE2 :
639                                                     READ_CD_USERDATA;
640
641             /* Result buffer */
642             ssc.SRB_BufPointer  = p_block;
643             ssc.SRB_BufLen = VCD_SECTOR_SIZE * i_nb;
644
645             /* Initiate transfer */
646             ResetEvent( hEvent );
647             p_vcddev->lpSendCommand( (void*) &ssc );
648
649             /* If the command has still not been processed, wait until it's
650              * finished */
651             if( ssc.SRB_Status == SS_PENDING )
652             {
653                 WaitForSingleObject( hEvent, INFINITE );
654             }
655             CloseHandle( hEvent );
656
657             /* check that the transfer went as planned */
658             if( ssc.SRB_Status != SS_COMP )
659             {
660                 if( i_type == VCD_TYPE ) free( p_block );
661                 return -1;
662             }
663         }
664         else
665         {
666             DWORD dwBytesReturned;
667             RAW_READ_INFO cdrom_raw;
668
669             /* Initialize CDROM_RAW_READ structure */
670             cdrom_raw.DiskOffset.QuadPart = CD_SECTOR_SIZE * i_sector;
671             cdrom_raw.SectorCount = i_nb;
672             cdrom_raw.TrackMode =  i_type == VCD_TYPE ? XAForm2 : CDDA;
673
674             if( DeviceIoControl( p_vcddev->h_device_handle,
675                                  IOCTL_CDROM_RAW_READ, &cdrom_raw,
676                                  sizeof(RAW_READ_INFO), p_block,
677                                  VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
678                                  NULL ) == 0 )
679             {
680                 if( i_type == VCD_TYPE )
681                 {
682                     /* Retry in YellowMode2 */
683                     cdrom_raw.TrackMode = YellowMode2;
684                     if( DeviceIoControl( p_vcddev->h_device_handle,
685                                  IOCTL_CDROM_RAW_READ, &cdrom_raw,
686                                  sizeof(RAW_READ_INFO), p_block,
687                                  VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
688                                  NULL ) == 0 )
689                     {
690                         free( p_block );
691                         return -1;
692                     }
693                 }
694                 else return -1;
695             }
696         }
697
698 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
699         struct scsireq  sc;
700         int i_ret;
701
702         memset( &sc, 0, sizeof(sc) );
703         sc.cmd[0] = 0xBE;
704         sc.cmd[1] = i_type == VCD_TYPE ? SECTOR_TYPE_MODE2_FORM2:
705                                          SECTOR_TYPE_CDDA;
706         sc.cmd[2] = (i_sector >> 24) & 0xff;
707         sc.cmd[3] = (i_sector >> 16) & 0xff;
708         sc.cmd[4] = (i_sector >>  8) & 0xff;
709         sc.cmd[5] = (i_sector >>  0) & 0xff;
710         sc.cmd[6] = (i_nb >> 16) & 0xff;
711         sc.cmd[7] = (i_nb >>  8) & 0xff;
712         sc.cmd[8] = (i_nb      ) & 0xff;
713         sc.cmd[9] = i_type == VCD_TYPE ? READ_CD_RAW_MODE2 : READ_CD_USERDATA;
714         sc.cmd[10] = 0; /* sub channel */
715         sc.cmdlen = 12;
716         sc.databuf = (caddr_t)p_block;
717         sc.datalen = VCD_SECTOR_SIZE * i_nb;
718         sc.senselen = sizeof( sc.sense );
719         sc.flags = SCCMD_READ;
720         sc.timeout = 10000;
721
722         i_ret = ioctl( i_fd, SCIOCCOMMAND, &sc );
723         if( i_ret == -1 )
724         {
725             msg_Err( p_this, "SCIOCCOMMAND failed" );
726             if( i_type == VCD_TYPE ) free( p_block );
727             return -1;
728         }
729         if( sc.retsts || sc.error )
730         {
731             msg_Err( p_this, "SCSI command failed: status %d error %d\n",
732                              sc.retsts, sc.error );
733             if( i_type == VCD_TYPE ) free( p_block );
734            return -1;
735         }
736
737 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
738         int i_size = VCD_SECTOR_SIZE;
739
740         if( ioctl( p_vcddev->i_device_handle, CDRIOCSETBLOCKSIZE, &i_size )
741             == -1 )
742         {
743             msg_Err( p_this, "Could not set block size" );
744             if( i_type == VCD_TYPE ) free( p_block );
745             return( -1 );
746         }
747
748         if( lseek( p_vcddev->i_device_handle,
749                    i_sector * VCD_SECTOR_SIZE, SEEK_SET ) == -1 )
750         {
751             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
752             if( i_type == VCD_TYPE ) free( p_block );
753             return( -1 );
754         }
755
756         if( read( p_vcddev->i_device_handle,
757                   p_block, VCD_SECTOR_SIZE * i_nb ) == -1 )
758         {
759             msg_Err( p_this, "Could not read sector %d", i_sector );
760             if( i_type == VCD_TYPE ) free( p_block );
761             return( -1 );
762         }
763
764 #else
765         for( i = 0; i < i_nb; i++ )
766         {
767             int i_dummy = i_sector + i + 2 * CD_FRAMES;
768
769 #define p_msf ((struct cdrom_msf0 *)(p_block + i * VCD_SECTOR_SIZE))
770             p_msf->minute =   i_dummy / (CD_FRAMES * CD_SECS);
771             p_msf->second = ( i_dummy % (CD_FRAMES * CD_SECS) ) / CD_FRAMES;
772             p_msf->frame =  ( i_dummy % (CD_FRAMES * CD_SECS) ) % CD_FRAMES;
773 #undef p_msf
774
775             if( ioctl( p_vcddev->i_device_handle, CDROMREADRAW,
776                        p_block + i * VCD_SECTOR_SIZE ) == -1 )
777             {
778                 msg_Err( p_this, "could not read block %i from disc",
779                          i_sector );
780
781                 if( i == 0 )
782                 {
783                     if( i_type == VCD_TYPE ) free( p_block );
784                     return( -1 );
785                 }
786                 else break;
787             }
788         }
789 #endif
790     }
791
792     /* For VCDs, we don't want to keep the header and footer of the
793      * sectors read */
794     if( i_type == VCD_TYPE )
795     {
796         for( i = 0; i < i_nb; i++ )
797         {
798             memcpy( p_buffer + i * VCD_DATA_SIZE,
799                     p_block + i * VCD_SECTOR_SIZE + VCD_DATA_START,
800                     VCD_DATA_SIZE );
801         }
802         free( p_block );
803     }
804
805     return( 0 );
806 }
807
808 /****************************************************************************
809  * Private functions
810  ****************************************************************************/
811
812 /****************************************************************************
813  * OpenVCDImage: try to open a vcd image from a .cue file
814  ****************************************************************************/
815 static int OpenVCDImage( vlc_object_t * p_this, const char *psz_dev,
816                          vcddev_t *p_vcddev )
817 {
818     int i_ret = -1;
819     char *p_pos;
820     char *psz_vcdfile = NULL;
821     char *psz_cuefile = NULL;
822     FILE *cuefile     = NULL;
823     char line[1024];
824
825     /* Check if we are dealing with a .cue file */
826     p_pos = strrchr( psz_dev, '.' );
827     if( p_pos && !strcmp( p_pos, ".cue" ) )
828     {
829         /* psz_dev must be the cue file. Let's assume there's a .bin
830          * file with the same filename */
831         if( p_pos )
832         {
833             psz_vcdfile = malloc( p_pos - psz_dev + 5 /* ".bin" */ );
834             strncpy( psz_vcdfile, psz_dev, p_pos - psz_dev );
835             strcpy( psz_vcdfile + (p_pos - psz_dev), ".bin");
836         }
837         else
838         {
839             psz_vcdfile = malloc( strlen(psz_dev) + 5 /* ".bin" */ );
840             sprintf( psz_vcdfile, "%s.bin", psz_dev );
841         }
842         psz_cuefile = strdup( psz_dev );
843     }
844     else
845     {
846         /* psz_dev must be the actual vcd file. Let's assume there's a .cue
847          * file with the same filename */
848         if( p_pos )
849         {
850             psz_cuefile = malloc( p_pos - psz_dev + 5 /* ".cue" */ );
851             strncpy( psz_cuefile, psz_dev, p_pos - psz_dev );
852             strcpy( psz_cuefile + (p_pos - psz_dev), ".cue");
853         }
854         else
855         {
856             psz_cuefile = malloc( strlen(psz_dev) + 5 /* ".cue" */ );
857             sprintf( psz_cuefile, "%s.cue", psz_dev );
858         }
859         /* If we need to look up the .cue file, then we don't have to look for the vcd */
860         psz_vcdfile = strdup( psz_dev );
861     }
862
863     /* Open the cue file and try to parse it */
864     msg_Dbg( p_this,"trying .cue file: %s", psz_cuefile );
865     cuefile = utf8_fopen( psz_cuefile, "rt" );
866     if( cuefile == NULL )
867     {
868         i_ret = -1;
869         msg_Dbg( p_this, "could not find .cue file" );
870         goto error;
871     }
872
873     msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
874     p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
875                                     O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
876  
877     if( p_vcddev->i_vcdimage_handle == -1 &&
878         fscanf( cuefile, "FILE %c", line ) &&
879         fgets( line, 1024, cuefile ) )
880     {
881         /* We have a cue file, but no valid vcd file yet */
882         free( psz_vcdfile );
883         p_pos = strchr( line, '"' );
884         if( p_pos )
885         {
886             *p_pos = 0;
887
888             /* Take care of path standardization */
889             if( *line != '/' && ((p_pos = strrchr( psz_cuefile, '/' ))
890                 || (p_pos = strrchr( psz_cuefile, '\\' ) )) )
891             {
892                 psz_vcdfile = malloc( strlen(line) +
893                                       (p_pos - psz_cuefile + 1) + 1 );
894                 strncpy( psz_vcdfile, psz_cuefile, (p_pos - psz_cuefile + 1) );
895                 strcpy( psz_vcdfile + (p_pos - psz_cuefile + 1), line );
896             }
897             else psz_vcdfile = strdup( line );
898         }
899         msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
900         p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
901                                         O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
902     }
903
904     if( p_vcddev->i_vcdimage_handle == -1)
905     {
906         i_ret = -1;
907         goto error;
908     }
909     else i_ret = 0;
910
911     /* Try to parse the i_tracks and p_sectors info so we can just forget
912      * about the cuefile */
913     if( i_ret == 0 )
914     {
915         int p_sectors[100];
916         int i_tracks = 0;
917         int i_num;
918         char psz_dummy[10];
919
920         while( fgets( line, 1024, cuefile ) )
921         {
922             /* look for a TRACK line */
923             if( !sscanf( line, "%9s", psz_dummy ) ||
924                 strcmp(psz_dummy, "TRACK") )
925                 continue;
926
927             /* look for an INDEX line */
928             while( fgets( line, 1024, cuefile ) )
929             {
930                 int i_min, i_sec, i_frame;
931
932                 if( (sscanf( line, "%9s %2u %2u:%2u:%2u", psz_dummy, &i_num,
933                             &i_min, &i_sec, &i_frame ) != 5) || (i_num != 1) )
934                     continue;
935
936                 i_tracks++;
937                 p_sectors[i_tracks - 1] = MSF_TO_LBA(i_min, i_sec, i_frame);
938                 msg_Dbg( p_this, "vcd track %i begins at sector:%i",
939                          i_tracks - 1, p_sectors[i_tracks - 1] );
940                 break;
941             }
942         }
943
944         /* fill in the last entry */
945         p_sectors[i_tracks] = lseek(p_vcddev->i_vcdimage_handle, 0, SEEK_END)
946                                 / VCD_SECTOR_SIZE;
947         msg_Dbg( p_this, "vcd track %i, begins at sector:%i",
948                  i_tracks, p_sectors[i_tracks] );
949         p_vcddev->i_tracks = i_tracks;
950         p_vcddev->p_sectors = malloc( (i_tracks + 1) * sizeof(int) );
951         memcpy( p_vcddev->p_sectors, p_sectors, (i_tracks + 1) * sizeof(int) );
952
953     }
954
955 error:
956     if( cuefile ) fclose( cuefile );
957     free( psz_cuefile );
958     free( psz_vcdfile );
959
960     return i_ret;
961 }
962
963 /****************************************************************************
964  * CloseVCDImage: closes a vcd image opened by OpenVCDImage
965  ****************************************************************************/
966 static void CloseVCDImage( vlc_object_t * p_this, vcddev_t *p_vcddev )
967 {
968     if( p_vcddev->i_vcdimage_handle != -1 )
969         close( p_vcddev->i_vcdimage_handle );
970     else
971         return;
972
973     free( p_vcddev->p_sectors );
974 }
975
976 #if defined( __APPLE__ )
977 /****************************************************************************
978  * darwin_getTOC: get the TOC
979  ****************************************************************************/
980 static CDTOC *darwin_getTOC( vlc_object_t * p_this, const vcddev_t *p_vcddev )
981 {
982     mach_port_t port;
983     char *psz_devname;
984     kern_return_t ret;
985     CDTOC *pTOC = NULL;
986     io_iterator_t iterator;
987     io_registry_entry_t service;
988     CFMutableDictionaryRef properties;
989     CFDataRef data;
990
991     /* get the device name */
992     if( ( psz_devname = strrchr( p_vcddev->psz_dev, '/') ) != NULL )
993         ++psz_devname;
994     else
995         psz_devname = p_vcddev->psz_dev;
996
997     /* unraw the device name */
998     if( *psz_devname == 'r' )
999         ++psz_devname;
1000
1001     /* get port for IOKit communication */
1002     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
1003     {
1004         msg_Err( p_this, "IOMasterPort: 0x%08x", ret );
1005         return( NULL );
1006     }
1007
1008     /* get service iterator for the device */
1009     if( ( ret = IOServiceGetMatchingServices(
1010                     port, IOBSDNameMatching( port, 0, psz_devname ),
1011                     &iterator ) ) != KERN_SUCCESS )
1012     {
1013         msg_Err( p_this, "IOServiceGetMatchingServices: 0x%08x", ret );
1014         return( NULL );
1015     }
1016
1017     /* first service */
1018     service = IOIteratorNext( iterator );
1019     IOObjectRelease( iterator );
1020
1021     /* search for kIOCDMediaClass */
1022     while( service && !IOObjectConformsTo( service, kIOCDMediaClass ) )
1023     {
1024         if( ( ret = IORegistryEntryGetParentIterator( service,
1025                         kIOServicePlane, &iterator ) ) != KERN_SUCCESS )
1026         {
1027             msg_Err( p_this, "IORegistryEntryGetParentIterator: 0x%08x", ret );
1028             IOObjectRelease( service );
1029             return( NULL );
1030         }
1031
1032         IOObjectRelease( service );
1033         service = IOIteratorNext( iterator );
1034         IOObjectRelease( iterator );
1035     }
1036
1037     if( service == NULL )
1038     {
1039         msg_Err( p_this, "search for kIOCDMediaClass came up empty" );
1040         return( NULL );
1041     }
1042
1043     /* create a CF dictionary containing the TOC */
1044     if( ( ret = IORegistryEntryCreateCFProperties( service, &properties,
1045                     kCFAllocatorDefault, kNilOptions ) ) != KERN_SUCCESS )
1046     {
1047         msg_Err( p_this, "IORegistryEntryCreateCFProperties: 0x%08x", ret );
1048         IOObjectRelease( service );
1049         return( NULL );
1050     }
1051
1052     /* get the TOC from the dictionary */
1053     if( ( data = (CFDataRef) CFDictionaryGetValue( properties,
1054                                     CFSTR(kIOCDMediaTOCKey) ) ) != NULL )
1055     {
1056         CFRange range;
1057         CFIndex buf_len;
1058
1059         buf_len = CFDataGetLength( data ) + 1;
1060         range = CFRangeMake( 0, buf_len );
1061
1062         if( ( pTOC = (CDTOC *)malloc( buf_len ) ) != NULL )
1063         {
1064             CFDataGetBytes( data, range, (u_char *)pTOC );
1065         }
1066     }
1067     else
1068     {
1069         msg_Err( p_this, "CFDictionaryGetValue failed" );
1070     }
1071
1072     CFRelease( properties );
1073     IOObjectRelease( service );
1074
1075     return( pTOC );
1076 }
1077
1078 /****************************************************************************
1079  * darwin_getNumberOfTracks: get number of tracks in TOC
1080  ****************************************************************************/
1081 static int darwin_getNumberOfTracks( CDTOC *pTOC, int i_descriptors )
1082 {
1083     u_char track;
1084     int i, i_tracks = 0;
1085     CDTOCDescriptor *pTrackDescriptors = NULL;
1086
1087     pTrackDescriptors = (CDTOCDescriptor *)pTOC->descriptors;
1088
1089     for( i = i_descriptors; i > 0; i-- )
1090     {
1091         track = pTrackDescriptors[i].point;
1092
1093         if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
1094             continue;
1095
1096         i_tracks++;
1097     }
1098
1099     return( i_tracks );
1100 }
1101 #endif /* __APPLE__ */
1102
1103 #if defined( WIN32 )
1104 /*****************************************************************************
1105  * win32_vcd_open: open vcd drive
1106  *****************************************************************************
1107  * Load and use aspi if it is available, otherwise use IOCTLs on WinNT/2K/XP.
1108  *****************************************************************************/
1109 static int win32_vcd_open( vlc_object_t * p_this, const char *psz_dev,
1110                            vcddev_t *p_vcddev )
1111 {
1112     /* Initializations */
1113     p_vcddev->h_device_handle = NULL;
1114     p_vcddev->i_sid = 0;
1115     p_vcddev->hASPI = 0;
1116     p_vcddev->lpSendCommand = 0;
1117
1118     if( WIN_NT )
1119     {
1120         char psz_win32_drive[7];
1121
1122         msg_Dbg( p_this, "using winNT/2K/XP ioctl layer" );
1123
1124         sprintf( psz_win32_drive, "\\\\.\\%c:", psz_dev[0] );
1125
1126         p_vcddev->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
1127                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
1128                                             NULL, OPEN_EXISTING,
1129                                             FILE_FLAG_NO_BUFFERING |
1130                                             FILE_FLAG_RANDOM_ACCESS, NULL );
1131         return (p_vcddev->h_device_handle == NULL) ? -1 : 0;
1132     }
1133     else
1134     {
1135         HMODULE hASPI = NULL;
1136         long (*lpGetSupport)( void ) = NULL;
1137         long (*lpSendCommand)( void* ) = NULL;
1138         DWORD dwSupportInfo;
1139         int i, j, i_hostadapters;
1140         char c_drive = psz_dev[0];
1141
1142         hASPI = LoadLibrary( "wnaspi32.dll" );
1143         if( hASPI != NULL )
1144         {
1145             lpGetSupport = (void *)GetProcAddress( hASPI, "GetASPI32SupportInfo" );
1146             lpSendCommand = (void *)GetProcAddress( hASPI, "SendASPI32Command" );
1147         }
1148
1149         if( hASPI == NULL || lpGetSupport == NULL || lpSendCommand == NULL )
1150         {
1151             msg_Dbg( p_this,
1152                      "unable to load aspi or get aspi function pointers" );
1153             if( hASPI ) FreeLibrary( hASPI );
1154             return -1;
1155         }
1156
1157         /* ASPI support seems to be there */
1158
1159         dwSupportInfo = lpGetSupport();
1160
1161         if( HIBYTE( LOWORD ( dwSupportInfo ) ) == SS_NO_ADAPTERS )
1162         {
1163             msg_Dbg( p_this, "no host adapters found (aspi)" );
1164             FreeLibrary( hASPI );
1165             return -1;
1166         }
1167
1168         if( HIBYTE( LOWORD ( dwSupportInfo ) ) != SS_COMP )
1169         {
1170             msg_Dbg( p_this, "unable to initalize aspi layer" );
1171             FreeLibrary( hASPI );
1172             return -1;
1173         }
1174
1175         i_hostadapters = LOBYTE( LOWORD( dwSupportInfo ) );
1176         if( i_hostadapters == 0 )
1177         {
1178             FreeLibrary( hASPI );
1179             return -1;
1180         }
1181
1182         c_drive = c_drive > 'Z' ? c_drive - 'a' : c_drive - 'A';
1183
1184         for( i = 0; i < i_hostadapters; i++ )
1185         {
1186           for( j = 0; j < 15; j++ )
1187           {
1188               struct SRB_GetDiskInfo srbDiskInfo;
1189
1190               srbDiskInfo.SRB_Cmd         = SC_GET_DISK_INFO;
1191               srbDiskInfo.SRB_HaId        = i;
1192               srbDiskInfo.SRB_Flags       = 0;
1193               srbDiskInfo.SRB_Hdr_Rsvd    = 0;
1194               srbDiskInfo.SRB_Target      = j;
1195               srbDiskInfo.SRB_Lun         = 0;
1196
1197               lpSendCommand( (void*) &srbDiskInfo );
1198
1199               if( (srbDiskInfo.SRB_Status == SS_COMP) &&
1200                   (srbDiskInfo.SRB_Int13HDriveInfo == c_drive) )
1201               {
1202                   /* Make sure this is a cdrom device */
1203                   struct SRB_GDEVBlock   srbGDEVBlock;
1204
1205                   memset( &srbGDEVBlock, 0, sizeof(struct SRB_GDEVBlock) );
1206                   srbGDEVBlock.SRB_Cmd    = SC_GET_DEV_TYPE;
1207                   srbGDEVBlock.SRB_HaId   = i;
1208                   srbGDEVBlock.SRB_Target = j;
1209
1210                   lpSendCommand( (void*) &srbGDEVBlock );
1211
1212                   if( ( srbGDEVBlock.SRB_Status == SS_COMP ) &&
1213                       ( srbGDEVBlock.SRB_DeviceType == DTYPE_CDROM ) )
1214                   {
1215                       p_vcddev->i_sid = MAKEWORD( i, j );
1216                       p_vcddev->hASPI = (long)hASPI;
1217                       p_vcddev->lpSendCommand = lpSendCommand;
1218                       msg_Dbg( p_this, "using aspi layer" );
1219
1220                       return 0;
1221                   }
1222                   else
1223                   {
1224                       FreeLibrary( hASPI );
1225                       msg_Dbg( p_this, "%c: is not a cdrom drive",
1226                                psz_dev[0] );
1227                       return -1;
1228                   }
1229               }
1230           }
1231         }
1232
1233         FreeLibrary( hASPI );
1234         msg_Dbg( p_this, "unable to get haid and target (aspi)" );
1235
1236     }
1237
1238     return -1;
1239 }
1240
1241 #endif /* WIN32 */