1"""
2@copyright: 2009 Bastian Blank <waldi@debian.org>
3@license: GNU GPL-3
4"""
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 3 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17import os
18import stat
19
20from .volume import VmgUdf, VtsUdf
21
22
23class Media(object):
24    pass
25
26
27class MediaUdf(Media):
28    class File(object):
29        def __init__(self, filename):
30            f = open(filename, 'rb')
31            self.close = f.close
32            self.read = f.read
33            self.seek = f.seek
34            self.tell = f.tell
35
36        def read_sector(self, count, **kw):
37            return self.read(count * 2048)
38
39        def seek_sector(self, offset, **kw):
40            self.seek(offset * 2048)
41
42        def tell_sector(self):
43            return self.tell() // 2048
44
45    def __init__(self, filename):
46        from .udf.media import Media
47        try:
48            from .libdvdcss import DvdCssFile
49        except ImportError:
50            DvdCssFile = self.File
51
52        s = os.stat(filename)
53        if stat.S_ISREG(s.st_mode):
54            f = self.File(filename)
55        elif stat.S_ISBLK(s.st_mode) or stat.S_ISCHR(s.st_mode):
56            f = DvdCssFile(filename)
57        else:
58            raise RuntimeError
59
60        self.read = f.read_sector
61        self.seek = f.seek_sector
62        self.tell = f.tell_sector
63
64        self._file = f
65        self.udf = Media(f)
66        self.video_dir = self.udf.volume.partitions[0].fileset.root.tree['VIDEO_TS'].entry.tree
67
68    def __getitem__(self, name):
69        f = self.get(name)
70        if not f:
71            raise KeyError(name)
72        return f
73
74    def get(self, name, default=None):
75        f = self.video_dir.get(name)
76        if not f:
77            return default
78        if len(f.entry.ad) > 1:
79            raise NotImplementedError
80        return f
81
82    def vmg(self):
83        return VmgUdf(self)
84
85    def vts(self, titleset):
86        return VtsUdf(self, titleset)
87