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