summaryrefslogtreecommitdiff
path: root/src/codecs/include/codec.hpp
blob: 32ebef692b00aad6ae1c0eb94bf3c64704adb642 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#pragma once

#include <stdint.h>
#include <sys/_stdint.h>

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

#include "result.hpp"
#include "sample.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,
  };

  static auto ErrorString(Error err) -> std::string {
    switch (err) {
      case Error::kOutOfInput:
        return "out of input";
      case Error::kMalformedData:
        return "malformed data";
      case Error::kInternalError:
        return "internal error";
    }
    return "uhh";
  }

  /*
   * 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;
    uint32_t sample_rate_hz;

    std::optional<uint32_t> duration_seconds;
    std::optional<uint32_t> bits_per_second;
  };

  /*
   * 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 samples_written;
    bool is_finished_writing;
  };

  /*
   * Writes PCM samples to the given output buffer.
   */
  virtual auto ContinueStream(cpp::span<const std::byte> input,
                              cpp::span<sample::Sample> 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