NativeInstruments / ni-media

NI Media is a C++ library for reading and writing audio streams.
MIT License
244 stars 34 forks source link

Unable to sample_seekg to the last sample in an AIFF file #52

Open ghost opened 3 years ago

ghost commented 3 years ago

Using an AIFF file as input, I am unable to sample_seekg to the last sample in the file. If, however, I read the file sequentially using the extraction operator, I can read all samples in the file (including the last one). I tested this on 7e2de4b043f37a3833464c897e68a8fc3ca107d5.

The following example shows the issue:

    auto in = audio::ifstream{getSamplePath("sample.aif")};
    const auto inputSampleCount =
      static_cast<int>(in.seekg(0, std::ios::end).sample_tellg());

    float value;
    if (in.sample_seekg(inputSampleCount - 1) >> value)
    {
        // this code is never executed
    }

My expectation would have been to be able to sample_seekg to all samples in the file, understanding its argument as an index from zero to inputSampleCount - 1.

Consider the following code, using the same input as above:

    auto in = audio::ifstream{getSamplePath("sample.aif")};
    const auto inputSampleCount =
      static_cast<int>(in.seekg(0, std::ios::end).sample_tellg());

    auto readCount = 0;
    float value;
    in.seekg(0, std::ios::beg);
    while (in >> value)
    {
      ++readCount;
    }

At the end of the execution, readCount == inputSampleCount (as expected).

Furthermore, consider the following example in which each sample is sample_seekg to individually:

    auto in = audio::ifstream{getSamplePath("sample.aif")};
    const auto inputSampleCount =
      static_cast<int>(in.seekg(0, std::ios::end).sample_tellg());

    auto readCount = 0;
    float value;
    in.seekg(0, std::ios::beg);
    while (in.sample_seekg(readCount) >> value)
    {
      ++readCount;
      if (readCount == inputSampleCount)
      {
        break;
      }
    }

At the end of the execution, readCount == inputSampleCount - 1, which is not what I expected (I expected readCount == inputSampleCount).

Am I understanding the API incorrectly here?