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