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