]> git.sesse.net Git - vlc/blob - modules/access/vcd/cdrom.c
vcd module: fix .cue loading. was failing on .cue's for MP3s
[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     bool b_found      = false;
825
826     /* Check if we are dealing with a .cue file */
827     p_pos = strrchr( psz_dev, '.' );
828     if( p_pos && !strcmp( p_pos, ".cue" ) )
829     {
830         /* psz_dev must be the cue file. Let's assume there's a .bin
831          * file with the same filename */
832         psz_vcdfile = malloc( p_pos - psz_dev + 5 /* ".bin" */ );
833         strncpy( psz_vcdfile, psz_dev, p_pos - psz_dev );
834         strcpy( psz_vcdfile + (p_pos - psz_dev), ".bin");
835         psz_cuefile = strdup( psz_dev );
836     }
837     else
838     {
839         /* psz_dev must be the actual vcd file. Let's assume there's a .cue
840          * file with the same filename */
841         if( p_pos )
842         {
843             psz_cuefile = malloc( p_pos - psz_dev + 5 /* ".cue" */ );
844             strncpy( psz_cuefile, psz_dev, p_pos - psz_dev );
845             strcpy( psz_cuefile + (p_pos - psz_dev), ".cue");
846         }
847         else
848         {
849             psz_cuefile = malloc( strlen(psz_dev) + 5 /* ".cue" */ );
850             sprintf( psz_cuefile, "%s.cue", psz_dev );
851         }
852         /* If we need to look up the .cue file, then we don't have to look for the vcd */
853         psz_vcdfile = strdup( psz_dev );
854     }
855
856     /* Open the cue file and try to parse it */
857     msg_Dbg( p_this,"trying .cue file: %s", psz_cuefile );
858     cuefile = utf8_fopen( psz_cuefile, "rt" );
859     if( cuefile == NULL )
860     {
861         i_ret = -1;
862         msg_Dbg( p_this, "could not find .cue file" );
863         goto error;
864     }
865
866     msg_Dbg( p_this,"guessing vcd image file: %s", psz_vcdfile );
867     p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
868                                     O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
869  
870     while( fgets( line, 1024, cuefile ) && !b_found )
871     {
872         /* We have a cue file, but no valid vcd file yet */
873         char filename[1024];
874         char type[16];
875         int i_temp = sscanf( line, "FILE \"%1023[^\"]\" %15s", filename, type );
876         *p_pos = 0;
877         switch( i_temp )
878         {
879             case 2:
880                 msg_Dbg( p_this, "the cue file says the data file is %s", type );
881                 if( strcasecmp( type, "BINARY" ) )
882                     goto error; /* Error if not binary, otherwise treat as case 1 */
883             case 1:
884                 if( p_vcddev->i_vcdimage_handle == -1 )
885                 {
886                     msg_Dbg( p_this, "we could not find the data file, but we found a new path" );
887                     free( psz_vcdfile);
888                     if( *filename != '/' && ((p_pos = strrchr( psz_cuefile, '/' ))
889                         || (p_pos = strrchr( psz_cuefile, '\\' ) )) )
890                     {
891                         psz_vcdfile = malloc( strlen(filename) +
892                                       (p_pos - psz_cuefile + 1) + 1 );
893                         strncpy( psz_vcdfile, psz_cuefile, (p_pos - psz_cuefile + 1) );
894                         strcpy( psz_vcdfile + (p_pos - psz_cuefile + 1), filename );
895                     } else psz_vcdfile = strdup( filename );
896                     msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
897                     p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
898                                         O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
899                 }
900                 b_found = true;
901             default:
902                 break;
903         }
904     }
905
906     if( p_vcddev->i_vcdimage_handle == -1)
907     {
908         i_ret = -1;
909         goto error;
910     }
911     else i_ret = 0;
912
913     /* Try to parse the i_tracks and p_sectors info so we can just forget
914      * about the cuefile */
915     if( i_ret == 0 )
916     {
917         int p_sectors[100];
918         int i_tracks = 0;
919         int i_num;
920         char psz_dummy[10];
921
922         while( fgets( line, 1024, cuefile ) )
923         {
924             /* look for a TRACK line */
925             if( !sscanf( line, "%9s", psz_dummy ) ||
926                 strcmp(psz_dummy, "TRACK") )
927                 continue;
928
929             /* look for an INDEX line */
930             while( fgets( line, 1024, cuefile ) )
931             {
932                 int i_min, i_sec, i_frame;
933
934                 if( (sscanf( line, "%9s %2u %2u:%2u:%2u", psz_dummy, &i_num,
935                             &i_min, &i_sec, &i_frame ) != 5) || (i_num != 1) )
936                     continue;
937
938                 i_tracks++;
939                 p_sectors[i_tracks - 1] = MSF_TO_LBA(i_min, i_sec, i_frame);
940                 msg_Dbg( p_this, "vcd track %i begins at sector:%i",
941                          i_tracks - 1, p_sectors[i_tracks - 1] );
942                 break;
943             }
944         }
945
946         /* fill in the last entry */
947         p_sectors[i_tracks] = lseek(p_vcddev->i_vcdimage_handle, 0, SEEK_END)
948                                 / VCD_SECTOR_SIZE;
949         msg_Dbg( p_this, "vcd track %i, begins at sector:%i",
950                  i_tracks, p_sectors[i_tracks] );
951         p_vcddev->i_tracks = i_tracks;
952         p_vcddev->p_sectors = malloc( (i_tracks + 1) * sizeof(int) );
953         memcpy( p_vcddev->p_sectors, p_sectors, (i_tracks + 1) * sizeof(int) );
954
955     }
956
957 error:
958     if( cuefile ) fclose( cuefile );
959     free( psz_cuefile );
960     free( psz_vcdfile );
961
962     return i_ret;
963 }
964
965 /****************************************************************************
966  * CloseVCDImage: closes a vcd image opened by OpenVCDImage
967  ****************************************************************************/
968 static void CloseVCDImage( vlc_object_t * p_this, vcddev_t *p_vcddev )
969 {
970     if( p_vcddev->i_vcdimage_handle != -1 )
971         close( p_vcddev->i_vcdimage_handle );
972     else
973         return;
974
975     free( p_vcddev->p_sectors );
976 }
977
978 #if defined( __APPLE__ )
979 /****************************************************************************
980  * darwin_getTOC: get the TOC
981  ****************************************************************************/
982 static CDTOC *darwin_getTOC( vlc_object_t * p_this, const vcddev_t *p_vcddev )
983 {
984     mach_port_t port;
985     char *psz_devname;
986     kern_return_t ret;
987     CDTOC *pTOC = NULL;
988     io_iterator_t iterator;
989     io_registry_entry_t service;
990     CFMutableDictionaryRef properties;
991     CFDataRef data;
992
993     /* get the device name */
994     if( ( psz_devname = strrchr( p_vcddev->psz_dev, '/') ) != NULL )
995         ++psz_devname;
996     else
997         psz_devname = p_vcddev->psz_dev;
998
999     /* unraw the device name */
1000     if( *psz_devname == 'r' )
1001         ++psz_devname;
1002
1003     /* get port for IOKit communication */
1004     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
1005     {
1006         msg_Err( p_this, "IOMasterPort: 0x%08x", ret );
1007         return( NULL );
1008     }
1009
1010     /* get service iterator for the device */
1011     if( ( ret = IOServiceGetMatchingServices(
1012                     port, IOBSDNameMatching( port, 0, psz_devname ),
1013                     &iterator ) ) != KERN_SUCCESS )
1014     {
1015         msg_Err( p_this, "IOServiceGetMatchingServices: 0x%08x", ret );
1016         return( NULL );
1017     }
1018
1019     /* first service */
1020     service = IOIteratorNext( iterator );
1021     IOObjectRelease( iterator );
1022
1023     /* search for kIOCDMediaClass */
1024     while( service && !IOObjectConformsTo( service, kIOCDMediaClass ) )
1025     {
1026         if( ( ret = IORegistryEntryGetParentIterator( service,
1027                         kIOServicePlane, &iterator ) ) != KERN_SUCCESS )
1028         {
1029             msg_Err( p_this, "IORegistryEntryGetParentIterator: 0x%08x", ret );
1030             IOObjectRelease( service );
1031             return( NULL );
1032         }
1033
1034         IOObjectRelease( service );
1035         service = IOIteratorNext( iterator );
1036         IOObjectRelease( iterator );
1037     }
1038
1039     if( service == NULL )
1040     {
1041         msg_Err( p_this, "search for kIOCDMediaClass came up empty" );
1042         return( NULL );
1043     }
1044
1045     /* create a CF dictionary containing the TOC */
1046     if( ( ret = IORegistryEntryCreateCFProperties( service, &properties,
1047                     kCFAllocatorDefault, kNilOptions ) ) != KERN_SUCCESS )
1048     {
1049         msg_Err( p_this, "IORegistryEntryCreateCFProperties: 0x%08x", ret );
1050         IOObjectRelease( service );
1051         return( NULL );
1052     }
1053
1054     /* get the TOC from the dictionary */
1055     if( ( data = (CFDataRef) CFDictionaryGetValue( properties,
1056                                     CFSTR(kIOCDMediaTOCKey) ) ) != NULL )
1057     {
1058         CFRange range;
1059         CFIndex buf_len;
1060
1061         buf_len = CFDataGetLength( data ) + 1;
1062         range = CFRangeMake( 0, buf_len );
1063
1064         if( ( pTOC = (CDTOC *)malloc( buf_len ) ) != NULL )
1065         {
1066             CFDataGetBytes( data, range, (u_char *)pTOC );
1067         }
1068     }
1069     else
1070     {
1071         msg_Err( p_this, "CFDictionaryGetValue failed" );
1072     }
1073
1074     CFRelease( properties );
1075     IOObjectRelease( service );
1076
1077     return( pTOC );
1078 }
1079
1080 /****************************************************************************
1081  * darwin_getNumberOfTracks: get number of tracks in TOC
1082  ****************************************************************************/
1083 static int darwin_getNumberOfTracks( CDTOC *pTOC, int i_descriptors )
1084 {
1085     u_char track;
1086     int i, i_tracks = 0;
1087     CDTOCDescriptor *pTrackDescriptors = NULL;
1088
1089     pTrackDescriptors = (CDTOCDescriptor *)pTOC->descriptors;
1090
1091     for( i = i_descriptors; i > 0; i-- )
1092     {
1093         track = pTrackDescriptors[i].point;
1094
1095         if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
1096             continue;
1097
1098         i_tracks++;
1099     }
1100
1101     return( i_tracks );
1102 }
1103 #endif /* __APPLE__ */
1104
1105 #if defined( WIN32 )
1106 /*****************************************************************************
1107  * win32_vcd_open: open vcd drive
1108  *****************************************************************************
1109  * Load and use aspi if it is available, otherwise use IOCTLs on WinNT/2K/XP.
1110  *****************************************************************************/
1111 static int win32_vcd_open( vlc_object_t * p_this, const char *psz_dev,
1112                            vcddev_t *p_vcddev )
1113 {
1114     /* Initializations */
1115     p_vcddev->h_device_handle = NULL;
1116     p_vcddev->i_sid = 0;
1117     p_vcddev->hASPI = 0;
1118     p_vcddev->lpSendCommand = 0;
1119
1120     if( WIN_NT )
1121     {
1122         char psz_win32_drive[7];
1123
1124         msg_Dbg( p_this, "using winNT/2K/XP ioctl layer" );
1125
1126         sprintf( psz_win32_drive, "\\\\.\\%c:", psz_dev[0] );
1127
1128         p_vcddev->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
1129                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
1130                                             NULL, OPEN_EXISTING,
1131                                             FILE_FLAG_NO_BUFFERING |
1132                                             FILE_FLAG_RANDOM_ACCESS, NULL );
1133         return (p_vcddev->h_device_handle == NULL) ? -1 : 0;
1134     }
1135     else
1136     {
1137         HMODULE hASPI = NULL;
1138         long (*lpGetSupport)( void ) = NULL;
1139         long (*lpSendCommand)( void* ) = NULL;
1140         DWORD dwSupportInfo;
1141         int i, j, i_hostadapters;
1142         char c_drive = psz_dev[0];
1143
1144         hASPI = LoadLibrary( "wnaspi32.dll" );
1145         if( hASPI != NULL )
1146         {
1147             lpGetSupport = (void *)GetProcAddress( hASPI, "GetASPI32SupportInfo" );
1148             lpSendCommand = (void *)GetProcAddress( hASPI, "SendASPI32Command" );
1149         }
1150
1151         if( hASPI == NULL || lpGetSupport == NULL || lpSendCommand == NULL )
1152         {
1153             msg_Dbg( p_this,
1154                      "unable to load aspi or get aspi function pointers" );
1155             if( hASPI ) FreeLibrary( hASPI );
1156             return -1;
1157         }
1158
1159         /* ASPI support seems to be there */
1160
1161         dwSupportInfo = lpGetSupport();
1162
1163         if( HIBYTE( LOWORD ( dwSupportInfo ) ) == SS_NO_ADAPTERS )
1164         {
1165             msg_Dbg( p_this, "no host adapters found (aspi)" );
1166             FreeLibrary( hASPI );
1167             return -1;
1168         }
1169
1170         if( HIBYTE( LOWORD ( dwSupportInfo ) ) != SS_COMP )
1171         {
1172             msg_Dbg( p_this, "unable to initalize aspi layer" );
1173             FreeLibrary( hASPI );
1174             return -1;
1175         }
1176
1177         i_hostadapters = LOBYTE( LOWORD( dwSupportInfo ) );
1178         if( i_hostadapters == 0 )
1179         {
1180             FreeLibrary( hASPI );
1181             return -1;
1182         }
1183
1184         c_drive = c_drive > 'Z' ? c_drive - 'a' : c_drive - 'A';
1185
1186         for( i = 0; i < i_hostadapters; i++ )
1187         {
1188           for( j = 0; j < 15; j++ )
1189           {
1190               struct SRB_GetDiskInfo srbDiskInfo;
1191
1192               srbDiskInfo.SRB_Cmd         = SC_GET_DISK_INFO;
1193               srbDiskInfo.SRB_HaId        = i;
1194               srbDiskInfo.SRB_Flags       = 0;
1195               srbDiskInfo.SRB_Hdr_Rsvd    = 0;
1196               srbDiskInfo.SRB_Target      = j;
1197               srbDiskInfo.SRB_Lun         = 0;
1198
1199               lpSendCommand( (void*) &srbDiskInfo );
1200
1201               if( (srbDiskInfo.SRB_Status == SS_COMP) &&
1202                   (srbDiskInfo.SRB_Int13HDriveInfo == c_drive) )
1203               {
1204                   /* Make sure this is a cdrom device */
1205                   struct SRB_GDEVBlock   srbGDEVBlock;
1206
1207                   memset( &srbGDEVBlock, 0, sizeof(struct SRB_GDEVBlock) );
1208                   srbGDEVBlock.SRB_Cmd    = SC_GET_DEV_TYPE;
1209                   srbGDEVBlock.SRB_HaId   = i;
1210                   srbGDEVBlock.SRB_Target = j;
1211
1212                   lpSendCommand( (void*) &srbGDEVBlock );
1213
1214                   if( ( srbGDEVBlock.SRB_Status == SS_COMP ) &&
1215                       ( srbGDEVBlock.SRB_DeviceType == DTYPE_CDROM ) )
1216                   {
1217                       p_vcddev->i_sid = MAKEWORD( i, j );
1218                       p_vcddev->hASPI = (long)hASPI;
1219                       p_vcddev->lpSendCommand = lpSendCommand;
1220                       msg_Dbg( p_this, "using aspi layer" );
1221
1222                       return 0;
1223                   }
1224                   else
1225                   {
1226                       FreeLibrary( hASPI );
1227                       msg_Dbg( p_this, "%c: is not a cdrom drive",
1228                                psz_dev[0] );
1229                       return -1;
1230                   }
1231               }
1232           }
1233         }
1234
1235         FreeLibrary( hASPI );
1236         msg_Dbg( p_this, "unable to get haid and target (aspi)" );
1237
1238     }
1239
1240     return -1;
1241 }
1242
1243 #endif /* WIN32 */