1// Copyright (c) 2012 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
9#include "mkvwriter.hpp"
10
11#ifdef _MSC_VER
12#include <share.h>  // for _SH_DENYWR
13#endif
14
15#include <new>
16
17namespace mkvmuxer {
18
19MkvWriter::MkvWriter() : file_(NULL), writer_owns_file_(true) {
20}
21
22MkvWriter::MkvWriter(FILE* fp): file_(fp), writer_owns_file_(false) {
23}
24
25MkvWriter::~MkvWriter() {
26  Close();
27}
28
29int32 MkvWriter::Write(const void* buffer, uint32 length) {
30  if (!file_)
31    return -1;
32
33  if (length == 0)
34    return 0;
35
36  if (buffer == NULL)
37    return -1;
38
39  const size_t bytes_written = fwrite(buffer, 1, length, file_);
40
41  return (bytes_written == length) ? 0 : -1;
42}
43
44bool MkvWriter::Open(const char* filename) {
45  if (filename == NULL)
46    return false;
47
48  if (file_)
49    return false;
50
51#ifdef _MSC_VER
52  file_ = _fsopen(filename, "wb", _SH_DENYWR);
53#else
54  file_ = fopen(filename, "wb");
55#endif
56  if (file_ == NULL)
57    return false;
58  return true;
59}
60
61void MkvWriter::Close() {
62  if (file_ && writer_owns_file_) {
63    fclose(file_);
64  }
65  file_ = NULL;
66}
67
68int64 MkvWriter::Position() const {
69  if (!file_)
70    return 0;
71
72#ifdef _MSC_VER
73    return _ftelli64(file_);
74#else
75    return ftell(file_);
76#endif
77}
78
79int32 MkvWriter::Position(int64 position) {
80  if (!file_)
81    return -1;
82
83#ifdef _MSC_VER
84    return _fseeki64(file_, position, SEEK_SET);
85#else
86    return fseek(file_, position, SEEK_SET);
87#endif
88}
89
90bool MkvWriter::Seekable() const {
91  return true;
92}
93
94void MkvWriter::ElementStartNotify(uint64, int64) {
95}
96
97}  // namespace mkvmuxer
98