1 /*
2  * Copyright 2023, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <system/audio.h>
20 #include <audio_utils/CircularBuffer.h>
21 #include <audio_utils/spdif/FrameScanner.h>
22 #include <audio_utils/spdif/SPDIF.h>
23 
24 #include <algorithm>
25 #include <cstdint>
26 #include <vector>
27 
28 namespace android {
29 
30 using audio_utils::CircularBuffer;
31 
32 /**
33  * Scan the incoming SPDIF stream for a frame sync.
34  * Then unwrap the burst payload from the data burst and send it off to the receiver.
35  */
36 class SPDIFDecoder {
37  public:
38     explicit SPDIFDecoder(audio_format_t format);
39     virtual ~SPDIFDecoder() = default;
40 
41     /**
42      * Read burst payload data.
43      * @return number of bytes read or negative error
44      */
45     ssize_t read(void* buffer, size_t numBytes);
46 
47     /**
48      * Called by SPDIFDecoder for it to read in SPDIF stream data.
49      * Must be implemented in the subclass.
50      * @return number of bytes read or negative error
51      */
52     virtual ssize_t readInput(void* buffer, size_t numBytes) = 0;
53 
54     /**
55      * Get ratio of the encoded data burst sample rate to the encoded rate.
56      * For example, EAC3 data bursts are 4X the encoded rate.
57      */
getRateMultiplier()58     uint32_t getRateMultiplier() const { return mFramer->getRateMultiplier(); }
59 
60     /**
61      * @return true if we can unwrap this format from a SPDIF stream
62      */
63     static bool isFormatSupported(audio_format_t format);
64 
65     /**
66      * Discard any data in the buffer. Reset frame scanners.
67      * This should be called when seeking to a new position in the stream.
68      */
69     void reset();
70 
71  protected:
72     ssize_t fillBurstDataBuffer();
73 
74     std::unique_ptr<FrameScanner> mFramer;
75 
76     audio_format_t mAudioFormat;
77     CircularBuffer mBurstDataBuffer;  // Stores burst data
78     size_t mPayloadBytesPending;  // number of bytes of burst payload remaining to be extracted
79     size_t mPayloadBytesRead;  // number of bytes of burst payload already extracted
80     bool mScanning;  // state variable, true if scanning for start of SPDIF frame
81 };
82 
83 }  // namespace android
84