1
0
Fork 0
OpenLCP/protocol/osc/bundle.cpp

100 lines
3.1 KiB
C++

/*
osc/bundle.cpp
Copyright (c) 2022 Kevin Matz (kevin.matz@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "bundle.h"
namespace OSC {
size_t Bundle::streamSize() const
{
size_t size = 16; // "#bundle" + timetag
for (const auto &element: elements)
size += 4 + element->streamSize(); // element's length + element length
return size;
}
void Bundle::iStream(std::shared_ptr<bufferstream> buffer)
{
auto element = [&](std::shared_ptr<Message> msg, uint32_t size) {
msg->iStream(buffer);
// The element, as read, must match the prescribed size.
if (!buffer->fail())
{
if (msg->streamSize() == size)
elements.push_back(msg);
else
buffer->setstate(std::ios::failbit);
}
};
/// An OSC Bundle consists of the OSC-string “#bundle”
std::string header;
Message::readString(buffer, header);
if (header.compare(address_pattern) != 0)
return buffer->setstate(std::ios::failbit);
/// ... followed by an OSC Time Tag
time_tag.iStream(buffer);
/// ... followed by zero or more OSC Bundle Elements.
while (buffer->available() && buffer->good())
{
/// > \cite Spec10 An OSC Bundle Element consists of its size and its contents.
/// > \cite Spec10 The size is an int32 representing the number of 8-bit bytes
/// > in the contents, and will always be a multiple of 4.
uint32_t size = buffer->readType<int32_t>();
if (size % 4 != 0)
return buffer->setstate(std::ios::failbit);
/// > \cite Spec10 The contents are either an OSC Message or an OSC Bundle.
switch (buffer->peek()) {
case '/':
element(std::make_shared<Message>(), size);
break;
case '#':
element(std::make_shared<Bundle>(), size);
break;
default:
buffer->setstate(std::ios::failbit);
}
}
}
void Bundle::oStream(std::shared_ptr<bufferstream> buffer) const
{
Message::writeString(buffer, address_pattern);
time_tag.oStream(buffer);
for (const auto &element: elements)
{
buffer->writeType<int32_t>(element->streamSize());
element->oStream(buffer);
}
}
} // namespace OSC