]> git.sesse.net Git - vlc/blob - modules/access/vcd/cdrom.c
utf8_* -> vlc_* (sed roxxors)
[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         *p_pos = 0;
690         switch( i_temp )
691         {
692             case 2:
693                 msg_Dbg( p_this, "the cue file says the data file is %s", type );
694                 if( strcasecmp( type, "BINARY" ) )
695                     goto error; /* Error if not binary, otherwise treat as case 1 */
696             case 1:
697                 if( p_vcddev->i_vcdimage_handle == -1 )
698                 {
699                     msg_Dbg( p_this, "we could not find the data file, but we found a new path" );
700                     free( psz_vcdfile);
701                     if( *filename != '/' && ((p_pos = strrchr( psz_cuefile, '/' ))
702                         || (p_pos = strrchr( psz_cuefile, '\\' ) )) )
703                     {
704                         psz_vcdfile = malloc( strlen(filename) +
705                                       (p_pos - psz_cuefile + 1) + 1 );
706                         strncpy( psz_vcdfile, psz_cuefile, (p_pos - psz_cuefile + 1) );
707                         strcpy( psz_vcdfile + (p_pos - psz_cuefile + 1), filename );
708                     } else psz_vcdfile = strdup( filename );
709                     msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
710                     p_vcddev->i_vcdimage_handle = vlc_open( psz_vcdfile,
711                                         O_RDONLY | O_NONBLOCK | O_BINARY );
712                 }
713                 b_found = true;
714             default:
715                 break;
716         }
717     }
718
719     if( p_vcddev->i_vcdimage_handle == -1)
720         goto error;
721
722     /* Try to parse the i_tracks and p_sectors info so we can just forget
723      * about the cuefile */
724     size_t i_tracks = 0;
725
726     while( fgets( line, 1024, cuefile ) && i_tracks < INT_MAX-1 )
727     {
728         /* look for a TRACK line */
729         char psz_dummy[9];
730         if( !sscanf( line, "%9s", psz_dummy ) || strcmp(psz_dummy, "TRACK") )
731             continue;
732
733         /* look for an INDEX line */
734         while( fgets( line, 1024, cuefile ) )
735         {
736             int i_num, i_min, i_sec, i_frame;
737
738             if( (sscanf( line, "%*9s %2u %2u:%2u:%2u", &i_num,
739                          &i_min, &i_sec, &i_frame ) != 4) || (i_num != 1) )
740                 continue;
741
742             int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
743             if (buf == NULL)
744                 goto error;
745             p_sectors = buf;
746             p_sectors[i_tracks] = MSF_TO_LBA(i_min, i_sec, i_frame);
747             msg_Dbg( p_this, "vcd track %i begins at sector:%i",
748                      (int)i_tracks, (int)p_sectors[i_tracks] );
749             i_tracks++;
750             break;
751         }
752     }
753
754     /* fill in the last entry */
755     int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
756     if (buf == NULL)
757         goto error;
758     p_sectors = buf;
759     p_sectors[i_tracks] = lseek(p_vcddev->i_vcdimage_handle, 0, SEEK_END)
760                                  / VCD_SECTOR_SIZE;
761     msg_Dbg( p_this, "vcd track %i, begins at sector:%i",
762              (int)i_tracks, (int)p_sectors[i_tracks] );
763     p_vcddev->i_tracks = ++i_tracks;
764     p_vcddev->p_sectors = p_sectors;
765     i_ret = 0;
766
767 error:
768     if( cuefile ) fclose( cuefile );
769     free( p_sectors );
770     free( psz_cuefile );
771     free( psz_vcdfile );
772
773     return i_ret;
774 }
775
776 /****************************************************************************
777  * CloseVCDImage: closes a vcd image opened by OpenVCDImage
778  ****************************************************************************/
779 static void CloseVCDImage( vlc_object_t * p_this, vcddev_t *p_vcddev )
780 {
781     VLC_UNUSED( p_this );
782     if( p_vcddev->i_vcdimage_handle != -1 )
783         close( p_vcddev->i_vcdimage_handle );
784     else
785         return;
786
787     free( p_vcddev->p_sectors );
788 }
789
790 #if defined( __APPLE__ )
791 /****************************************************************************
792  * darwin_getTOC: get the TOC
793  ****************************************************************************/
794 static CDTOC *darwin_getTOC( vlc_object_t * p_this, const vcddev_t *p_vcddev )
795 {
796     mach_port_t port;
797     char *psz_devname;
798     kern_return_t ret;
799     CDTOC *pTOC = NULL;
800     io_iterator_t iterator;
801     io_registry_entry_t service;
802     CFMutableDictionaryRef properties;
803     CFDataRef data;
804
805     /* get the device name */
806     if( ( psz_devname = strrchr( p_vcddev->psz_dev, '/') ) != NULL )
807         ++psz_devname;
808     else
809         psz_devname = p_vcddev->psz_dev;
810
811     /* unraw the device name */
812     if( *psz_devname == 'r' )
813         ++psz_devname;
814
815     /* get port for IOKit communication */
816     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
817     {
818         msg_Err( p_this, "IOMasterPort: 0x%08x", ret );
819         return( NULL );
820     }
821
822     /* get service iterator for the device */
823     if( ( ret = IOServiceGetMatchingServices(
824                     port, IOBSDNameMatching( port, 0, psz_devname ),
825                     &iterator ) ) != KERN_SUCCESS )
826     {
827         msg_Err( p_this, "IOServiceGetMatchingServices: 0x%08x", ret );
828         return( NULL );
829     }
830
831     /* first service */
832     service = IOIteratorNext( iterator );
833     IOObjectRelease( iterator );
834
835     /* search for kIOCDMediaClass */
836     while( service && !IOObjectConformsTo( service, kIOCDMediaClass ) )
837     {
838         if( ( ret = IORegistryEntryGetParentIterator( service,
839                         kIOServicePlane, &iterator ) ) != KERN_SUCCESS )
840         {
841             msg_Err( p_this, "IORegistryEntryGetParentIterator: 0x%08x", ret );
842             IOObjectRelease( service );
843             return( NULL );
844         }
845
846         IOObjectRelease( service );
847         service = IOIteratorNext( iterator );
848         IOObjectRelease( iterator );
849     }
850
851     if( !service )
852     {
853         msg_Err( p_this, "search for kIOCDMediaClass came up empty" );
854         return( NULL );
855     }
856
857     /* create a CF dictionary containing the TOC */
858     if( ( ret = IORegistryEntryCreateCFProperties( service, &properties,
859                     kCFAllocatorDefault, kNilOptions ) ) != KERN_SUCCESS )
860     {
861         msg_Err( p_this, "IORegistryEntryCreateCFProperties: 0x%08x", ret );
862         IOObjectRelease( service );
863         return( NULL );
864     }
865
866     /* get the TOC from the dictionary */
867     if( ( data = (CFDataRef) CFDictionaryGetValue( properties,
868                                     CFSTR(kIOCDMediaTOCKey) ) ) != NULL )
869     {
870         CFRange range;
871         CFIndex buf_len;
872
873         buf_len = CFDataGetLength( data ) + 1;
874         range = CFRangeMake( 0, buf_len );
875
876         if( ( pTOC = malloc( buf_len ) ) != NULL )
877         {
878             CFDataGetBytes( data, range, (u_char *)pTOC );
879         }
880     }
881     else
882     {
883         msg_Err( p_this, "CFDictionaryGetValue failed" );
884     }
885
886     CFRelease( properties );
887     IOObjectRelease( service );
888
889     return( pTOC );
890 }
891
892 /****************************************************************************
893  * darwin_getNumberOfTracks: get number of tracks in TOC
894  ****************************************************************************/
895 static int darwin_getNumberOfTracks( CDTOC *pTOC, int i_descriptors )
896 {
897     u_char track;
898     int i, i_tracks = 0;
899     CDTOCDescriptor *pTrackDescriptors = NULL;
900
901     pTrackDescriptors = (CDTOCDescriptor *)pTOC->descriptors;
902
903     for( i = i_descriptors; i > 0; i-- )
904     {
905         track = pTrackDescriptors[i].point;
906
907         if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
908             continue;
909
910         i_tracks++;
911     }
912
913     return( i_tracks );
914 }
915 #endif /* __APPLE__ */
916
917 #if defined( WIN32 )
918 /*****************************************************************************
919  * win32_vcd_open: open vcd drive
920  *****************************************************************************
921  * Use IOCTLs on WinNT/2K/XP.
922  *****************************************************************************/
923 static int win32_vcd_open( vlc_object_t * p_this, const char *psz_dev,
924                            vcddev_t *p_vcddev )
925 {
926     /* Initializations */
927     p_vcddev->h_device_handle = NULL;
928
929     char psz_win32_drive[7];
930
931     msg_Dbg( p_this, "using winNT/2K/XP ioctl layer" );
932
933     sprintf( psz_win32_drive, "\\\\.\\%c:", psz_dev[0] );
934
935     p_vcddev->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
936                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
937                                             NULL, OPEN_EXISTING,
938                                             FILE_FLAG_NO_BUFFERING |
939                                             FILE_FLAG_RANDOM_ACCESS, NULL );
940     return (p_vcddev->h_device_handle == NULL) ? -1 : 0;
941 }
942
943 #endif /* WIN32 */
944
945 /* */
946 static void astrcat( char **ppsz_dst, char *psz_src )
947 {
948     char *psz_old = *ppsz_dst;
949
950     if( !psz_old )
951     {
952         *ppsz_dst = strdup( psz_src );
953     }
954     else if( psz_src )
955     {
956         if( asprintf( ppsz_dst, "%s%s", psz_old, psz_src ) < 0 )
957             *ppsz_dst = psz_old;
958         else
959             free( psz_old );
960     }
961 }
962
963 /* */
964 static int CdTextParse( vlc_meta_t ***ppp_tracks, int *pi_tracks,
965                         const uint8_t *p_buffer, int i_buffer )
966 {
967     char *pppsz_info[128][0x10];
968     int i_track_last = -1;
969     if( i_buffer < 4 )
970         return -1;
971
972     memset( pppsz_info, 0, sizeof(pppsz_info) );
973
974     for( int i = 0; i < (i_buffer-4)/18; i++ )
975     {
976         const uint8_t *p_block = &p_buffer[4 + 18*i];
977         char psz_text[12+1];
978
979         const int i_pack_type = p_block[0];
980         if( i_pack_type < 0x80 || i_pack_type > 0x8f )
981             continue;
982
983         const int i_track_number = (p_block[1] >> 0)&0x7f;
984         const int i_extension_flag = ( p_block[1] >> 7)& 0x01;
985         if( i_extension_flag )
986             continue;
987
988         //const int i_sequence_number = p_block[2];
989         //const int i_charater_position = (p_block[3] >> 0) &0x0f;
990         //const int i_block_number = (p_block[3] >> 4) &0x07;
991         /* TODO unicode support
992          * I need a sample */
993         //const int i_unicode = ( p_block[3] >> 7)&0x01;
994         //const int i_crc = (p_block[4+12] << 8) | (p_block[4+13] << 0);
995
996         /* */
997         memcpy( psz_text, &p_block[4], 12 );
998         psz_text[12] = '\0';
999
1000         /* */
1001         int i_track =  i_track_number;
1002         char *psz_track = &psz_text[0];
1003         while( i_track <= 127 && psz_track < &psz_text[12] )
1004         {
1005             //fprintf( stderr, "t=%d psz_track=%p end=%p", i_track, psz_track, &psz_text[12] );
1006             if( *psz_track )
1007             {
1008                 astrcat( &pppsz_info[i_track][i_pack_type-0x80], psz_track );
1009                 i_track_last = __MAX( i_track_last, i_track );
1010             }
1011
1012             i_track++;
1013             psz_track += 1 + strlen(psz_track);
1014         }
1015     }
1016
1017     if( i_track_last < 0 )
1018         return -1;
1019
1020     vlc_meta_t **pp_tracks = calloc( i_track_last+1, sizeof(*pp_tracks) );
1021     if( !pp_tracks )
1022         goto exit;
1023
1024     for( int j = 0; j < 0x10; j++ )
1025     {
1026         for( int i = 0; i <= i_track_last; i++ )
1027         {
1028             /* */
1029             if( pppsz_info[i][j] )
1030                 EnsureUTF8( pppsz_info[i][j] );
1031
1032             /* */
1033             const char *psz_default = pppsz_info[0][j];
1034             const char *psz_value = pppsz_info[i][j];
1035
1036             if( !psz_value && !psz_default )
1037                 continue;
1038             vlc_meta_t *p_track = pp_tracks[i];
1039             if( !p_track )
1040             {
1041                 p_track = pp_tracks[i] = vlc_meta_New();
1042                 if( !p_track )
1043                     continue;
1044             }
1045             switch( j )
1046             {
1047             case 0x00: /* Album/Title */
1048                 if( i == 0 )
1049                 {
1050                     vlc_meta_SetAlbum( p_track, psz_value );
1051                 }
1052                 else
1053                 {
1054                     if( psz_value )
1055                         vlc_meta_SetTitle( p_track, psz_value );
1056                     if( psz_default )
1057                         vlc_meta_SetAlbum( p_track, psz_default );
1058                 }
1059                 break;
1060             case 0x01: /* Performer */
1061                 vlc_meta_SetArtist( p_track,
1062                                     psz_value ? psz_value : psz_default );
1063                 break;
1064             case 0x05: /* Messages */
1065                 vlc_meta_SetDescription( p_track,
1066                                          psz_value ? psz_value : psz_default );
1067                 break;
1068             case 0x07: /* Genre */
1069                 vlc_meta_SetGenre( p_track,
1070                                    psz_value ? psz_value : psz_default );
1071                 break;
1072             /* FIXME unsupported:
1073              * 0x02: songwriter
1074              * 0x03: composer
1075              * 0x04: arrenger
1076              * 0x06: disc id */
1077             }
1078         }
1079     }
1080     /* */
1081 exit:
1082     for( int j = 0; j < 0x10; j++ )
1083         for( int i = 0; i <= i_track_last; i++ )
1084             free( pppsz_info[i][j] );
1085
1086     *ppp_tracks = pp_tracks;
1087     *pi_tracks = i_track_last+1;
1088     return pp_tracks ? 0 : -1;
1089 }
1090
1091 #if defined( __APPLE__ ) || \
1092     defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) || \
1093     defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
1094 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1095                        uint8_t **pp_buffer, int *pi_buffer )
1096 {
1097     VLC_UNUSED( p_object );
1098     VLC_UNUSED( p_vcddev );
1099     VLC_UNUSED( pp_buffer );
1100     VLC_UNUSED( pi_buffer );
1101     return -1;
1102 }
1103 #elif defined( WIN32 )
1104 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1105                        uint8_t **pp_buffer, int *pi_buffer )
1106 {
1107     VLC_UNUSED( p_object );
1108
1109     CDROM_READ_TOC_EX TOCEx;
1110     memset(&TOCEx, 0, sizeof(TOCEx));
1111     TOCEx.Format = CDROM_READ_TOC_EX_FORMAT_CDTEXT;
1112
1113     const int i_header_size = __MAX( 4, MINIMUM_CDROM_READ_TOC_EX_SIZE );
1114     uint8_t header[i_header_size];
1115     DWORD i_read;
1116     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1117                           &TOCEx, sizeof(TOCEx), header, i_header_size, &i_read, 0 ) )
1118         return -1;
1119
1120     const int i_text = 2 + (header[0] << 8) + header[1];
1121     if( i_text <= 4 )
1122         return -1;
1123
1124     /* Read complete CD-TEXT */
1125     uint8_t *p_text = calloc( 1, i_text );
1126     if( !p_text )
1127         return VLC_EGENERIC;
1128
1129     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1130                           &TOCEx, sizeof(TOCEx), p_text, i_text, &i_read, 0 ) )
1131     {
1132         free( p_text );
1133         return VLC_EGENERIC;
1134     }
1135
1136     /* */
1137     *pp_buffer = p_text;
1138     *pi_buffer = i_text;
1139     return VLC_SUCCESS;
1140 }
1141 #else
1142 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1143                        uint8_t **pp_buffer, int *pi_buffer )
1144 {
1145     VLC_UNUSED( p_object );
1146
1147     if( p_vcddev->i_device_handle == -1 )
1148         return -1;
1149
1150     struct cdrom_generic_command gc;
1151     uint8_t header[4];
1152
1153     /* Read CD-TEXT size */
1154     memset( header, 0, sizeof(header) );
1155     memset( &gc, 0, sizeof(gc) );
1156     gc.cmd[0] = 0x43;   /* Read TOC */
1157     gc.cmd[1] = 0x02;   /* MSF */
1158     gc.cmd[2] = 5;      /* CD-Text */
1159     gc.cmd[7] = ( sizeof(header) >> 8 ) & 0xff;
1160     gc.cmd[8] = ( sizeof(header) >> 0 ) & 0xff;
1161
1162     gc.buflen = sizeof(header);
1163     gc.buffer = header;
1164     gc.data_direction = CGC_DATA_READ;
1165     gc.timeout = 1000;
1166
1167     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1168         return VLC_EGENERIC;
1169
1170     /* If the size is less than 4 it is an error, if it 4 then
1171      * it means no text data */
1172     const int i_text = 2 + (header[0] << 8) + header[1];
1173     if( i_text <= 4 )
1174         return VLC_EGENERIC;
1175
1176     /* Read complete CD-TEXT */
1177     uint8_t *p_text = calloc( 1, i_text );
1178     if( !p_text )
1179         return VLC_EGENERIC;
1180
1181     memset( &gc, 0, sizeof(gc) );
1182     gc.cmd[0] = 0x43;   /* Read TOC */
1183     gc.cmd[1] = 0x02;   /* MSF */
1184     gc.cmd[2] = 5;      /* CD-Text */
1185     gc.cmd[7] = ( i_text >> 8 ) & 0xff;
1186     gc.cmd[8] = ( i_text >> 0 ) & 0xff;
1187
1188     gc.buflen = i_text;
1189     gc.buffer = p_text;
1190     gc.data_direction = CGC_DATA_READ;
1191     gc.timeout = 1000;
1192
1193     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1194     {
1195         free( p_text );
1196         return VLC_EGENERIC;
1197     }
1198
1199     /* */
1200     *pp_buffer = p_text;
1201     *pi_buffer = i_text;
1202     return VLC_SUCCESS;
1203 }
1204 #endif
1205
1206 int ioctl_GetCdText( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1207                      vlc_meta_t ***ppp_tracks, int *pi_tracks )
1208 {
1209     uint8_t *p_text;
1210     int i_text;
1211
1212     if( p_vcddev->i_vcdimage_handle != -1 )
1213         return -1;
1214
1215     if( CdTextRead( p_object, p_vcddev, &p_text, &i_text ) )
1216         return -1;
1217
1218     CdTextParse( ppp_tracks, pi_tracks, p_text, i_text );
1219     free( p_text );
1220     return 0;
1221 }
1222