Class: CHD

Inherits:
Object
  • Object
show all
Defined in:
ext/chd.c,
lib/chd.rb,
lib/chd/cd.rb,
lib/chd/version.rb,
lib/chd/metadata.rb,
ext/chd.c

Overview

Accessing CHD MAME file.

Defined Under Namespace

Modules: Metadata Classes: CD, DataError, Error, IOError, NotFoundError, NotSupportedError, NotWritableError, ParentInvalidError, ParentRequiredError, ParsingError, UnsupportedError

Constant Summary collapse

VERSION =

Current version of this gem/library

'0.1.1'
RDONLY =

Read-only mode for opening CHD file.

1
RDWR =

Read-write mode for opening CHD file.

2
METADATA_FLAG_CHECKSUM =

Indicates that data is checksumed

0x01

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, mode = RDONLY, parent: nil) ⇒ CHD

Note:

Only the read-only mode (RDONLY) is currently supported.

Create a new access to a CHD file.

Parameters:

  • file (String, IO)

    path-string or open IO on the CHD file

  • mode (Integer) (defaults to: RDONLY)

    opening mode (RDONLY or RDWR)

  • parent (String, IO) (defaults to: nil)

    path-string or open IO on the CHD parent file.



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'ext/chd.c', line 451

static VALUE
chd_m_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE file, mode, opts;
    ID    kwargs_id[1] = { id_parent };
    VALUE kwargs   [1];
    
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);

    // Sanity check
    if (chd->flags & CHD_RB_DATA_INITIALIZED) {
	rb_warn("%"PRIsVALUE" refusing to initialize same instance twice",
		rb_obj_as_string(cCHD));
	return Qnil;
    }

    // Retrieve arguments
    rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "11:",
		    &file, &mode, &opts);
    rb_get_kwargs(opts, kwargs_id, 0, 2, kwargs);

    // If mode not specified, default to read-only
    if (NIL_P(mode)) {
	mode = INT2FIX(CHD_OPEN_READ);
    }
    
    // If given retrieve parent chd file
    chd_file *parent = NULL;
    if ((kwargs[0] != Qundef) && (kwargs[0] != Qnil)) {
	if (! RTEST(rb_obj_is_kind_of(kwargs[0], cCHD))) {
	    rb_raise(rb_eArgError, "parent must be a kind of %"PRIsVALUE,
		     rb_obj_as_string(cCHD));
	}
	struct chd_rb_data *chd_parent;
	chd_rb_get_typeddata(chd_parent, self);
	parent = chd_parent->file;
    }

    // Open CHD
    chd_error err = CHDERR_NONE;
    if (RTEST(rb_obj_is_kind_of(file, rb_cIO))) {
        rb_io_t *fptr;
        GetOpenFile(file, fptr);

	err = chd_open_file(rb_io_stdio_file(fptr),
			    FIX2INT(mode), parent, &chd->file);
    } else {
	err = chd_open(StringValueCStr(file),
		       FIX2INT(mode), parent, &chd->file);
    }
    chd_rb_raise_if_error(err);    

    // Retrieve header and hunkbytes
    chd->header         = chd_get_header(chd->file);
    chd->units_per_hunk = chd->header->hunkbytes / chd->header->unitbytes;
    if (chd->header->hunkbytes % chd->header->unitbytes) {
	chd_close(chd->file);
	rb_raise(eCHDDataError, "CHD hunk is not a multiple of unit");
    }

    // Allocate cache
    chd->cached_hunk    = malloc(chd->header->hunkbytes);
    chd->cached_hunkidx = -1;
    if (chd->cached_hunk == NULL) {
	chd_close(chd->file);
	rb_raise(rb_eNoMemError, "out of memory (hunk cache)");
    }
    
    // Mark as initialized and opened
    chd->flags = CHD_RB_DATA_INITIALIZED | CHD_RB_DATA_OPENED;
    
    return Qnil;
}

Class Method Details

.header(filename) ⇒ Hash{Symbol => Object}

Retrieve the header from a CHD file.

For a detailed description of the header, see #header.

Parameters:

  • filename (String)

    path to CHD file

Returns:

  • (Hash{Symbol => Object})


426
427
428
429
430
431
432
433
434
435
436
# File 'ext/chd.c', line 426

static VALUE
chd_s_header(VALUE klass, VALUE filename)
{
    chd_header header;
    chd_error  err;

    err = chd_read_header(StringValueCStr(filename), &header);
    chd_rb_raise_if_error(err);    

    return chd_rb_header(&header);
}

.msf(frames) ⇒ String

Returns a string representation of the number of frames using minutes:seconds:frames format.

Parameters:

  • frames (Integer)

Returns:

  • (String)


15
16
17
# File 'lib/chd.rb', line 15

def self.msf(frames)
    "%02d:%02d:%02d" % [ frames / (75 * 60), (frames / 75) % 60, frames % 75 ]
end

.initialize(file, mode = RDONLY, parent: nil) ⇒ CHD

Note:

Only the read-only mode (RDONLY) is currently supported.

Create a new access to a CHD file.

Parameters:

  • file (String, IO)

    path-string or open IO on the CHD file

  • mode (Integer) (defaults to: RDONLY)

    opening mode (RDONLY or RDWR)

  • parent (String, IO) (defaults to: nil)

    path-string or open IO on the CHD parent file.

Returns:



373
374
375
376
377
# File 'ext/chd.c', line 373

static VALUE
chd_s_new(int argc, VALUE *argv, VALUE klass)
{
    return rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);
}

.open(file, mode = RDONLY, parent: nil) ⇒ Object

Note:

Only the read-only mode (RDONLY) is currently supported.

Open a CHD file.

With no associated block open is synonym for new. If the optional code block is given, it will be passed the opened CHD file as an argument and the CHD object will automatically be closed when the block terminates. The value of the block will be returned.

Examples:

CHD.open('file.chd') do |chd|
  puts chd.
end

Parameters:

  • file (String, IO)

    path-string or open IO on the CHD file

  • mode (Integer) (defaults to: RDONLY)

    opening mode (RDONLY or RDWR)

  • parent (String, IO) (defaults to: nil)

    path-string or open IO on the CHD parent file.

Yields:

  • (chd)

    the opened CHD file



402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'ext/chd.c', line 402

static VALUE
chd_s_open(int argc, VALUE *argv, VALUE klass)
{
    VALUE chd;

    chd = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, chd, chd_m_close, chd);
    }

    return chd;
}

Instance Method Details

#closenil

Note:

Once closed, further operation on this object will result in an Error exception, except for #close that will be a no-op.

Close the file.

Returns:

  • (nil)


857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'ext/chd.c', line 857

static VALUE
chd_m_close(VALUE self) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
	
    // If opened
    if (chd->flags & CHD_RB_DATA_OPENED) {
	chd_close(chd->file);
	chd->file         = NULL;
	chd->header       = NULL;
	chd->value.header = Qnil;
	chd->flags       &= ~(CHD_RB_DATA_OPENED | CHD_RB_DATA_PRECACHED);
    }
    
    return Qnil;
}

#closed?Boolean

Is the file closed?

Returns:

  • (Boolean)


880
881
882
883
884
885
886
887
888
# File 'ext/chd.c', line 880

static VALUE
chd_m_closed_p(VALUE self) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);

    return (chd->flags & CHD_RB_DATA_OPENED) ? Qfalse : Qtrue;
}

#get_metadata(index = 0, tag = nil) ⇒ Array(String, Integer, Symbol)?

Retrieve a single metadata.

If specified the metadata tag is a 4-character symbol, some commonly used are `:GDDD`, `:IDNT`, `:'KEY '`, `:'CIS '`, `:CHTR`, `:CHT2`, `:CHGD`, `:AVAV`, `:AVLD`. Note the use of single-quote to include a white-space in some of the tag.

Parameters:

  • index (Integer) (defaults to: 0)

    index from which to lookup for metadata

  • tag (Symbol, nil) (defaults to: nil)

    tag of the metadata to lookup (using nil as a wildcard)

Returns:

  • (Array(String, Integer, Symbol))
  • (nil)

    if do metadata found



612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'ext/chd.c', line 612

static VALUE
chd_m_get_metadata(int argc, VALUE *argv, VALUE self)
{
    VALUE tag, index;

    // Retrieve arguments
    rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "02",
		    &index, &tag);

    if (! NIL_P(index)) {
	rb_check_type(index, T_FIXNUM);	
    }
    
    if (! NIL_P(tag)) {
	rb_warn("%"PRIsVALUE" refusing to initialize same instance twice",
		rb_obj_as_string(tag));
	rb_check_type(tag, T_SYMBOL);
	tag = rb_sym2str(tag);
	if (RSTRING_LEN(tag) != 4) {
	    rb_raise(rb_eArgError, "tag must be a 4-char symbol");
	}
    }

    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);

    // Perform query
    char     buffer[CHD_METATADATA_BUFFER_MAXSIZE] = { 0 };
    uint32_t buflen                                = sizeof(buffer);
    uint32_t resultlen                             = 0;
    uint32_t resulttag                             = 0;
    uint8_t  resultflags                           = 0;    
    uint32_t searchindex                           = 0;
    uint32_t searchtag                             = CHDMETATAG_WILDCARD;

    if (! NIL_P(index)) {
	searchindex = FIX2INT(index);
    }

    if (! NIL_P(tag)) {
	char *tag_str       = RSTRING_PTR(tag);
	char *searchtag_str = (char *)&searchtag;
	searchtag_str[0] = tag_str[3];
	searchtag_str[1] = tag_str[2];
	searchtag_str[2] = tag_str[1];
	searchtag_str[3] = tag_str[0];
    }
    
    chd_error err;
    err = chd_get_metadata(chd->file,
			   searchtag, searchindex,
			   buffer, buflen,
			   &resultlen, &resulttag, &resultflags);

    // return nil on not found, otherwise raise exception
    if (err == CHDERR_METADATA_NOT_FOUND)
	return Qnil;
    chd_rb_raise_if_error(err);    

    // Sanity check on buffer length
    if (resultlen > buflen) {
	rb_bug("decoding metadata buffer size (%d) is too small (got: %d)",
	       (int)sizeof(buffer), resultlen);
    }

    // Assume it's ascii 8-bit text encoded, remove last null-char
    if ((resultlen > 0) &&
	(buffer[resultlen-1] == '\0') &&
	(strchr(buffer, '\0') == &buffer[resultlen-1])) {
	resultlen -= 1;
    }

    // Returns result
    char str[sizeof(uint32_t)];
    rb_integer_pack(ULONG2NUM(resulttag), str, 1, sizeof(uint32_t), 0,
		    INTEGER_PACK_BIG_ENDIAN);

    VALUE res[] = { rb_str_new(buffer, resultlen),
	            INT2FIX(resultflags),
		    rb_to_symbol(rb_str_new(str, sizeof(str)))
                  };
    
    return rb_ary_new_from_values(ARRAY_SIZE(res), res);
}

#headerHash{Symbol => Object}

Return the CHD header.

The header contains information about:

* version
*  compression used
*  digest (sha1 or md5) for the file and the parent
* hunk and unit (size and count)

Returns:

  • (Hash{Symbol => Object})


580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'ext/chd.c', line 580

static VALUE
chd_m_header(VALUE self) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);
    
    if (NIL_P(chd->value.header)) {
	chd->value.header = rb_obj_freeze(chd_rb_header(chd->header));
    }

    return chd->value.header;
}

#hunk_bytesInteger

Number of bytes in a hunk.

Returns:

  • (Integer)


906
907
908
909
# File 'ext/chd.c', line 906

static VALUE
chd_m_hunk_bytes(VALUE self) {
    return rb_hash_lookup(chd_m_header(self), ID2SYM(id_hunk_bytes));
}

#hunk_countInteger

Number of hunks.

Returns:

  • (Integer)


916
917
918
919
# File 'ext/chd.c', line 916

static VALUE
chd_m_hunk_count(VALUE self) {
    return rb_hash_lookup(chd_m_header(self), ID2SYM(id_hunk_count));
}

#metadataArray<Array(String, Integer, Symbol)>

Retrieve all the metadata.

Returns:

  • (Array<Array(String, Integer, Symbol)>)


706
707
708
709
710
711
712
713
714
715
716
717
# File 'ext/chd.c', line 706

static VALUE
chd_m_metadata(VALUE self) {
    VALUE list = rb_ary_new();
    
    for (int i = 0 ; ; i++) {
	VALUE md  = chd_m_get_metadata(1, (VALUE []) { INT2FIX(i) }, self);
	if (NIL_P(md))
	    break;
	rb_ary_push(list, md);
    }
    return list;
}

#precacheself

Note:
  • It is not necessary to enable pre-cache just to improved consecutive partial-read as the current hunk is always cached.

  • Once enabled, there is no way to remove the cache.

Pre-cache the whole CHD in memory.

Returns:

  • (self)


538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'ext/chd.c', line 538

static VALUE
chd_m_precache(VALUE self) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);

    chd_error err = chd_precache(chd->file);
    chd_rb_raise_if_error(err);
    chd->flags |= CHD_RB_DATA_PRECACHED;

    return self;
}

#precached?Boolean

Has the CHD been pre-cached?

Returns:

  • (Boolean)


557
558
559
560
561
562
563
564
565
566
# File 'ext/chd.c', line 557

static VALUE
chd_m_precached_p(VALUE self) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);

    return (chd->flags & CHD_RB_DATA_PRECACHED) ? Qtrue : Qfalse;
}

#read_bytes(offset, size) ⇒ String

Read bytes of data.

Parameters:

  • offset (Integer)

    offset from which reading bytes start

  • size (Integer)

    number of bytes to read

Returns:

  • (String)

Raises:

  • (IOError)

    if the requested data is not available



797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# File 'ext/chd.c', line 797

static VALUE
chd_m_read_bytes(VALUE self, VALUE offset, VALUE size) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);
    
    const uint32_t  _offset       = VALUE_TO_UINT32(offset);
    const uint32_t  _size         = VALUE_TO_UINT32(size);
    const uint32_t  hunkbytes     = chd->header->hunkbytes;
    const uint32_t  hunkidx_first = _offset               / hunkbytes;
    const uint32_t  hunkidx_last  = (_offset + _size - 1) / hunkbytes;
    const VALUE     strdata       = rb_str_buf_new(_size);
          char     *buffer        = RSTRING_PTR(strdata);

    for (uint32_t hunkidx = hunkidx_first; hunkidx <= hunkidx_last; hunkidx++) {
	uint32_t startoffs = (hunkidx == hunkidx_first)
	                   ? (_offset % hunkbytes)
	                   : 0;
	uint32_t endoffs   = (hunkidx == hunkidx_last)
	                   ? ((_offset + _size - 1) % hunkbytes)
	                   : (hunkbytes - 1);
	size_t   chunksize = endoffs + 1 - startoffs;
	
	// if it's a full block, just read directly from disk
	// (unless it's the cached hunk)
	if ((startoffs == 0                   ) &&
	    (endoffs   == (hunkbytes - 1)     ) &&
	    (hunkidx   != chd->cached_hunkidx)) {
	    chd_error err = chd_read(chd->file, hunkidx, buffer);
	    chd_rb_raise_if_error(err);
	}
	// otherwise, read from the cache
	// (and fill the cache if necessary)
	else {
	    if (hunkidx != chd->cached_hunkidx) {
		chd_error err = chd_read(chd->file, hunkidx, chd->cached_hunk);
		chd->cached_hunkidx = (err == CHDERR_NONE) ? hunkidx : -1;
		chd_rb_raise_if_error(err);
	    }
	    memcpy(buffer, &chd->cached_hunk[startoffs], chunksize);
	}
	
	buffer += chunksize;
    }

    rb_str_set_len(strdata, _size);
    return strdata;
}

#read_hunk(idx) ⇒ String

Read a CHD hunk.

Parameters:

  • idx (Integer)

    hunk index (start at 0)

Returns:

  • (String)

Raises:

  • (RangeError)

    if the requested hunk doesn't exists



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'ext/chd.c', line 729

static VALUE
chd_m_read_hunk(VALUE self, VALUE idx) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);

    uint32_t hunkidx = VALUE_TO_UINT32(idx);
    if ((hunkidx < 0) || (hunkidx >= chd->header->totalhunks)) {
	rb_raise(rb_eRangeError, "hunk index (%d) is out of range (%d..%d)",
		 hunkidx, 0, chd->header->totalhunks - 1);
    }

    VALUE strdata = rb_str_buf_new(chd->header->hunkbytes);
    char *buffer  = RSTRING_PTR(strdata);
    
    chd_error err = chd_read(chd->file, hunkidx, buffer);
    chd_rb_raise_if_error(err);

    rb_str_set_len(strdata, chd->header->hunkbytes);
    return strdata;
}

#read_unit(idx) ⇒ String

Read a CHD unit.

Parameters:

  • idx (Integer)

    unit index (start at 0)

Returns:

  • (String)

Raises:

  • (RangeError)

    if the requested unit doesn't exists



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'ext/chd.c', line 763

static VALUE
chd_m_read_unit(VALUE self, VALUE idx) {
    // Retrieve typed data
    struct chd_rb_data *chd;
    chd_rb_get_typeddata(chd, self);
    chd_rb_ensure_initialized(chd);
    chd_rb_ensure_opened(chd);

    const uint32_t hunkbytes  = chd->header->hunkbytes;
    const uint32_t unitbytes  = chd->header->unitbytes;
    const uint32_t unitidx    = VALUE_TO_UINT32(idx);
    const uint32_t hunkidx    = unitidx / chd->units_per_hunk;
    const size_t   offset     = (unitidx % chd->units_per_hunk) * unitbytes;
	  
    if (hunkidx != chd->cached_hunkidx) {
	chd_error err = chd_read(chd->file, hunkidx, chd->cached_hunk);
	chd->cached_hunkidx = (err == CHDERR_NONE) ? hunkidx : -1;
	chd_rb_raise_if_error(err);
    }

    return rb_str_new((char *) &chd->cached_hunk[offset], unitbytes);
}

#unit_bytesInteger

Number of bytes in a unit

Returns:

  • (Integer)


926
927
928
929
# File 'ext/chd.c', line 926

static VALUE
chd_m_unit_bytes(VALUE self) {
    return rb_hash_lookup(chd_m_header(self), ID2SYM(id_unit_bytes));
}

#unit_countInteger

Number of units.

Returns:

  • (Integer)


936
937
938
939
# File 'ext/chd.c', line 936

static VALUE
chd_m_unit_count(VALUE self) {
    return rb_hash_lookup(chd_m_header(self), ID2SYM(id_unit_count));
}

#versionString

Returns version number.

Returns:

  • (String)


896
897
898
899
# File 'ext/chd.c', line 896

static VALUE
chd_m_version(VALUE self) {
    return rb_hash_lookup(chd_m_header(self), ID2SYM(id_version));
}