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