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