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