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