m-hiki / isobmff

The isobmff is a python library for reading/writing ISO base media file format.
MIT License
4 stars 2 forks source link

Implementation the Box with the closure #5

Open m-hiki opened 7 years ago

m-hiki commented 7 years ago

In the specification document, the box of ISO BMFF is represented as object. Then the object oriented design might be matched for it. However the box is essentially stream. Fields in the box is needed to be keeped in a decided order. There is also a problem of an inner class in python can't refer outer class's definitions. More optimal and effective representations are required for the Box to implement with the Python. Therefore, the Box implementation using the generator is proposed for solving this problem.

m-hiki commented 7 years ago

prototype


# -*- coding: utf-8 -*-
from functools import wraps

class Field:
    def __init__(self, size):
        self.size = size // 8
        self.value = None

    def read(self, file):
        pass

    def write(self, file):
        pass

class Int(Field):
    def read(self, file):
        print('read int')

class String(Field):
    def read(self, file):
        print('read string')

def defbox(extend):
    def _defbox(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if extend:
                for gen in extend:
                    yield gen
            for gen in func(*args, **kwargs):
                yield gen
        return wrapper
    return _defbox

@defbox(extend=None)
def box(boxtype):
    size = Int(32)
    typ = String(32)
    yield size
    yield typ

@defbox(extend=box(None))
def full_box():
    version = Int(8)
    flags = Int(24)
    yield version
    yield flags

@defbox(extend=box('ftyp'))
def file_type_box():
    major_brand = Int(32)
    minor_version = Int(32)
    compatible_brands = Int(32)
    yield major_brand
    yield minor_version
    yield compatible_brands

@defbox(extend=box('moov'))
def movie_box():
    pass

if __name__ == '__main__':
    for field in full_box():
        field.read('hoge')
m-hiki commented 7 years ago

関数は状態をもたない。そのため、クロージャでなんとかしないと読み出してもオブジェクトは消える。

m-hiki commented 7 years ago

ランダムアクセスができないのでこのアイデアはボツ。