dvd_udf.c 25.9 KB
Newer Older
1 2 3 4 5 6
/*
 * This code is based on dvdudf by:
 *   Christian Wolff <scarabaeus@convergence.de>.
 *
 * Modifications by:
 *   Billy Biggs <vektor@dumbterm.net>.
7
 *   Björn Englund <d4bjorn@dtek.chalmers.se>.
8 9 10 11 12
 *
 * dvdudf: parse and read the UDF volume information of a DVD Video
 * Copyright (C) 1999 Christian Wolff for convergence integrated media
 * GmbH The author can be reached at scarabaeus@convergence.de, the
 * project's page is at http://linuxtv.org/dvd/
13
 *
14 15 16
 * This file is part of libdvdread.
 *
 * libdvdread is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18 19
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
20
 *
21 22 23 24
 * libdvdread is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
25
 *
26 27 28
 * You should have received a copy of the GNU General Public License along
 * with libdvdread; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29
 */
30

31
#include "config.h"
32 33 34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
35
#include <strings.h>
36 37 38 39 40 41

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <inttypes.h>

42
#include "dvdread_internal.h"
43 44
#include "dvdread/dvd_reader.h"
#include "dvdread/dvd_udf.h"
45 46 47

/* It's required to either fail or deliver all the blocks asked for. */
static int DVDReadLBUDF( dvd_reader_t *device, uint32_t lb_number,
48 49
                         size_t block_count, unsigned char *data,
                         int encrypted )
50 51 52 53
{
  size_t count = block_count;

  while(count > 0) {
54
    int ret;
55

56
    ret = InternalUDFReadBlocksRaw(device, lb_number, count, data + DVD_VIDEO_LB_LEN * (block_count - count), encrypted);
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

    if(ret <= 0) {
      /* One of the reads failed or nothing more to read, too bad.
       * We won't even bother returning the reads that went ok. */
      return ret;
    }

    count -= (size_t)ret;
    lb_number += (uint32_t)ret;
  }

  return block_count;
}


#ifndef NULL
#define NULL ((void *)0)
#endif

struct Partition {
  int valid;
  char VolumeDesc[128];
  uint16_t Flags;
  uint16_t Number;
  char Contents[32];
  uint32_t AccessType;
  uint32_t Start;
  uint32_t Length;
};

struct AD {
  uint32_t Location;
  uint32_t Length;
  uint8_t  Flags;
  uint16_t Partition;
};

struct extent_ad {
  uint32_t location;
  uint32_t length;
};

struct avdp_t {
  struct extent_ad mvds;
  struct extent_ad rvds;
};

struct pvd_t {
  uint8_t VolumeIdentifier[32];
  uint8_t VolumeSetIdentifier[128];
};

struct lbudf {
  uint32_t lb;
  uint8_t *data;
  /* needed for proper freeing */
  uint8_t *data_base;
};

struct icbmap {
  uint32_t lbn;
  struct AD file;
  uint8_t filetype;
};

struct udf_cache {
  int avdp_valid;
  struct avdp_t avdp;
  int pvd_valid;
  struct pvd_t pvd;
  int partition_valid;
  struct Partition partition;
  int rooticb_valid;
  struct AD rooticb;
  int lb_num;
  struct lbudf *lbs;
  int map_num;
  struct icbmap *maps;
};

typedef enum {
  PartitionCache, RootICBCache, LBUDFCache, MapCache, AVDPCache, PVDCache
} UDFCacheType;

void FreeUDFCache(void *cache)
{
  struct udf_cache *c = (struct udf_cache *)cache;
  if(c == NULL)
    return;

  if(c->lbs) {
    int n;
    for(n = 0; n < c->lb_num; n++)
      free(c->lbs[n].data_base);
    free(c->lbs);
  }
  if(c->maps)
    free(c->maps);
  free(c);
}


static int GetUDFCache(dvd_reader_t *device, UDFCacheType type,
160
                       uint32_t nr, void *data)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
{
  int n;
  struct udf_cache *c;

  if(DVDUDFCacheLevel(device, -1) <= 0)
    return 0;

  c = (struct udf_cache *)GetUDFCacheHandle(device);

  if(c == NULL)
    return 0;

  switch(type) {
  case AVDPCache:
    if(c->avdp_valid) {
      *(struct avdp_t *)data = c->avdp;
      return 1;
    }
    break;
  case PVDCache:
    if(c->pvd_valid) {
      *(struct pvd_t *)data = c->pvd;
      return 1;
    }
    break;
  case PartitionCache:
    if(c->partition_valid) {
      *(struct Partition *)data = c->partition;
      return 1;
    }
    break;
  case RootICBCache:
    if(c->rooticb_valid) {
      *(struct AD *)data = c->rooticb;
      return 1;
    }
    break;
  case LBUDFCache:
    for(n = 0; n < c->lb_num; n++) {
      if(c->lbs[n].lb == nr) {
201 202
        *(uint8_t **)data = c->lbs[n].data;
        return 1;
203 204 205 206 207 208
      }
    }
    break;
  case MapCache:
    for(n = 0; n < c->map_num; n++) {
      if(c->maps[n].lbn == nr) {
209 210
        *(struct icbmap *)data = c->maps[n];
        return 1;
211 212 213 214 215 216 217 218 219 220 221
      }
    }
    break;
  default:
    break;
  }

  return 0;
}

static int SetUDFCache(dvd_reader_t *device, UDFCacheType type,
222
                       uint32_t nr, void *data)
223 224 225 226 227 228 229 230 231 232 233
{
  int n;
  struct udf_cache *c;
  void *tmp;

  if(DVDUDFCacheLevel(device, -1) <= 0)
    return 0;

  c = (struct udf_cache *)GetUDFCacheHandle(device);

  if(c == NULL) {
234
    c = calloc(1, sizeof(struct udf_cache));
235 236 237 238 239 240 241 242 243
    /* fprintf(stderr, "calloc: %d\n", sizeof(struct udf_cache)); */
    if(c == NULL)
      return 0;
    SetUDFCacheHandle(device, c);
  }


  switch(type) {
  case AVDPCache:
244
    c->avdp = *(struct avdp_t *)data;
245 246 247
    c->avdp_valid = 1;
    break;
  case PVDCache:
248
    c->pvd = *(struct pvd_t *)data;
249 250 251
    c->pvd_valid = 1;
    break;
  case PartitionCache:
252
    c->partition = *(struct Partition *)data;
253 254 255
    c->partition_valid = 1;
    break;
  case RootICBCache:
256
    c->rooticb = *(struct AD *)data;
257 258 259 260 261
    c->rooticb_valid = 1;
    break;
  case LBUDFCache:
    for(n = 0; n < c->lb_num; n++) {
      if(c->lbs[n].lb == nr) {
262 263 264 265 266
        /* replace with new data */
        c->lbs[n].data_base = ((uint8_t **)data)[0];
        c->lbs[n].data = ((uint8_t **)data)[1];
        c->lbs[n].lb = nr;
        return 1;
267 268 269 270 271 272
      }
    }
    c->lb_num++;
    tmp = realloc(c->lbs, c->lb_num * sizeof(struct lbudf));
    /*
    fprintf(stderr, "realloc lb: %d * %d = %d\n",
273 274
    c->lb_num, sizeof(struct lbudf),
    c->lb_num * sizeof(struct lbudf));
275 276 277 278 279 280 281 282 283 284 285 286 287 288
    */
    if(tmp == NULL) {
      if(c->lbs) free(c->lbs);
      c->lb_num = 0;
      return 0;
    }
    c->lbs = tmp;
    c->lbs[n].data_base = ((uint8_t **)data)[0];
    c->lbs[n].data = ((uint8_t **)data)[1];
    c->lbs[n].lb = nr;
    break;
  case MapCache:
    for(n = 0; n < c->map_num; n++) {
      if(c->maps[n].lbn == nr) {
289 290 291 292
        /* replace with new data */
        c->maps[n] = *(struct icbmap *)data;
        c->maps[n].lbn = nr;
        return 1;
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
      }
    }
    c->map_num++;
    tmp = realloc(c->maps, c->map_num * sizeof(struct icbmap));
    /*
    fprintf(stderr, "realloc maps: %d * %d = %d\n",
      c->map_num, sizeof(struct icbmap),
      c->map_num * sizeof(struct icbmap));
    */
    if(tmp == NULL) {
      if(c->maps) free(c->maps);
      c->map_num = 0;
      return 0;
    }
    c->maps = tmp;
    c->maps[n] = *(struct icbmap *)data;
    c->maps[n].lbn = nr;
    break;
  default:
    return 0;
  }

  return 1;
}


/* For direct data access, LSB first */
#define GETN1(p) ((uint8_t)data[p])
#define GETN2(p) ((uint16_t)data[p] | ((uint16_t)data[(p) + 1] << 8))
322
#define GETN3(p) ((uint32_t)data[p] | ((uint32_t)data[(p) + 1] << 8)    \
323
                  | ((uint32_t)data[(p) + 2] << 16))
324 325 326
#define GETN4(p) ((uint32_t)data[p]                     \
                  | ((uint32_t)data[(p) + 1] << 8)      \
                  | ((uint32_t)data[(p) + 2] << 16)     \
327
                  | ((uint32_t)data[(p) + 3] << 24))
328 329 330
/* This is wrong with regard to endianess */
#define GETN(p, n, target) memcpy(target, &data[p], n)

331
static int Unicodedecode( uint8_t *data, int len, char *target )
332
{
333
  int p = 1, i = 0;
334
  int err = 0;
335

336
  if( ( data[ 0 ] == 8 ) || ( data[ 0 ] == 16 ) ) do {
337
    if( data[ 0 ] == 16 ) err |= data[p++];  /* character cannot be converted to 8bit, return error */
338 339 340 341
    if( p < len ) {
      target[ i++ ] = data[ p++ ];
    }
  } while( p < len );
342

343
  target[ i ] = '\0';
344
  return !err;
345 346
}

347
static int UDFDescriptor( uint8_t *data, uint16_t *TagID )
348
{
349 350 351
  *TagID = GETN2(0);
  /* TODO: check CRC 'n stuff */
  return 0;
352 353
}

354
static int UDFExtentAD( uint8_t *data, uint32_t *Length, uint32_t *Location )
355
{
356 357 358
  *Length   = GETN4(0);
  *Location = GETN4(4);
  return 0;
359 360
}

361
static int UDFShortAD( uint8_t *data, struct AD *ad,
362
                       struct Partition *partition )
363
{
364 365 366 367 368 369
  ad->Length = GETN4(0);
  ad->Flags = ad->Length >> 30;
  ad->Length &= 0x3FFFFFFF;
  ad->Location = GETN4(4);
  ad->Partition = partition->Number; /* use number of current partition */
  return 0;
370 371 372 373
}

static int UDFLongAD( uint8_t *data, struct AD *ad )
{
374 375 376 377 378 379 380
  ad->Length = GETN4(0);
  ad->Flags = ad->Length >> 30;
  ad->Length &= 0x3FFFFFFF;
  ad->Location = GETN4(4);
  ad->Partition = GETN2(8);
  /* GETN(10, 6, Use); */
  return 0;
381 382 383 384
}

static int UDFExtAD( uint8_t *data, struct AD *ad )
{
385 386 387 388 389 390 391
  ad->Length = GETN4(0);
  ad->Flags = ad->Length >> 30;
  ad->Length &= 0x3FFFFFFF;
  ad->Location = GETN4(12);
  ad->Partition = GETN2(16);
  /* GETN(10, 6, Use); */
  return 0;
392 393 394 395
}

static int UDFICB( uint8_t *data, uint8_t *FileType, uint16_t *Flags )
{
396 397 398
  *FileType = GETN1(11);
  *Flags = GETN2(18);
  return 0;
399 400 401 402
}


static int UDFPartition( uint8_t *data, uint16_t *Flags, uint16_t *Number,
403
                         char *Contents, uint32_t *Start, uint32_t *Length )
404
{
405 406 407 408 409 410
  *Flags = GETN2(20);
  *Number = GETN2(22);
  GETN(24, 32, Contents);
  *Start = GETN4(188);
  *Length = GETN4(192);
  return 0;
411 412 413 414 415 416 417 418
}

/**
 * Reads the volume descriptor and checks the parameters.  Returns 0 on OK, 1
 * on error.
 */
static int UDFLogVolume( uint8_t *data, char *VolumeDescriptor )
{
419
  uint32_t lbsize;
420 421
  Unicodedecode(&data[84], 128, VolumeDescriptor);
  lbsize = GETN4(212);  /* should be 2048 */
422 423 424 425 426
  /* MT_L = GETN4(264);  */  /* should be 6 */
  /* N_PM = GETN4(268);  */  /* should be 1 */
  if (lbsize != DVD_VIDEO_LB_LEN)
    return 1;

427
  return 0;
428 429
}

430
static int UDFFileEntry( uint8_t *data, uint8_t *FileType,
431
                         struct Partition *partition, struct AD *ad )
432
{
433 434 435 436 437 438 439 440 441 442 443 444 445 446
  uint16_t flags;
  uint32_t L_EA, L_AD;
  unsigned int p;

  UDFICB( &data[ 16 ], FileType, &flags );

  /* Init ad for an empty file (i.e. there isn't a AD, L_AD == 0 ) */
  ad->Length = GETN4( 60 ); /* Really 8 bytes a 56 */
  ad->Flags = 0;
  ad->Location = 0; /* what should we put here?  */
  ad->Partition = partition->Number; /* use number of current partition */

  L_EA = GETN4( 168 );
  L_AD = GETN4( 172 );
447 448 449 450

  if (176 + L_EA + L_AD > DVD_VIDEO_LB_LEN)
    return 0;

451 452 453
  p = 176 + L_EA;
  while( p < 176 + L_EA + L_AD ) {
    switch( flags & 0x0007 ) {
454 455 456 457 458 459 460 461 462 463 464 465
    case 0:
      UDFShortAD( &data[ p ], ad, partition );
      p += 8;
      break;
    case 1:
      UDFLongAD( &data[ p ], ad );
      p += 16;
      break;
    case 2:
      UDFExtAD( &data[ p ], ad );
      p += 20;
      break;
466 467
    case 3:
      switch( L_AD ) {
468 469 470 471 472 473 474 475 476
      case 8:
        UDFShortAD( &data[ p ], ad, partition );
        break;
      case 16:
        UDFLongAD( &data[ p ], ad );
        break;
      case 20:
        UDFExtAD( &data[ p ], ad );
        break;
477 478 479 480
      }
      p += L_AD;
      break;
    default:
481 482
      p += L_AD;
      break;
483
    }
484 485
  }
  return 0;
486 487 488
}

static int UDFFileIdentifier( uint8_t *data, uint8_t *FileCharacteristics,
489
                              char *FileName, struct AD *FileICB )
490
{
491 492 493 494 495 496 497
  uint8_t L_FI;
  uint16_t L_IU;

  *FileCharacteristics = GETN1(18);
  L_FI = GETN1(19);
  UDFLongAD(&data[20], FileICB);
  L_IU = GETN2(36);
498 499 500
  if (L_FI) {
    if (!Unicodedecode(&data[38 + L_IU], L_FI, FileName)) FileName[0] = 0;
  } else FileName[0] = '\0';
501
  return 4 * ((38 + L_FI + L_IU + 3) / 4);
502 503 504 505 506 507 508 509 510 511
}

/**
 * Maps ICB to FileAD
 * ICB: Location of ICB of directory to scan
 * FileType: Type of the file
 * File: Location of file the ICB is pointing to
 * return 1 on success, 0 on error;
 */
static int UDFMapICB( dvd_reader_t *device, struct AD ICB, uint8_t *FileType,
512
                      struct Partition *partition, struct AD *File )
513
{
514 515 516 517 518
  uint8_t LogBlock_base[DVD_VIDEO_LB_LEN + 2048];
  uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
  uint32_t lbnum;
  uint16_t TagID;
  struct icbmap tmpmap;
519
  int ret;
520

521 522 523 524 525 526 527
  lbnum = partition->Start + ICB.Location;
  tmpmap.lbn = lbnum;
  if(GetUDFCache(device, MapCache, lbnum, &tmpmap)) {
    *FileType = tmpmap.filetype;
    memcpy(File, &tmpmap.file, sizeof(tmpmap.file));
    return 1;
  }
528

529
  do {
530 531 532 533 534
    ret = DVDReadLBUDF( device, lbnum++, 1, LogBlock, 0 );
    if( ret < 0 ) {
      return ret;
    }
    else if( ret == 0 ) {
535
      TagID = 0;
536 537
    }
    else {
538
      UDFDescriptor( LogBlock, &TagID );
539
    }
540

541
    if( TagID == FileEntry ) {
542 543 544 545 546 547 548
      UDFFileEntry( LogBlock, FileType, partition, File );
      memcpy(&tmpmap.file, File, sizeof(tmpmap.file));
      tmpmap.filetype = *FileType;
      SetUDFCache(device, MapCache, tmpmap.lbn, &tmpmap);
      return 1;
    };
  } while( ( lbnum <= partition->Start + ICB.Location + ( ICB.Length - 1 )
549
             / DVD_VIDEO_LB_LEN ) && ( TagID != FileEntry ) );
550

551
  return 0;
552 553 554 555 556 557 558 559 560 561
}

/**
 * Dir: Location of directory to scan
 * FileName: Name of file to look for
 * FileICB: Location of ICB of the found file
 * return 1 on success, 0 on error;
 */
static int UDFScanDir( dvd_reader_t *device, struct AD Dir, char *FileName,
                       struct Partition *partition, struct AD *FileICB,
562
                       int cache_file_info)
563
{
564 565 566 567 568 569 570 571 572 573
  char filename[ MAX_UDF_FILE_NAME_LEN ];
  uint8_t directory_base[ 2 * DVD_VIDEO_LB_LEN + 2048];
  uint8_t *directory = (uint8_t *)(((uintptr_t)directory_base & ~((uintptr_t)2047)) + 2048);
  uint32_t lbnum;
  uint16_t TagID;
  uint8_t filechar;
  unsigned int p;
  uint8_t *cached_dir_base = NULL, *cached_dir;
  uint32_t dir_lba;
  struct AD tmpICB;
574
  int ret;
575 576 577 578 579

  /* Scan dir for ICB of file */
  lbnum = partition->Start + Dir.Location;

  if(DVDUDFCacheLevel(device, -1) > 0) {
580 581 582
    int found = 0;
    int in_cache = 0;

583 584 585 586 587
    /* caching */

    if(!GetUDFCache(device, LBUDFCache, lbnum, &cached_dir)) {
      dir_lba = (Dir.Length + DVD_VIDEO_LB_LEN) / DVD_VIDEO_LB_LEN;
      if((cached_dir_base = malloc(dir_lba * DVD_VIDEO_LB_LEN + 2048)) == NULL)
588
        return 0;
589
      cached_dir = (uint8_t *)(((uintptr_t)cached_dir_base & ~((uintptr_t)2047)) + 2048);
590 591
      ret = DVDReadLBUDF( device, lbnum, dir_lba, cached_dir, 0);
      if( ret <= 0 ) {
592 593 594
        free(cached_dir_base);
        cached_dir_base = NULL;
        cached_dir = NULL;
595 596
        if( ret < 0 )
            return ret;
597
      }
598 599 600 601 602 603 604 605 606 607 608 609 610
      /*
      if(cached_dir) {
        fprintf(stderr, "malloc dir: %d\n",  dir_lba * DVD_VIDEO_LB_LEN);
      }
      */
      {
        uint8_t *data[2];
        data[0] = cached_dir_base;
        data[1] = cached_dir;
        SetUDFCache(device, LBUDFCache, lbnum, data);
      }
    } else
      in_cache = 1;
611

612 613
    if(cached_dir == NULL) {
      free(cached_dir_base);
614
      return 0;
615
    }
616 617

    p = 0;
618

619
    while( p < Dir.Length ) {
620

621
      UDFDescriptor( &cached_dir[ p ], &TagID );
622
      if( TagID == FileIdentifierDescriptor ) {
623 624 625 626 627 628 629 630 631 632
        p += UDFFileIdentifier( &cached_dir[ p ], &filechar,
                                filename, &tmpICB );
        if(cache_file_info && !in_cache) {
          uint8_t tmpFiletype;
          struct AD tmpFile;

          if( !strcasecmp( FileName, filename ) ) {
            memcpy(FileICB, &tmpICB, sizeof(tmpICB));
            found = 1;
          }
633
          if(!UDFMapICB(device, tmpICB, &tmpFiletype, partition, &tmpFile))
Erik Hovland's avatar
Erik Hovland committed
634
            return 0;
635

636 637 638
        } else {
          if( !strcasecmp( FileName, filename ) ) {
            memcpy(FileICB, &tmpICB, sizeof(tmpICB));
639
            return 1;
640
          }
641
        }
642 643 644 645 646
      } else {
        if(cache_file_info && (!in_cache) && found)
          return 1;
        return 0;
      }
647
    }
648 649 650 651
    if(cache_file_info && (!in_cache) && found)
      return 1;
    return 0;
  }
652

653
  if( DVDReadLBUDF( device, lbnum, 2, directory, 0 ) <= 0 )
654
    return 0;
655 656 657 658 659 660 661 662 663 664 665 666

  p = 0;
  while( p < Dir.Length ) {
    if( p > DVD_VIDEO_LB_LEN ) {
      ++lbnum;
      p -= DVD_VIDEO_LB_LEN;
      Dir.Length -= DVD_VIDEO_LB_LEN;
      if( DVDReadLBUDF( device, lbnum, 2, directory, 0 ) <= 0 ) {
        return 0;
      }
    }
    UDFDescriptor( &directory[ p ], &TagID );
667
    if( TagID == FileIdentifierDescriptor ) {
668 669 670 671 672 673 674 675 676 677
      p += UDFFileIdentifier( &directory[ p ], &filechar,
                              filename, FileICB );
      if( !strcasecmp( FileName, filename ) ) {
        return 1;
      }
    } else
      return 0;
  }

  return 0;
678 679 680 681
}


static int UDFGetAVDP( dvd_reader_t *device,
682
                       struct avdp_t *avdp)
683 684 685 686 687 688 689
{
  uint8_t Anchor_base[ DVD_VIDEO_LB_LEN + 2048 ];
  uint8_t *Anchor = (uint8_t *)(((uintptr_t)Anchor_base & ~((uintptr_t)2047)) + 2048);
  uint32_t lbnum, MVDS_location, MVDS_length;
  uint16_t TagID;
  uint32_t lastsector;
  int terminate;
690
  struct avdp_t;
691
  int ret;
692 693 694 695 696 697 698 699 700 701

  if(GetUDFCache(device, AVDPCache, 0, avdp))
    return 1;

  /* Find Anchor */
  lastsector = 0;
  lbnum = 256;   /* Try #1, prime anchor */
  terminate = 0;

  for(;;) {
702 703 704 705 706
    ret = DVDReadLBUDF( device, lbnum, 1, Anchor, 0 );
    if( ret < 0 ) {
      return ret;
    }
    else if( ret == 0 ) {
707 708
      TagID = 0;
    }
709 710 711
    else {
      UDFDescriptor( Anchor, &TagID );
    }
712
    if (TagID != AnchorVolumeDescriptorPointer) {
713 714 715 716
      /* Not an anchor */
      if( terminate ) return 0; /* Final try failed */

      if( lastsector ) {
717
        /* We already found the last sector.  Try #3, alternative
718
         * backup anchor.  If that fails, don't try again.
719
         */
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        lbnum = lastsector;
        terminate = 1;
      } else {
        /* TODO: Find last sector of the disc (this is optional). */
        if( lastsector )
          /* Try #2, backup anchor */
          lbnum = lastsector - 256;
        else
          /* Unable to find last sector */
          return 0;
      }
    } else
      /* It's an anchor! We can leave */
      break;
  }
  /* Main volume descriptor */
  UDFExtentAD( &Anchor[ 16 ], &MVDS_length, &MVDS_location );
  avdp->mvds.location = MVDS_location;
  avdp->mvds.length = MVDS_length;

  /* Backup volume descriptor */
  UDFExtentAD( &Anchor[ 24 ], &MVDS_length, &MVDS_location );
  avdp->rvds.location = MVDS_location;
  avdp->rvds.length = MVDS_length;

  SetUDFCache(device, AVDPCache, 0, avdp);

  return 1;
}

/**
 * Looks for partition on the disc.  Returns 1 if partition found, 0 on error.
 *   partnum: Number of the partition, starting at 0.
 *   part: structure to fill with the partition information
 */
static int UDFFindPartition( dvd_reader_t *device, int partnum,
756
                             struct Partition *part )
757
{
758 759 760 761
  uint8_t LogBlock_base[ DVD_VIDEO_LB_LEN + 2048 ];
  uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
  uint32_t lbnum, MVDS_location, MVDS_length;
  uint16_t TagID;
762
  int i, volvalid, ret;
763
  struct avdp_t avdp;
764

765 766
  if(!UDFGetAVDP(device, &avdp))
    return 0;
767

768 769 770 771 772 773 774 775 776 777 778
  /* Main volume descriptor */
  MVDS_location = avdp.mvds.location;
  MVDS_length = avdp.mvds.length;

  part->valid = 0;
  volvalid = 0;
  part->VolumeDesc[ 0 ] = '\0';
  i = 1;
  do {
    /* Find Volume Descriptor */
    lbnum = MVDS_location;
779 780
    do {

781 782 783 784 785
      ret = DVDReadLBUDF( device, lbnum++, 1, LogBlock, 0 );
      if( ret < 0 ) {
        return ret;
      }
      else if( ret == 0 ) {
786
        TagID = 0;
787 788
      }
      else {
789
        UDFDescriptor( LogBlock, &TagID );
790
      }
791

792
      if( ( TagID == PartitionDescriptor ) && ( !part->valid ) ) {
793 794 795 796
        /* Partition Descriptor */
        UDFPartition( LogBlock, &part->Flags, &part->Number,
                      part->Contents, &part->Start, &part->Length );
        part->valid = ( partnum == part->Number );
797
      } else if( ( TagID == LogicalVolumeDescriptor ) && ( !volvalid ) ) {
798 799 800 801 802 803 804 805
        /* Logical Volume Descriptor */
        if( UDFLogVolume( LogBlock, part->VolumeDesc ) ) {
          /* TODO: sector size wrong! */
        } else
          volvalid = 1;
      }

    } while( ( lbnum <= MVDS_location + ( MVDS_length - 1 )
806
               / DVD_VIDEO_LB_LEN ) && ( TagID != TerminatingDescriptor )
807 808 809 810 811 812 813 814 815 816 817
             && ( ( !part->valid ) || ( !volvalid ) ) );

    if( ( !part->valid) || ( !volvalid ) ) {
      /* Backup volume descriptor */
      MVDS_location = avdp.mvds.location;
      MVDS_length = avdp.mvds.length;
    }
  } while( i-- && ( ( !part->valid ) || ( !volvalid ) ) );

  /* We only care for the partition, not the volume */
  return part->valid;
818 819
}

Petri Hintukainen's avatar
Petri Hintukainen committed
820
uint32_t UDFFindFile( dvd_reader_t *device, const char *filename,
821
                      uint32_t *filesize )
822
{
823 824 825 826 827 828 829 830
  uint8_t LogBlock_base[ DVD_VIDEO_LB_LEN + 2048 ];
  uint8_t *LogBlock = (uint8_t *)(((uintptr_t)LogBlock_base & ~((uintptr_t)2047)) + 2048);
  uint32_t lbnum;
  uint16_t TagID;
  struct Partition partition;
  struct AD RootICB, File, ICB;
  char tokenline[ MAX_UDF_FILE_NAME_LEN ];
  uint8_t filetype;
831
  int ret;
832 833 834 835 836

  *filesize = 0;
  tokenline[0] = '\0';
  strncat(tokenline, filename, MAX_UDF_FILE_NAME_LEN - 1);
  memset(&ICB, 0, sizeof(ICB));
837

838 839 840 841 842 843 844 845 846
  if(!(GetUDFCache(device, PartitionCache, 0, &partition) &&
       GetUDFCache(device, RootICBCache, 0, &RootICB))) {
    /* Find partition, 0 is the standard location for DVD Video.*/
    if( !UDFFindPartition( device, 0, &partition ) ) return 0;
    SetUDFCache(device, PartitionCache, 0, &partition);

    /* Find root dir ICB */
    lbnum = partition.Start;
    do {
847 848 849 850 851
      ret = DVDReadLBUDF( device, lbnum++, 1, LogBlock, 0 );
      if( ret < 0 ) {
        return ret;
      }
      else if( ret == 0 ) {
852
        TagID = 0;
853 854
      }
      else {
855
        UDFDescriptor( LogBlock, &TagID );
856
      }
857 858

      /* File Set Descriptor */
859
      if( TagID == FileSetDescriptor )  /* File Set Descriptor */
860
        UDFLongAD( &LogBlock[ 400 ], &RootICB );
861
    } while( ( lbnum < partition.Start + partition.Length )
862
             && ( TagID != TerminatingDescriptor ) && ( TagID != FileSetDescriptor) );
863 864

    /* Sanity checks. */
865
    if( TagID != FileSetDescriptor )
866 867 868
      return 0;
    if( RootICB.Partition != 0 )
      return 0;
869
    SetUDFCache(device, RootICBCache, 0, &RootICB);
870
  }
871

872 873 874 875 876 877 878 879
  /* Find root dir */
  if( !UDFMapICB( device, RootICB, &filetype, &partition, &File ) )
    return 0;
  if( filetype != 4 )
    return 0;  /* Root dir should be dir */
  {
    int cache_file_info = 0;
    /* Tokenize filepath */
880
    char *token = strtok(tokenline, "/");
881 882 883 884 885 886 887 888 889 890

    while( token != NULL ) {
      if( !UDFScanDir( device, File, token, &partition, &ICB,
                       cache_file_info))
        return 0;
      if( !UDFMapICB( device, ICB, &filetype, &partition, &File ) )
        return 0;
      if(!strcmp(token, "VIDEO_TS"))
        cache_file_info = 1;
      token = strtok( NULL, "/" );
891
    }
892
  }
893

894 895 896 897 898 899 900 901 902
  /* Sanity check. */
  if( File.Partition != 0 )
    return 0;
  *filesize = File.Length;
  /* Hack to not return partition.Start for empty files. */
  if( !File.Location )
    return 0;
  else
    return partition.Start + File.Location;
903 904 905 906 907 908 909 910 911 912 913
}



/**
 * Gets a Descriptor .
 * Returns 1 if descriptor found, 0 on error.
 * id, tagid of descriptor
 * bufsize, size of BlockBuf (must be >= DVD_VIDEO_LB_LEN).
 */
static int UDFGetDescriptor( dvd_reader_t *device, int id,
914
                             uint8_t *descriptor, int bufsize)
915 916 917 918
{
  uint32_t lbnum, MVDS_location, MVDS_length;
  struct avdp_t avdp;
  uint16_t TagID;
919
  int i, desc_found = 0, ret;
920 921 922 923 924 925 926 927 928 929 930
  /* Find Anchor */
  lbnum = 256;   /* Try #1, prime anchor */
  if(bufsize < DVD_VIDEO_LB_LEN)
    return 0;

  if(!UDFGetAVDP(device, &avdp))
    return 0;

  /* Main volume descriptor */
  MVDS_location = avdp.mvds.location;
  MVDS_length = avdp.mvds.length;
931

932 933 934 935 936
  i = 1;
  do {
    /* Find  Descriptor */
    lbnum = MVDS_location;
    do {
937 938 939 940 941
      ret = DVDReadLBUDF( device, lbnum++, 1, descriptor, 0 );
      if( ret < 0 ) {
        return ret;
      }
      else if( ret == 0 ) {
942
        TagID = 0;
943 944
      }
      else {
945
        UDFDescriptor( descriptor, &TagID );
946
      }
947 948 949 950
      if( (TagID == id) && ( !desc_found ) )
        /* Descriptor */
        desc_found = 1;
    } while( ( lbnum <= MVDS_location + ( MVDS_length - 1 )
951
               / DVD_VIDEO_LB_LEN ) && ( TagID != TerminatingDescriptor )
952
             && ( !desc_found) );
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

    if( !desc_found ) {
      /* Backup volume descriptor */
      MVDS_location = avdp.rvds.location;
      MVDS_length = avdp.rvds.length;
    }
  } while( i-- && ( !desc_found )  );

  return desc_found;
}


static int UDFGetPVD(dvd_reader_t *device, struct pvd_t *pvd)
{
  uint8_t pvd_buf_base[DVD_VIDEO_LB_LEN + 2048];
  uint8_t *pvd_buf = (uint8_t *)(((uintptr_t)pvd_buf_base & ~((uintptr_t)2047)) + 2048);
  if(GetUDFCache(device, PVDCache, 0, pvd))
    return 1;

972
  if(!UDFGetDescriptor( device, 1, pvd_buf, DVD_VIDEO_LB_LEN))
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    return 0;

  memcpy(pvd->VolumeIdentifier, &pvd_buf[24], 32);
  memcpy(pvd->VolumeSetIdentifier, &pvd_buf[72], 128);
  SetUDFCache(device, PVDCache, 0, pvd);
  return 1;
}

/**
 * Gets the Volume Identifier string, in 8bit unicode (latin-1)
 * volid, place to put the string
 * volid_size, size of the buffer volid points to
 * returns the size of buffer needed for all data
 */
int UDFGetVolumeIdentifier(dvd_reader_t *device, char *volid,
988
                           unsigned int volid_size)
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
{
  struct pvd_t pvd;
  unsigned int volid_len;

  /* get primary volume descriptor */
  if(!UDFGetPVD(device, &pvd))
    return 0;

  volid_len = pvd.VolumeIdentifier[31];
  if(volid_len > 31)
    /* this field is only 32 bytes something is wrong */
    volid_len = 31;
  if(volid_size > volid_len)
    volid_size = volid_len;
  Unicodedecode(pvd.VolumeIdentifier, volid_size, volid);
1004

1005 1006 1007 1008 1009 1010 1011
  return volid_len;
}

/**
 * Gets the Volume Set Identifier, as a 128-byte dstring (not decoded)
 * WARNING This is not a null terminated string
 * volsetid, place to put the data
1012
 * volsetid_size, size of the buffer volsetid points to
1013 1014 1015 1016 1017
 * the buffer should be >=128 bytes to store the whole volumesetidentifier
 * returns the size of the available volsetid information (128)
 * or 0 on error
 */
int UDFGetVolumeSetIdentifier(dvd_reader_t *device, uint8_t *volsetid,
1018
                              unsigned int volsetid_size)
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
{
  struct pvd_t pvd;

  /* get primary volume descriptor */
  if(!UDFGetPVD(device, &pvd))
    return 0;


  if(volsetid_size > 128)
    volsetid_size = 128;

  memcpy(volsetid, pvd.VolumeSetIdentifier, volsetid_size);
1031

1032 1033
  return 128;
}