Skip to content

Commit

Permalink
improve safety
Browse files Browse the repository at this point in the history
  • Loading branch information
leng-yue committed Aug 24, 2024
1 parent ef69071 commit b0ff78f
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ class OpusBufferedEncoder
OggOpusEnc *encoder;
OggOpusComments *comments;
int channels;
bool has_written;

public:
OpusBufferedEncoder(int sample_rate, int channels, int bitrate = OPUS_AUTO, int signal_type = 0, int encoder_complexity = 10, int decision_delay = 0)
: encoder(nullptr), comments(nullptr), channels(channels)
: encoder(nullptr), comments(nullptr), channels(channels), has_written(false)
{
if (channels < 1 || channels > 8)
{
Expand Down Expand Up @@ -97,6 +98,11 @@ class OpusBufferedEncoder
throw py::value_error("Buffer must have shape [samples, channels] and match the number of channels specified in the constructor.");
}

if (buffer.shape(0) == 0)
{
return py::bytes();
}

const int16_t *data = buffer.data();
int samples = buffer.shape(0);

Expand All @@ -107,6 +113,8 @@ class OpusBufferedEncoder
throw py::value_error("Encoding failed");
}

has_written = true;

unsigned char *packet;
opus_int32 len;
while (ope_encoder_get_page(encoder, &packet, &len, 1) != 0)
Expand All @@ -119,7 +127,16 @@ class OpusBufferedEncoder

py::bytes flush()
{
ope_encoder_drain(encoder);
if (!has_written)
{
throw py::value_error("You must call write() at least once before calling flush().");
}

if (ope_encoder_drain(encoder) != OPE_OK)
{
throw py::value_error("Draining failed, you can't call flush() more than once.");
}

opus_int32 len;
unsigned char *packet;
std::vector<unsigned char> encoded_data;
Expand Down

0 comments on commit b0ff78f

Please sign in to comment.