]> git.sesse.net Git - vlc/blob - modules/access/vcd/cdrom.c
Removed invalid assignation while loading cue files.
[vlc] / modules / access / vcd / cdrom.c
1 /****************************************************************************
2  * cdrom.c: cdrom tools
3  *****************************************************************************
4  * Copyright (C) 1998-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Johan Bilien <jobi@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_access.h>
35 #include <vlc_charset.h>
36 #include <vlc_fs.h>
37 #include <limits.h>
38
39 #ifdef HAVE_UNISTD_H
40 #   include <unistd.h>
41 #endif
42
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_STAT_H
45 #   include <sys/stat.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #   include <fcntl.h>
49 #endif
50 #ifdef HAVE_ARPA_INET_H
51 #   include <arpa/inet.h>
52 #endif
53
54 #if defined( SYS_BSDI )
55 #   include <dvd.h>
56 #elif defined ( __APPLE__ )
57 #   include <CoreFoundation/CFBase.h>
58 #   include <IOKit/IOKitLib.h>
59 #   include <IOKit/storage/IOCDTypes.h>
60 #   include <IOKit/storage/IOCDMedia.h>
61 #   include <IOKit/storage/IOCDMediaBSDClient.h>
62 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
63 #   include <inttypes.h>
64 #   include <sys/cdio.h>
65 #   include <sys/scsiio.h>
66 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
67 #   include <sys/cdio.h>
68 #   include <sys/cdrio.h>
69 #elif defined( WIN32 )
70 #   include <windows.h>
71 #   include <winioctl.h>
72 #elif defined (__linux__)
73 #   include <sys/ioctl.h>
74 #   include <linux/cdrom.h>
75 #else
76 #   error FIXME
77 #endif
78
79 #include "cdrom_internals.h"
80 #include "cdrom.h"
81 #include <vlc_meta.h>
82
83 /*****************************************************************************
84  * ioctl_Open: Opens a VCD device or file and returns an opaque handle
85  *****************************************************************************/
86 vcddev_t *ioctl_Open( vlc_object_t *p_this, const char *psz_dev )
87 {
88     int i_ret;
89     int b_is_file;
90     vcddev_t *p_vcddev;
91 #ifndef WIN32
92     struct stat fileinfo;
93 #endif
94
95     if( !psz_dev ) return NULL;
96
97     /*
98      *  Initialize structure with default values
99      */
100     p_vcddev = malloc( sizeof(*p_vcddev) );
101     if( p_vcddev == NULL )
102         return NULL;
103     p_vcddev->i_vcdimage_handle = -1;
104     p_vcddev->psz_dev = NULL;
105     b_is_file = 1;
106
107     /*
108      *  Check if we are dealing with a device or a file (vcd image)
109      */
110 #ifdef WIN32
111     if( (strlen( psz_dev ) == 2 && psz_dev[1] == ':') )
112     {
113         b_is_file = 0;
114     }
115
116 #else
117     if( vlc_stat( psz_dev, &fileinfo ) < 0 )
118     {
119         free( p_vcddev );
120         return NULL;
121     }
122
123     /* Check if this is a block/char device */
124     if( S_ISBLK( fileinfo.st_mode ) || S_ISCHR( fileinfo.st_mode ) )
125         b_is_file = 0;
126 #endif
127
128     if( b_is_file )
129     {
130         i_ret = OpenVCDImage( p_this, psz_dev, p_vcddev );
131     }
132     else
133     {
134         /*
135          *  open the vcd device
136          */
137
138 #ifdef WIN32
139         i_ret = win32_vcd_open( p_this, psz_dev, p_vcddev );
140 #else
141         p_vcddev->i_device_handle = -1;
142         p_vcddev->i_device_handle = vlc_open( psz_dev, O_RDONLY | O_NONBLOCK );
143         i_ret = (p_vcddev->i_device_handle == -1) ? -1 : 0;
144 #endif
145     }
146
147     if( i_ret == 0 )
148     {
149         p_vcddev->psz_dev = (char *)strdup( psz_dev );
150     }
151     else
152     {
153         free( p_vcddev );
154         p_vcddev = NULL;
155     }
156
157     return p_vcddev;
158 }
159
160 /*****************************************************************************
161  * ioctl_Close: Closes an already opened VCD device or file.
162  *****************************************************************************/
163 void ioctl_Close( vlc_object_t * p_this, vcddev_t *p_vcddev )
164 {
165     free( p_vcddev->psz_dev );
166
167     if( p_vcddev->i_vcdimage_handle != -1 )
168     {
169         /*
170          *  vcd image mode
171          */
172
173         CloseVCDImage( p_this, p_vcddev );
174         return;
175     }
176
177     /*
178      *  vcd device mode
179      */
180
181 #ifdef WIN32
182     if( p_vcddev->h_device_handle )
183         CloseHandle( p_vcddev->h_device_handle );
184 #else
185     if( p_vcddev->i_device_handle != -1 )
186         close( p_vcddev->i_device_handle );
187 #endif
188     free( p_vcddev );
189 }
190
191 /*****************************************************************************
192  * ioctl_GetTracksMap: Read the Table of Content, fill in the pp_sectors map
193  *                     if pp_sectors is not null and return the number of
194  *                     tracks available.
195  *****************************************************************************/
196 int ioctl_GetTracksMap( vlc_object_t *p_this, const vcddev_t *p_vcddev,
197                         int **pp_sectors )
198 {
199     int i_tracks = 0;
200
201     if( p_vcddev->i_vcdimage_handle != -1 )
202     {
203         /*
204          *  vcd image mode
205          */
206
207         i_tracks = p_vcddev->i_tracks;
208
209         if( pp_sectors )
210         {
211             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
212             if( *pp_sectors == NULL )
213                 return 0;
214             memcpy( *pp_sectors, p_vcddev->p_sectors,
215                     (i_tracks + 1) * sizeof(**pp_sectors) );
216         }
217
218         return i_tracks;
219     }
220     else
221     {
222
223         /*
224          *  vcd device mode
225          */
226
227 #if defined( __APPLE__ )
228
229         CDTOC *pTOC;
230         int i_descriptors;
231
232         if( ( pTOC = darwin_getTOC( p_this, p_vcddev ) ) == NULL )
233         {
234             msg_Err( p_this, "failed to get the TOC" );
235             return 0;
236         }
237
238         i_descriptors = CDTOCGetDescriptorCount( pTOC );
239         i_tracks = darwin_getNumberOfTracks( pTOC, i_descriptors );
240
241         if( pp_sectors )
242         {
243             int i, i_leadout = -1;
244             CDTOCDescriptor *pTrackDescriptors;
245             u_char track;
246
247             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
248             if( *pp_sectors == NULL )
249             {
250                 darwin_freeTOC( pTOC );
251                 return 0;
252             }
253
254             pTrackDescriptors = pTOC->descriptors;
255
256             for( i_tracks = 0, i = 0; i < i_descriptors; i++ )
257             {
258                 track = pTrackDescriptors[i].point;
259
260                 if( track == 0xA2 )
261                     i_leadout = i;
262
263                 if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
264                     continue;
265
266                 (*pp_sectors)[i_tracks++] =
267                     CDConvertMSFToLBA( pTrackDescriptors[i].p );
268             }
269
270             if( i_leadout == -1 )
271             {
272                 msg_Err( p_this, "leadout not found" );
273                 free( *pp_sectors );
274                 darwin_freeTOC( pTOC );
275                 return 0;
276             }
277
278             /* set leadout sector */
279             (*pp_sectors)[i_tracks] =
280                 CDConvertMSFToLBA( pTrackDescriptors[i_leadout].p );
281         }
282
283         darwin_freeTOC( pTOC );
284
285 #elif defined( WIN32 )
286         DWORD dwBytesReturned;
287         CDROM_TOC cdrom_toc;
288
289         if( DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC,
290                              NULL, 0, &cdrom_toc, sizeof(CDROM_TOC),
291                              &dwBytesReturned, NULL ) == 0 )
292         {
293             msg_Err( p_this, "could not read TOCHDR" );
294             return 0;
295         }
296
297         i_tracks = cdrom_toc.LastTrack - cdrom_toc.FirstTrack + 1;
298
299         if( pp_sectors )
300         {
301             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
302             if( *pp_sectors == NULL )
303                 return 0;
304
305             for( int i = 0 ; i <= i_tracks ; i++ )
306             {
307                 (*pp_sectors)[ i ] = MSF_TO_LBA2(
308                                            cdrom_toc.TrackData[i].Address[1],
309                                            cdrom_toc.TrackData[i].Address[2],
310                                            cdrom_toc.TrackData[i].Address[3] );
311                 msg_Dbg( p_this, "p_sectors: %i, %i", i, (*pp_sectors)[i]);
312              }
313         }
314
315 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) \
316        || defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
317         struct ioc_toc_header tochdr;
318         struct ioc_read_toc_entry toc_entries;
319
320         if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCHEADER, &tochdr )
321             == -1 )
322         {
323             msg_Err( p_this, "could not read TOCHDR" );
324             return 0;
325         }
326
327         i_tracks = tochdr.ending_track - tochdr.starting_track + 1;
328
329         if( pp_sectors )
330         {
331              int i;
332
333              *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
334              if( *pp_sectors == NULL )
335                  return 0;
336
337              toc_entries.address_format = CD_LBA_FORMAT;
338              toc_entries.starting_track = 0;
339              toc_entries.data_len = ( i_tracks + 1 ) *
340                                         sizeof( struct cd_toc_entry );
341              toc_entries.data = (struct cd_toc_entry *)
342                                     malloc( toc_entries.data_len );
343              if( toc_entries.data == NULL )
344              {
345                  free( *pp_sectors );
346                  return 0;
347              }
348
349              /* Read the TOC */
350              if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCENTRYS,
351                         &toc_entries ) == -1 )
352              {
353                  msg_Err( p_this, "could not read the TOC" );
354                  free( *pp_sectors );
355                  free( toc_entries.data );
356                  return 0;
357              }
358
359              /* Fill the p_sectors structure with the track/sector matches */
360              for( i = 0 ; i <= i_tracks ; i++ )
361              {
362 #if defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
363                  /* FIXME: is this ok? */
364                  (*pp_sectors)[ i ] = toc_entries.data[i].addr.lba;
365 #else
366                  (*pp_sectors)[ i ] = ntohl( toc_entries.data[i].addr.lba );
367 #endif
368              }
369         }
370 #else
371         struct cdrom_tochdr   tochdr;
372         struct cdrom_tocentry tocent;
373
374         /* First we read the TOC header */
375         if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCHDR, &tochdr )
376             == -1 )
377         {
378             msg_Err( p_this, "could not read TOCHDR" );
379             return 0;
380         }
381
382         i_tracks = tochdr.cdth_trk1 - tochdr.cdth_trk0 + 1;
383
384         if( pp_sectors )
385         {
386             int i;
387
388             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
389             if( *pp_sectors == NULL )
390                 return 0;
391
392             /* Fill the p_sectors structure with the track/sector matches */
393             for( i = 0 ; i <= i_tracks ; i++ )
394             {
395                 tocent.cdte_format = CDROM_LBA;
396                 tocent.cdte_track =
397                     ( i == i_tracks ) ? CDROM_LEADOUT : tochdr.cdth_trk0 + i;
398
399                 if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCENTRY,
400                            &tocent ) == -1 )
401                 {
402                     msg_Err( p_this, "could not read TOCENTRY" );
403                     free( *pp_sectors );
404                     return 0;
405                 }
406
407                 (*pp_sectors)[ i ] = tocent.cdte_addr.lba;
408             }
409         }
410 #endif
411
412         return i_tracks;
413     }
414 }
415
416 /****************************************************************************
417  * ioctl_ReadSector: Read VCD or CDDA sectors
418  ****************************************************************************/
419 int ioctl_ReadSectors( vlc_object_t *p_this, const vcddev_t *p_vcddev,
420                        int i_sector, uint8_t *p_buffer, int i_nb, int i_type )
421 {
422     uint8_t *p_block;
423     int i;
424
425     if( i_type == VCD_TYPE )
426         p_block = malloc( VCD_SECTOR_SIZE * i_nb );
427     else
428         p_block = p_buffer;
429
430     if( p_vcddev->i_vcdimage_handle != -1 )
431     {
432         /*
433          *  vcd image mode
434          */
435         if( lseek( p_vcddev->i_vcdimage_handle, i_sector * VCD_SECTOR_SIZE,
436                    SEEK_SET ) == -1 )
437         {
438             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
439             if( i_type == VCD_TYPE ) free( p_block );
440             return -1;
441         }
442
443         if( read( p_vcddev->i_vcdimage_handle, p_block, VCD_SECTOR_SIZE * i_nb)
444             == -1 )
445         {
446             msg_Err( p_this, "Could not read sector %d", i_sector );
447             if( i_type == VCD_TYPE ) free( p_block );
448             return -1;
449         }
450
451     }
452     else
453     {
454
455         /*
456          *  vcd device mode
457          */
458
459 #if defined( __APPLE__ )
460         dk_cd_read_t cd_read;
461
462         memset( &cd_read, 0, sizeof(cd_read) );
463
464         cd_read.offset = i_sector * VCD_SECTOR_SIZE;
465         cd_read.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader |
466                              kCDSectorAreaSubHeader | kCDSectorAreaUser |
467                              kCDSectorAreaAuxiliary;
468         cd_read.sectorType = kCDSectorTypeUnknown;
469
470         cd_read.buffer = p_block;
471         cd_read.bufferLength = VCD_SECTOR_SIZE * i_nb;
472
473         if( ioctl( p_vcddev->i_device_handle, DKIOCCDREAD, &cd_read ) == -1 )
474         {
475             msg_Err( p_this, "could not read block %d", i_sector );
476             if( i_type == VCD_TYPE ) free( p_block );
477             return -1;
478         }
479
480 #elif defined( WIN32 )
481         DWORD dwBytesReturned;
482         RAW_READ_INFO cdrom_raw;
483
484         /* Initialize CDROM_RAW_READ structure */
485         cdrom_raw.DiskOffset.QuadPart = CD_SECTOR_SIZE * i_sector;
486         cdrom_raw.SectorCount = i_nb;
487         cdrom_raw.TrackMode =  i_type == VCD_TYPE ? XAForm2 : CDDA;
488
489         if( DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_RAW_READ,
490                              &cdrom_raw, sizeof(RAW_READ_INFO), p_block,
491                              VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
492                              NULL ) == 0 )
493         {
494             if( i_type == VCD_TYPE )
495             {
496                 /* Retry in YellowMode2 */
497                 cdrom_raw.TrackMode = YellowMode2;
498                 if( DeviceIoControl( p_vcddev->h_device_handle,
499                                      IOCTL_CDROM_RAW_READ, &cdrom_raw,
500                                      sizeof(RAW_READ_INFO), p_block,
501                                      VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
502                                      NULL ) == 0 )
503                 {
504                     free( p_block );
505                     return -1;
506                 }
507             }
508             else return -1;
509         }
510
511 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
512         struct scsireq  sc;
513         int i_ret;
514
515         memset( &sc, 0, sizeof(sc) );
516         sc.cmd[0] = 0xBE;
517         sc.cmd[1] = i_type == VCD_TYPE ? SECTOR_TYPE_MODE2_FORM2:
518                                          SECTOR_TYPE_CDDA;
519         sc.cmd[2] = (i_sector >> 24) & 0xff;
520         sc.cmd[3] = (i_sector >> 16) & 0xff;
521         sc.cmd[4] = (i_sector >>  8) & 0xff;
522         sc.cmd[5] = (i_sector >>  0) & 0xff;
523         sc.cmd[6] = (i_nb >> 16) & 0xff;
524         sc.cmd[7] = (i_nb >>  8) & 0xff;
525         sc.cmd[8] = (i_nb      ) & 0xff;
526         sc.cmd[9] = i_type == VCD_TYPE ? READ_CD_RAW_MODE2 : READ_CD_USERDATA;
527         sc.cmd[10] = 0; /* sub channel */
528         sc.cmdlen = 12;
529         sc.databuf = (caddr_t)p_block;
530         sc.datalen = VCD_SECTOR_SIZE * i_nb;
531         sc.senselen = sizeof( sc.sense );
532         sc.flags = SCCMD_READ;
533         sc.timeout = 10000;
534
535         i_ret = ioctl( p_vcddev->i_device_handle, SCIOCCOMMAND, &sc );
536         if( i_ret == -1 )
537         {
538             msg_Err( p_this, "SCIOCCOMMAND failed" );
539             if( i_type == VCD_TYPE ) free( p_block );
540             return -1;
541         }
542         if( sc.retsts || sc.error )
543         {
544             msg_Err( p_this, "SCSI command failed: status %d error %d",
545                              sc.retsts, sc.error );
546             if( i_type == VCD_TYPE ) free( p_block );
547            return -1;
548         }
549
550 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
551         int i_size = VCD_SECTOR_SIZE;
552
553         if( ioctl( p_vcddev->i_device_handle, CDRIOCSETBLOCKSIZE, &i_size )
554             == -1 )
555         {
556             msg_Err( p_this, "Could not set block size" );
557             if( i_type == VCD_TYPE ) free( p_block );
558             return( -1 );
559         }
560
561         if( lseek( p_vcddev->i_device_handle,
562                    i_sector * VCD_SECTOR_SIZE, SEEK_SET ) == -1 )
563         {
564             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
565             if( i_type == VCD_TYPE ) free( p_block );
566             return( -1 );
567         }
568
569         if( read( p_vcddev->i_device_handle,
570                   p_block, VCD_SECTOR_SIZE * i_nb ) == -1 )
571         {
572             msg_Err( p_this, "Could not read sector %d", i_sector );
573             if( i_type == VCD_TYPE ) free( p_block );
574             return( -1 );
575         }
576
577 #else
578         for( i = 0; i < i_nb; i++ )
579         {
580             int i_dummy = i_sector + i + 2 * CD_FRAMES;
581
582 #define p_msf ((struct cdrom_msf0 *)(p_block + i * VCD_SECTOR_SIZE))
583             p_msf->minute =   i_dummy / (CD_FRAMES * CD_SECS);
584             p_msf->second = ( i_dummy % (CD_FRAMES * CD_SECS) ) / CD_FRAMES;
585             p_msf->frame =  ( i_dummy % (CD_FRAMES * CD_SECS) ) % CD_FRAMES;
586 #undef p_msf
587
588             if( ioctl( p_vcddev->i_device_handle, CDROMREADRAW,
589                        p_block + i * VCD_SECTOR_SIZE ) == -1 )
590             {
591                 msg_Err( p_this, "could not read block %i from disc",
592                          i_sector );
593
594                 if( i == 0 )
595                 {
596                     if( i_type == VCD_TYPE ) free( p_block );
597                     return( -1 );
598                 }
599                 else break;
600             }
601         }
602 #endif
603     }
604
605     /* For VCDs, we don't want to keep the header and footer of the
606      * sectors read */
607     if( i_type == VCD_TYPE )
608     {
609         for( i = 0; i < i_nb; i++ )
610         {
611             memcpy( p_buffer + i * VCD_DATA_SIZE,
612                     p_block + i * VCD_SECTOR_SIZE + VCD_DATA_START,
613                     VCD_DATA_SIZE );
614         }
615         free( p_block );
616     }
617
618     return( 0 );
619 }
620
621 /****************************************************************************
622  * Private functions
623  ****************************************************************************/
624
625 /****************************************************************************
626  * OpenVCDImage: try to open a vcd image from a .cue file
627  ****************************************************************************/
628 static int OpenVCDImage( vlc_object_t * p_this, const char *psz_dev,
629                          vcddev_t *p_vcddev )
630 {
631     int i_ret = -1;
632     char *p_pos;
633     char *psz_vcdfile = NULL;
634     char *psz_cuefile = NULL;
635     FILE *cuefile     = NULL;
636     int *p_sectors    = NULL;
637     char line[1024];
638     bool b_found      = false;
639
640     /* Check if we are dealing with a .cue file */
641     p_pos = strrchr( psz_dev, '.' );
642     if( p_pos && !strcmp( p_pos, ".cue" ) )
643     {
644         /* psz_dev must be the cue file. Let's assume there's a .bin
645          * file with the same filename */
646         psz_vcdfile = malloc( p_pos - psz_dev + 5 /* ".bin" */ );
647         strncpy( psz_vcdfile, psz_dev, p_pos - psz_dev );
648         strcpy( psz_vcdfile + (p_pos - psz_dev), ".bin");
649         psz_cuefile = strdup( psz_dev );
650     }
651     else
652     {
653         /* psz_dev must be the actual vcd file. Let's assume there's a .cue
654          * file with the same filename */
655         if( p_pos )
656         {
657             psz_cuefile = malloc( p_pos - psz_dev + 5 /* ".cue" */ );
658             strncpy( psz_cuefile, psz_dev, p_pos - psz_dev );
659             strcpy( psz_cuefile + (p_pos - psz_dev), ".cue");
660         }
661         else
662         {
663             if( asprintf( &psz_cuefile, "%s.cue", psz_dev ) == -1 )
664                 psz_cuefile = NULL;
665         }
666         /* If we need to look up the .cue file, then we don't have to look for the vcd */
667         psz_vcdfile = strdup( psz_dev );
668     }
669
670     /* Open the cue file and try to parse it */
671     msg_Dbg( p_this,"trying .cue file: %s", psz_cuefile );
672     cuefile = vlc_fopen( psz_cuefile, "rt" );
673     if( cuefile == NULL )
674     {
675         msg_Dbg( p_this, "could not find .cue file" );
676         goto error;
677     }
678
679     msg_Dbg( p_this,"guessing vcd image file: %s", psz_vcdfile );
680     p_vcddev->i_vcdimage_handle = vlc_open( psz_vcdfile,
681                                     O_RDONLY | O_NONBLOCK | O_BINARY );
682  
683     while( fgets( line, 1024, cuefile ) && !b_found )
684     {
685         /* We have a cue file, but no valid vcd file yet */
686         char filename[1024];
687         char type[16];
688         int i_temp = sscanf( line, "FILE \"%1023[^\"]\" %15s", filename, type );
689         switch( i_temp )
690         {
691             case 2:
692                 msg_Dbg( p_this, "the cue file says the data file is %s", type );
693                 if( strcasecmp( type, "BINARY" ) )
694                     goto error; /* Error if not binary, otherwise treat as case 1 */
695             case 1:
696                 if( p_vcddev->i_vcdimage_handle == -1 )
697                 {
698                     msg_Dbg( p_this, "we could not find the data file, but we found a new path" );
699                     free( psz_vcdfile);
700                     if( *filename != '/' && ((p_pos = strrchr( psz_cuefile, '/' ))
701                         || (p_pos = strrchr( psz_cuefile, '\\' ) )) )
702                     {
703                         psz_vcdfile = malloc( strlen(filename) +
704                                       (p_pos - psz_cuefile + 1) + 1 );
705                         strncpy( psz_vcdfile, psz_cuefile, (p_pos - psz_cuefile + 1) );
706                         strcpy( psz_vcdfile + (p_pos - psz_cuefile + 1), filename );
707                     } else psz_vcdfile = strdup( filename );
708                     msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
709                     p_vcddev->i_vcdimage_handle = vlc_open( psz_vcdfile,
710                                         O_RDONLY | O_NONBLOCK | O_BINARY );
711                 }
712                 b_found = true;
713             default:
714                 break;
715         }
716     }
717
718     if( p_vcddev->i_vcdimage_handle == -1)
719         goto error;
720
721     /* Try to parse the i_tracks and p_sectors info so we can just forget
722      * about the cuefile */
723     size_t i_tracks = 0;
724
725     while( fgets( line, 1024, cuefile ) && i_tracks < INT_MAX-1 )
726     {
727         /* look for a TRACK line */
728         char psz_dummy[9];
729         if( !sscanf( line, "%9s", psz_dummy ) || strcmp(psz_dummy, "TRACK") )
730             continue;
731
732         /* look for an INDEX line */
733         while( fgets( line, 1024, cuefile ) )
734         {
735             int i_num, i_min, i_sec, i_frame;
736
737             if( (sscanf( line, "%*9s %2u %2u:%2u:%2u", &i_num,
738                          &i_min, &i_sec, &i_frame ) != 4) || (i_num != 1) )
739                 continue;
740
741             int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
742             if (buf == NULL)
743                 goto error;
744             p_sectors = buf;
745             p_sectors[i_tracks] = MSF_TO_LBA(i_min, i_sec, i_frame);
746             msg_Dbg( p_this, "vcd track %i begins at sector:%i",
747                      (int)i_tracks, (int)p_sectors[i_tracks] );
748             i_tracks++;
749             break;
750         }
751     }
752
753     /* fill in the last entry */
754     int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
755     if (buf == NULL)
756         goto error;
757     p_sectors = buf;
758     p_sectors[i_tracks] = lseek(p_vcddev->i_vcdimage_handle, 0, SEEK_END)
759                                  / VCD_SECTOR_SIZE;
760     msg_Dbg( p_this, "vcd track %i, begins at sector:%i",
761              (int)i_tracks, (int)p_sectors[i_tracks] );
762     p_vcddev->i_tracks = ++i_tracks;
763     p_vcddev->p_sectors = p_sectors;
764     i_ret = 0;
765
766 error:
767     if( cuefile ) fclose( cuefile );
768     free( p_sectors );
769     free( psz_cuefile );
770     free( psz_vcdfile );
771
772     return i_ret;
773 }
774
775 /****************************************************************************
776  * CloseVCDImage: closes a vcd image opened by OpenVCDImage
777  ****************************************************************************/
778 static void CloseVCDImage( vlc_object_t * p_this, vcddev_t *p_vcddev )
779 {
780     VLC_UNUSED( p_this );
781     if( p_vcddev->i_vcdimage_handle != -1 )
782         close( p_vcddev->i_vcdimage_handle );
783     else
784         return;
785
786     free( p_vcddev->p_sectors );
787 }
788
789 #if defined( __APPLE__ )
790 /****************************************************************************
791  * darwin_getTOC: get the TOC
792  ****************************************************************************/
793 static CDTOC *darwin_getTOC( vlc_object_t * p_this, const vcddev_t *p_vcddev )
794 {
795     mach_port_t port;
796     char *psz_devname;
797     kern_return_t ret;
798     CDTOC *pTOC = NULL;
799     io_iterator_t iterator;
800     io_registry_entry_t service;
801     CFMutableDictionaryRef properties;
802     CFDataRef data;
803
804     /* get the device name */
805     if( ( psz_devname = strrchr( p_vcddev->psz_dev, '/') ) != NULL )
806         ++psz_devname;
807     else
808         psz_devname = p_vcddev->psz_dev;
809
810     /* unraw the device name */
811     if( *psz_devname == 'r' )
812         ++psz_devname;
813
814     /* get port for IOKit communication */
815     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
816     {
817         msg_Err( p_this, "IOMasterPort: 0x%08x", ret );
818         return( NULL );
819     }
820
821     /* get service iterator for the device */
822     if( ( ret = IOServiceGetMatchingServices(
823                     port, IOBSDNameMatching( port, 0, psz_devname ),
824                     &iterator ) ) != KERN_SUCCESS )
825     {
826         msg_Err( p_this, "IOServiceGetMatchingServices: 0x%08x", ret );
827         return( NULL );
828     }
829
830     /* first service */
831     service = IOIteratorNext( iterator );
832     IOObjectRelease( iterator );
833
834     /* search for kIOCDMediaClass */
835     while( service && !IOObjectConformsTo( service, kIOCDMediaClass ) )
836     {
837         if( ( ret = IORegistryEntryGetParentIterator( service,
838                         kIOServicePlane, &iterator ) ) != KERN_SUCCESS )
839         {
840             msg_Err( p_this, "IORegistryEntryGetParentIterator: 0x%08x", ret );
841             IOObjectRelease( service );
842             return( NULL );
843         }
844
845         IOObjectRelease( service );
846         service = IOIteratorNext( iterator );
847         IOObjectRelease( iterator );
848     }
849
850     if( !service )
851     {
852         msg_Err( p_this, "search for kIOCDMediaClass came up empty" );
853         return( NULL );
854     }
855
856     /* create a CF dictionary containing the TOC */
857     if( ( ret = IORegistryEntryCreateCFProperties( service, &properties,
858                     kCFAllocatorDefault, kNilOptions ) ) != KERN_SUCCESS )
859     {
860         msg_Err( p_this, "IORegistryEntryCreateCFProperties: 0x%08x", ret );
861         IOObjectRelease( service );
862         return( NULL );
863     }
864
865     /* get the TOC from the dictionary */
866     if( ( data = (CFDataRef) CFDictionaryGetValue( properties,
867                                     CFSTR(kIOCDMediaTOCKey) ) ) != NULL )
868     {
869         CFRange range;
870         CFIndex buf_len;
871
872         buf_len = CFDataGetLength( data ) + 1;
873         range = CFRangeMake( 0, buf_len );
874
875         if( ( pTOC = malloc( buf_len ) ) != NULL )
876         {
877             CFDataGetBytes( data, range, (u_char *)pTOC );
878         }
879     }
880     else
881     {
882         msg_Err( p_this, "CFDictionaryGetValue failed" );
883     }
884
885     CFRelease( properties );
886     IOObjectRelease( service );
887
888     return( pTOC );
889 }
890
891 /****************************************************************************
892  * darwin_getNumberOfTracks: get number of tracks in TOC
893  ****************************************************************************/
894 static int darwin_getNumberOfTracks( CDTOC *pTOC, int i_descriptors )
895 {
896     u_char track;
897     int i, i_tracks = 0;
898     CDTOCDescriptor *pTrackDescriptors = NULL;
899
900     pTrackDescriptors = (CDTOCDescriptor *)pTOC->descriptors;
901
902     for( i = i_descriptors; i > 0; i-- )
903     {
904         track = pTrackDescriptors[i].point;
905
906         if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
907             continue;
908
909         i_tracks++;
910     }
911
912     return( i_tracks );
913 }
914 #endif /* __APPLE__ */
915
916 #if defined( WIN32 )
917 /*****************************************************************************
918  * win32_vcd_open: open vcd drive
919  *****************************************************************************
920  * Use IOCTLs on WinNT/2K/XP.
921  *****************************************************************************/
922 static int win32_vcd_open( vlc_object_t * p_this, const char *psz_dev,
923                            vcddev_t *p_vcddev )
924 {
925     /* Initializations */
926     p_vcddev->h_device_handle = NULL;
927
928     char psz_win32_drive[7];
929
930     msg_Dbg( p_this, "using winNT/2K/XP ioctl layer" );
931
932     sprintf( psz_win32_drive, "\\\\.\\%c:", psz_dev[0] );
933
934     p_vcddev->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
935                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
936                                             NULL, OPEN_EXISTING,
937                                             FILE_FLAG_NO_BUFFERING |
938                                             FILE_FLAG_RANDOM_ACCESS, NULL );
939     return (p_vcddev->h_device_handle == NULL) ? -1 : 0;
940 }
941
942 #endif /* WIN32 */
943
944 /* */
945 static void astrcat( char **ppsz_dst, char *psz_src )
946 {
947     char *psz_old = *ppsz_dst;
948
949     if( !psz_old )
950     {
951         *ppsz_dst = strdup( psz_src );
952     }
953     else if( psz_src )
954     {
955         if( asprintf( ppsz_dst, "%s%s", psz_old, psz_src ) < 0 )
956             *ppsz_dst = psz_old;
957         else
958             free( psz_old );
959     }
960 }
961
962 /* */
963 static int CdTextParse( vlc_meta_t ***ppp_tracks, int *pi_tracks,
964                         const uint8_t *p_buffer, int i_buffer )
965 {
966     char *pppsz_info[128][0x10];
967     int i_track_last = -1;
968     if( i_buffer < 4 )
969         return -1;
970
971     memset( pppsz_info, 0, sizeof(pppsz_info) );
972
973     for( int i = 0; i < (i_buffer-4)/18; i++ )
974     {
975         const uint8_t *p_block = &p_buffer[4 + 18*i];
976         char psz_text[12+1];
977
978         const int i_pack_type = p_block[0];
979         if( i_pack_type < 0x80 || i_pack_type > 0x8f )
980             continue;
981
982         const int i_track_number = (p_block[1] >> 0)&0x7f;
983         const int i_extension_flag = ( p_block[1] >> 7)& 0x01;
984         if( i_extension_flag )
985             continue;
986
987         //const int i_sequence_number = p_block[2];
988         //const int i_charater_position = (p_block[3] >> 0) &0x0f;
989         //const int i_block_number = (p_block[3] >> 4) &0x07;
990         /* TODO unicode support
991          * I need a sample */
992         //const int i_unicode = ( p_block[3] >> 7)&0x01;
993         //const int i_crc = (p_block[4+12] << 8) | (p_block[4+13] << 0);
994
995         /* */
996         memcpy( psz_text, &p_block[4], 12 );
997         psz_text[12] = '\0';
998
999         /* */
1000         int i_track =  i_track_number;
1001         char *psz_track = &psz_text[0];
1002         while( i_track <= 127 && psz_track < &psz_text[12] )
1003         {
1004             //fprintf( stderr, "t=%d psz_track=%p end=%p", i_track, psz_track, &psz_text[12] );
1005             if( *psz_track )
1006             {
1007                 astrcat( &pppsz_info[i_track][i_pack_type-0x80], psz_track );
1008                 i_track_last = __MAX( i_track_last, i_track );
1009             }
1010
1011             i_track++;
1012             psz_track += 1 + strlen(psz_track);
1013         }
1014     }
1015
1016     if( i_track_last < 0 )
1017         return -1;
1018
1019     vlc_meta_t **pp_tracks = calloc( i_track_last+1, sizeof(*pp_tracks) );
1020     if( !pp_tracks )
1021         goto exit;
1022
1023     for( int j = 0; j < 0x10; j++ )
1024     {
1025         for( int i = 0; i <= i_track_last; i++ )
1026         {
1027             /* */
1028             if( pppsz_info[i][j] )
1029                 EnsureUTF8( pppsz_info[i][j] );
1030
1031             /* */
1032             const char *psz_default = pppsz_info[0][j];
1033             const char *psz_value = pppsz_info[i][j];
1034
1035             if( !psz_value && !psz_default )
1036                 continue;
1037             vlc_meta_t *p_track = pp_tracks[i];
1038             if( !p_track )
1039             {
1040                 p_track = pp_tracks[i] = vlc_meta_New();
1041                 if( !p_track )
1042                     continue;
1043             }
1044             switch( j )
1045             {
1046             case 0x00: /* Album/Title */
1047                 if( i == 0 )
1048                 {
1049                     vlc_meta_SetAlbum( p_track, psz_value );
1050                 }
1051                 else
1052                 {
1053                     if( psz_value )
1054                         vlc_meta_SetTitle( p_track, psz_value );
1055                     if( psz_default )
1056                         vlc_meta_SetAlbum( p_track, psz_default );
1057                 }
1058                 break;
1059             case 0x01: /* Performer */
1060                 vlc_meta_SetArtist( p_track,
1061                                     psz_value ? psz_value : psz_default );
1062                 break;
1063             case 0x05: /* Messages */
1064                 vlc_meta_SetDescription( p_track,
1065                                          psz_value ? psz_value : psz_default );
1066                 break;
1067             case 0x07: /* Genre */
1068                 vlc_meta_SetGenre( p_track,
1069                                    psz_value ? psz_value : psz_default );
1070                 break;
1071             /* FIXME unsupported:
1072              * 0x02: songwriter
1073              * 0x03: composer
1074              * 0x04: arrenger
1075              * 0x06: disc id */
1076             }
1077         }
1078     }
1079     /* */
1080 exit:
1081     for( int j = 0; j < 0x10; j++ )
1082         for( int i = 0; i <= i_track_last; i++ )
1083             free( pppsz_info[i][j] );
1084
1085     *ppp_tracks = pp_tracks;
1086     *pi_tracks = i_track_last+1;
1087     return pp_tracks ? 0 : -1;
1088 }
1089
1090 #if defined( __APPLE__ ) || \
1091     defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) || \
1092     defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
1093 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1094                        uint8_t **pp_buffer, int *pi_buffer )
1095 {
1096     VLC_UNUSED( p_object );
1097     VLC_UNUSED( p_vcddev );
1098     VLC_UNUSED( pp_buffer );
1099     VLC_UNUSED( pi_buffer );
1100     return -1;
1101 }
1102 #elif defined( WIN32 )
1103 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1104                        uint8_t **pp_buffer, int *pi_buffer )
1105 {
1106     VLC_UNUSED( p_object );
1107
1108     CDROM_READ_TOC_EX TOCEx;
1109     memset(&TOCEx, 0, sizeof(TOCEx));
1110     TOCEx.Format = CDROM_READ_TOC_EX_FORMAT_CDTEXT;
1111
1112     const int i_header_size = __MAX( 4, MINIMUM_CDROM_READ_TOC_EX_SIZE );
1113     uint8_t header[i_header_size];
1114     DWORD i_read;
1115     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1116                           &TOCEx, sizeof(TOCEx), header, i_header_size, &i_read, 0 ) )
1117         return -1;
1118
1119     const int i_text = 2 + (header[0] << 8) + header[1];
1120     if( i_text <= 4 )
1121         return -1;
1122
1123     /* Read complete CD-TEXT */
1124     uint8_t *p_text = calloc( 1, i_text );
1125     if( !p_text )
1126         return VLC_EGENERIC;
1127
1128     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1129                           &TOCEx, sizeof(TOCEx), p_text, i_text, &i_read, 0 ) )
1130     {
1131         free( p_text );
1132         return VLC_EGENERIC;
1133     }
1134
1135     /* */
1136     *pp_buffer = p_text;
1137     *pi_buffer = i_text;
1138     return VLC_SUCCESS;
1139 }
1140 #else
1141 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1142                        uint8_t **pp_buffer, int *pi_buffer )
1143 {
1144     VLC_UNUSED( p_object );
1145
1146     if( p_vcddev->i_device_handle == -1 )
1147         return -1;
1148
1149     struct cdrom_generic_command gc;
1150     uint8_t header[4];
1151
1152     /* Read CD-TEXT size */
1153     memset( header, 0, sizeof(header) );
1154     memset( &gc, 0, sizeof(gc) );
1155     gc.cmd[0] = 0x43;   /* Read TOC */
1156     gc.cmd[1] = 0x02;   /* MSF */
1157     gc.cmd[2] = 5;      /* CD-Text */
1158     gc.cmd[7] = ( sizeof(header) >> 8 ) & 0xff;
1159     gc.cmd[8] = ( sizeof(header) >> 0 ) & 0xff;
1160
1161     gc.buflen = sizeof(header);
1162     gc.buffer = header;
1163     gc.data_direction = CGC_DATA_READ;
1164     gc.timeout = 1000;
1165
1166     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1167         return VLC_EGENERIC;
1168
1169     /* If the size is less than 4 it is an error, if it 4 then
1170      * it means no text data */
1171     const int i_text = 2 + (header[0] << 8) + header[1];
1172     if( i_text <= 4 )
1173         return VLC_EGENERIC;
1174
1175     /* Read complete CD-TEXT */
1176     uint8_t *p_text = calloc( 1, i_text );
1177     if( !p_text )
1178         return VLC_EGENERIC;
1179
1180     memset( &gc, 0, sizeof(gc) );
1181     gc.cmd[0] = 0x43;   /* Read TOC */
1182     gc.cmd[1] = 0x02;   /* MSF */
1183     gc.cmd[2] = 5;      /* CD-Text */
1184     gc.cmd[7] = ( i_text >> 8 ) & 0xff;
1185     gc.cmd[8] = ( i_text >> 0 ) & 0xff;
1186
1187     gc.buflen = i_text;
1188     gc.buffer = p_text;
1189     gc.data_direction = CGC_DATA_READ;
1190     gc.timeout = 1000;
1191
1192     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1193     {
1194         free( p_text );
1195         return VLC_EGENERIC;
1196     }
1197
1198     /* */
1199     *pp_buffer = p_text;
1200     *pi_buffer = i_text;
1201     return VLC_SUCCESS;
1202 }
1203 #endif
1204
1205 int ioctl_GetCdText( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1206                      vlc_meta_t ***ppp_tracks, int *pi_tracks )
1207 {
1208     uint8_t *p_text;
1209     int i_text;
1210
1211     if( p_vcddev->i_vcdimage_handle != -1 )
1212         return -1;
1213
1214     if( CdTextRead( p_object, p_vcddev, &p_text, &i_text ) )
1215         return -1;
1216
1217     CdTextParse( ppp_tracks, pi_tracks, p_text, i_text );
1218     free( p_text );
1219     return 0;
1220 }
1221