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