summaryrefslogtreecommitdiff
path: root/src/codecs/include/codec.hpp
blob: 4b5ab47fa818a97d16af3e63f9ff5036e2ec1617 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#pragma once

#include <stdint.h>

#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>

#include "result.hpp"
#include "span.hpp"
#include "types.hpp"

namespace codecs {

/*
 * Common interface to be implemented by all audio decoders.
 */
class ICodec {
 public:
  virtual ~ICodec() {}

  /* Errors that may be returned by codecs. */
  enum class Error {
    // Indicates that more data is required before this codec can finish its
    // operation. E.g. the input buffer ends with a truncated frame.
    kOutOfInput,
    // Indicates that the data within the input buffer is fatally malformed.
    kMalformedData,

    kInternalError,
  };

  /*
   * Alias for more readable return types. All codec methods, success or
   * failure, should also return the number of bytes they consumed.
   */
  template <typename T>
  using Result = std::pair<std::size_t, cpp::result<T, Error>>;

  struct OutputFormat {
    uint8_t num_channels;
    uint8_t bits_per_sample;
    uint32_t sample_rate_hz;
  };

  /*
   * Decodes metadata or headers from the given input stream, and returns the
   * format for the samples that will be decoded from it.
   */
  virtual auto BeginStream(cpp::span<const std::byte> input)
      -> Result<OutputFormat> = 0;

  struct OutputInfo {
    std::size_t bytes_written;
    bool is_finished_writing;
  };

  /*
   * Writes PCM samples to the given output buffer.
   */
  virtual auto ContinueStream(cpp::span<const std::byte> input,
                              cpp::span<std::byte> output)
      -> Result<OutputInfo> = 0;

  virtual auto SeekStream(cpp::span<const std::byte> input,
                          std::size_t target_sample) -> Result<void> = 0;
};

auto CreateCodecForType(StreamType type) -> std::optional<ICodec*>;

}  // namespace codecs