Line data Source code
1 : /* 2 : * Copyright (C) 2004-2025 Savoir-faire Linux Inc. 3 : * 4 : * This program is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 3 of the License, or 7 : * (at your option) any later version. 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 <https://www.gnu.org/licenses/>. 16 : */ 17 : #pragma once 18 : 19 : extern "C" { 20 : #include <libavutil/samplefmt.h> 21 : } 22 : 23 : #include <fmt/core.h> 24 : #include <sstream> 25 : #include <string> 26 : #include <cstddef> // for size_t 27 : 28 : namespace jami { 29 : 30 : /** 31 : * Structure to hold sample rate and channel number associated with audio data. 32 : */ 33 : struct AudioFormat 34 : { 35 : unsigned sample_rate; 36 : unsigned nb_channels; 37 : AVSampleFormat sampleFormat; 38 : 39 2641 : constexpr AudioFormat(unsigned sr, unsigned c, AVSampleFormat f = AV_SAMPLE_FMT_S16) 40 2641 : : sample_rate(sr) 41 2641 : , nb_channels(c) 42 2641 : , sampleFormat(f) 43 2641 : {} 44 : 45 384 : inline bool operator==(const AudioFormat& b) const 46 : { 47 384 : return ((b.sample_rate == sample_rate) && (b.nb_channels == nb_channels) && (b.sampleFormat == sampleFormat)); 48 : } 49 : 50 285 : inline bool operator!=(const AudioFormat& b) const { return !(*this == b); } 51 : 52 99 : inline std::string toString() const 53 : { 54 198 : return fmt::format("{{{}, {} channels, {}Hz}}", av_get_sample_fmt_name(sampleFormat), nb_channels, sample_rate); 55 : } 56 : 57 0 : inline AudioFormat withSampleFormat(AVSampleFormat format) { return {sample_rate, nb_channels, format}; } 58 : 59 : /** 60 : * Returns bytes necessary to hold one frame of audio data. 61 : */ 62 : inline size_t getBytesPerFrame() const { return av_get_bytes_per_sample(sampleFormat) * nb_channels; } 63 : 64 : /** 65 : * Bytes per second (default), or bytes necessary 66 : * to hold delay_ms milliseconds of audio data. 67 : */ 68 : inline size_t getBandwidth(unsigned delay_ms = 1000) const 69 : { 70 : return (getBytesPerFrame() * sample_rate * delay_ms) / 1000; 71 : } 72 : 73 : static const constexpr unsigned DEFAULT_SAMPLE_RATE = 48000; 74 38 : static const constexpr AudioFormat DEFAULT() { return AudioFormat {16000, 1}; } 75 : static const constexpr AudioFormat NONE() { return AudioFormat {0, 0}; } 76 5 : static const constexpr AudioFormat MONO() { return AudioFormat {DEFAULT_SAMPLE_RATE, 1}; } 77 5 : static const constexpr AudioFormat STEREO() { return AudioFormat {DEFAULT_SAMPLE_RATE, 2}; } 78 : }; 79 : 80 : } // namespace jami