]> granicus.if.org Git - libvpx/blob - third_party/libwebm/mkvparser/mkvreader.cc
third_party: Roll libwebm snapshot.
[libvpx] / third_party / libwebm / mkvparser / mkvreader.cc
1 // Copyright (c) 2010 The WebM project authors. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the LICENSE file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS.  All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 #include "mkvparser/mkvreader.h"
9
10 #include <cassert>
11
12 namespace mkvparser {
13
14 MkvReader::MkvReader() : m_file(NULL), reader_owns_file_(true) {}
15
16 MkvReader::MkvReader(FILE* fp) : m_file(fp), reader_owns_file_(false) {
17   GetFileSize();
18 }
19
20 MkvReader::~MkvReader() {
21   if (reader_owns_file_)
22     Close();
23   m_file = NULL;
24 }
25
26 int MkvReader::Open(const char* fileName) {
27   if (fileName == NULL)
28     return -1;
29
30   if (m_file)
31     return -1;
32
33 #ifdef _MSC_VER
34   const errno_t e = fopen_s(&m_file, fileName, "rb");
35
36   if (e)
37     return -1;  // error
38 #else
39   m_file = fopen(fileName, "rb");
40
41   if (m_file == NULL)
42     return -1;
43 #endif
44   return !GetFileSize();
45 }
46
47 bool MkvReader::GetFileSize() {
48   if (m_file == NULL)
49     return false;
50 #ifdef _MSC_VER
51   int status = _fseeki64(m_file, 0L, SEEK_END);
52
53   if (status)
54     return false;  // error
55
56   m_length = _ftelli64(m_file);
57 #else
58   fseek(m_file, 0L, SEEK_END);
59   m_length = ftell(m_file);
60 #endif
61   assert(m_length >= 0);
62
63   if (m_length < 0)
64     return false;
65
66 #ifdef _MSC_VER
67   status = _fseeki64(m_file, 0L, SEEK_SET);
68
69   if (status)
70     return false;  // error
71 #else
72   fseek(m_file, 0L, SEEK_SET);
73 #endif
74
75   return true;
76 }
77
78 void MkvReader::Close() {
79   if (m_file != NULL) {
80     fclose(m_file);
81     m_file = NULL;
82   }
83 }
84
85 int MkvReader::Length(long long* total, long long* available) {
86   if (m_file == NULL)
87     return -1;
88
89   if (total)
90     *total = m_length;
91
92   if (available)
93     *available = m_length;
94
95   return 0;
96 }
97
98 int MkvReader::Read(long long offset, long len, unsigned char* buffer) {
99   if (m_file == NULL)
100     return -1;
101
102   if (offset < 0)
103     return -1;
104
105   if (len < 0)
106     return -1;
107
108   if (len == 0)
109     return 0;
110
111   if (offset >= m_length)
112     return -1;
113
114 #ifdef _MSC_VER
115   const int status = _fseeki64(m_file, offset, SEEK_SET);
116
117   if (status)
118     return -1;  // error
119 #else
120   fseek(m_file, offset, SEEK_SET);
121 #endif
122
123   const size_t size = fread(buffer, 1, len, m_file);
124
125   if (size < size_t(len))
126     return -1;  // error
127
128   return 0;  // success
129 }
130
131 }  // namespace mkvparser