The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1188 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. namespace
  16. {
  17. //==============================================================================
  18. /** Allows a block of data to be accessed as a stream of OSC data.
  19. The memory is shared and will be neither copied nor owned by the OSCInputStream.
  20. This class is implementing the Open Sound Control 1.0 Specification for
  21. interpreting the data.
  22. Note: Some older implementations of OSC may omit the OSC Type Tag string
  23. in OSC messages. This class will treat such OSC messages as format errors.
  24. */
  25. class OSCInputStream
  26. {
  27. public:
  28. /** Creates an OSCInputStream.
  29. @param sourceData the block of data to use as the stream's source
  30. @param sourceDataSize the number of bytes in the source data block
  31. */
  32. OSCInputStream (const void* sourceData, size_t sourceDataSize)
  33. : input (sourceData, sourceDataSize, false)
  34. {}
  35. //==============================================================================
  36. /** Returns a pointer to the source data block from which this stream is reading. */
  37. const void* getData() const noexcept { return input.getData(); }
  38. /** Returns the number of bytes of source data in the block from which this stream is reading. */
  39. size_t getDataSize() const noexcept { return input.getDataSize(); }
  40. /** Returns the current position of the stream. */
  41. uint64 getPosition() { return (uint64) input.getPosition(); }
  42. /** Attempts to set the current position of the stream. Returns true if this was successful. */
  43. bool setPosition (int64 pos) { return input.setPosition (pos); }
  44. /** Returns the total amount of data in bytes accessible by this stream. */
  45. int64 getTotalLength() { return input.getTotalLength(); }
  46. /** Returns true if the stream has no more data to read. */
  47. bool isExhausted() { return input.isExhausted(); }
  48. //==============================================================================
  49. int32 readInt32()
  50. {
  51. checkBytesAvailable (4, "OSC input stream exhausted while reading int32");
  52. return input.readIntBigEndian();
  53. }
  54. uint64 readUint64()
  55. {
  56. checkBytesAvailable (8, "OSC input stream exhausted while reading uint64");
  57. return (uint64) input.readInt64BigEndian();
  58. }
  59. float readFloat32()
  60. {
  61. checkBytesAvailable (4, "OSC input stream exhausted while reading float");
  62. return input.readFloatBigEndian();
  63. }
  64. String readString()
  65. {
  66. checkBytesAvailable (4, "OSC input stream exhausted while reading string");
  67. auto posBegin = (size_t) getPosition();
  68. auto s = input.readString();
  69. auto posEnd = (size_t) getPosition();
  70. if (static_cast<const char*> (getData()) [posEnd - 1] != '\0')
  71. throw OSCFormatError ("OSC input stream exhausted before finding null terminator of string");
  72. size_t bytesRead = posEnd - posBegin;
  73. readPaddingZeros (bytesRead);
  74. return s;
  75. }
  76. MemoryBlock readBlob()
  77. {
  78. checkBytesAvailable (4, "OSC input stream exhausted while reading blob");
  79. auto blobDataSize = input.readIntBigEndian();
  80. checkBytesAvailable ((blobDataSize + 3) % 4, "OSC input stream exhausted before reaching end of blob");
  81. MemoryBlock blob;
  82. auto bytesRead = input.readIntoMemoryBlock (blob, (ssize_t) blobDataSize);
  83. readPaddingZeros (bytesRead);
  84. return blob;
  85. }
  86. OSCColour readColour()
  87. {
  88. checkBytesAvailable (4, "OSC input stream exhausted while reading colour");
  89. return OSCColour::fromInt32 ((uint32) input.readIntBigEndian());
  90. }
  91. OSCTimeTag readTimeTag()
  92. {
  93. checkBytesAvailable (8, "OSC input stream exhausted while reading time tag");
  94. return OSCTimeTag (uint64 (input.readInt64BigEndian()));
  95. }
  96. OSCAddress readAddress()
  97. {
  98. return OSCAddress (readString());
  99. }
  100. OSCAddressPattern readAddressPattern()
  101. {
  102. return OSCAddressPattern (readString());
  103. }
  104. //==============================================================================
  105. OSCTypeList readTypeTagString()
  106. {
  107. OSCTypeList typeList;
  108. checkBytesAvailable (4, "OSC input stream exhausted while reading type tag string");
  109. if (input.readByte() != ',')
  110. throw OSCFormatError ("OSC input stream format error: expected type tag string");
  111. for (;;)
  112. {
  113. if (isExhausted())
  114. throw OSCFormatError ("OSC input stream exhausted while reading type tag string");
  115. const OSCType type = input.readByte();
  116. if (type == 0)
  117. break; // encountered null terminator. list is complete.
  118. if (! OSCTypes::isSupportedType (type))
  119. throw OSCFormatError ("OSC input stream format error: encountered unsupported type tag");
  120. typeList.add (type);
  121. }
  122. auto bytesRead = (size_t) typeList.size() + 2;
  123. readPaddingZeros (bytesRead);
  124. return typeList;
  125. }
  126. //==============================================================================
  127. OSCArgument readArgument (OSCType type)
  128. {
  129. switch (type)
  130. {
  131. case OSCTypes::int32: return OSCArgument (readInt32());
  132. case OSCTypes::float32: return OSCArgument (readFloat32());
  133. case OSCTypes::string: return OSCArgument (readString());
  134. case OSCTypes::blob: return OSCArgument (readBlob());
  135. case OSCTypes::colour: return OSCArgument (readColour());
  136. default:
  137. // You supplied an invalid OSCType when calling readArgument! This should never happen.
  138. jassertfalse;
  139. throw OSCInternalError ("OSC input stream: internal error while reading message argument");
  140. }
  141. }
  142. //==============================================================================
  143. OSCMessage readMessage()
  144. {
  145. auto ap = readAddressPattern();
  146. auto types = readTypeTagString();
  147. OSCMessage msg (ap);
  148. for (auto& type : types)
  149. msg.addArgument (readArgument (type));
  150. return msg;
  151. }
  152. //==============================================================================
  153. OSCBundle readBundle (size_t maxBytesToRead = std::numeric_limits<size_t>::max())
  154. {
  155. // maxBytesToRead is only passed in here in case this bundle is a nested
  156. // bundle, so we know when to consider the next element *not* part of this
  157. // bundle anymore (but part of the outer bundle) and return.
  158. checkBytesAvailable (16, "OSC input stream exhausted while reading bundle");
  159. if (readString() != "#bundle")
  160. throw OSCFormatError ("OSC input stream format error: bundle does not start with string '#bundle'");
  161. OSCBundle bundle (readTimeTag());
  162. size_t bytesRead = 16; // already read "#bundle" and timeTag
  163. auto pos = getPosition();
  164. while (! isExhausted() && bytesRead < maxBytesToRead)
  165. {
  166. bundle.addElement (readElement());
  167. auto newPos = getPosition();
  168. bytesRead += (size_t) (newPos - pos);
  169. pos = newPos;
  170. }
  171. return bundle;
  172. }
  173. //==============================================================================
  174. OSCBundle::Element readElement()
  175. {
  176. checkBytesAvailable (4, "OSC input stream exhausted while reading bundle element size");
  177. auto elementSize = (size_t) readInt32();
  178. if (elementSize < 4)
  179. throw OSCFormatError ("OSC input stream format error: invalid bundle element size");
  180. return readElementWithKnownSize (elementSize);
  181. }
  182. //==============================================================================
  183. OSCBundle::Element readElementWithKnownSize (size_t elementSize)
  184. {
  185. checkBytesAvailable ((int64) elementSize, "OSC input stream exhausted while reading bundle element content");
  186. auto firstContentChar = static_cast<const char*> (getData()) [getPosition()];
  187. if (firstContentChar == '/') return OSCBundle::Element (readMessageWithCheckedSize (elementSize));
  188. if (firstContentChar == '#') return OSCBundle::Element (readBundleWithCheckedSize (elementSize));
  189. throw OSCFormatError ("OSC input stream: invalid bundle element content");
  190. }
  191. private:
  192. MemoryInputStream input;
  193. //==============================================================================
  194. void readPaddingZeros (size_t bytesRead)
  195. {
  196. size_t numZeros = ~(bytesRead - 1) & 0x03;
  197. while (numZeros > 0)
  198. {
  199. if (isExhausted() || input.readByte() != 0)
  200. throw OSCFormatError ("OSC input stream format error: missing padding zeros");
  201. --numZeros;
  202. }
  203. }
  204. OSCBundle readBundleWithCheckedSize (size_t size)
  205. {
  206. auto begin = (size_t) getPosition();
  207. auto maxBytesToRead = size - 4; // we've already read 4 bytes (the bundle size)
  208. OSCBundle bundle (readBundle (maxBytesToRead));
  209. if (getPosition() - begin != size)
  210. throw OSCFormatError ("OSC input stream format error: wrong element content size encountered while reading");
  211. return bundle;
  212. }
  213. OSCMessage readMessageWithCheckedSize (size_t size)
  214. {
  215. auto begin = (size_t) getPosition();
  216. auto message = readMessage();
  217. if (getPosition() - begin != size)
  218. throw OSCFormatError ("OSC input stream format error: wrong element content size encountered while reading");
  219. return message;
  220. }
  221. void checkBytesAvailable (int64 requiredBytes, const char* message)
  222. {
  223. if (input.getNumBytesRemaining() < requiredBytes)
  224. throw OSCFormatError (message);
  225. }
  226. };
  227. } // namespace
  228. //==============================================================================
  229. struct OSCReceiver::Pimpl : private Thread,
  230. private MessageListener
  231. {
  232. Pimpl (const String& oscThreadName) : Thread (oscThreadName)
  233. {
  234. }
  235. ~Pimpl() override
  236. {
  237. disconnect();
  238. }
  239. //==============================================================================
  240. bool connectToPort (int portNumber)
  241. {
  242. if (! disconnect())
  243. return false;
  244. socket.setOwned (new DatagramSocket (false));
  245. if (! socket->bindToPort (portNumber))
  246. return false;
  247. startThread();
  248. return true;
  249. }
  250. bool connectToSocket (DatagramSocket& newSocket)
  251. {
  252. if (! disconnect())
  253. return false;
  254. socket.setNonOwned (&newSocket);
  255. startThread();
  256. return true;
  257. }
  258. bool disconnect()
  259. {
  260. if (socket != nullptr)
  261. {
  262. signalThreadShouldExit();
  263. if (socket.willDeleteObject())
  264. socket->shutdown();
  265. waitForThreadToExit (10000);
  266. socket.reset();
  267. }
  268. return true;
  269. }
  270. //==============================================================================
  271. void addListener (OSCReceiver::Listener<MessageLoopCallback>* listenerToAdd)
  272. {
  273. listeners.add (listenerToAdd);
  274. }
  275. void addListener (OSCReceiver::Listener<RealtimeCallback>* listenerToAdd)
  276. {
  277. realtimeListeners.add (listenerToAdd);
  278. }
  279. void addListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToAdd,
  280. OSCAddress addressToMatch)
  281. {
  282. addListenerWithAddress (listenerToAdd, addressToMatch, listenersWithAddress);
  283. }
  284. void addListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToAdd, OSCAddress addressToMatch)
  285. {
  286. addListenerWithAddress (listenerToAdd, addressToMatch, realtimeListenersWithAddress);
  287. }
  288. void removeListener (OSCReceiver::Listener<MessageLoopCallback>* listenerToRemove)
  289. {
  290. listeners.remove (listenerToRemove);
  291. }
  292. void removeListener (OSCReceiver::Listener<RealtimeCallback>* listenerToRemove)
  293. {
  294. realtimeListeners.remove (listenerToRemove);
  295. }
  296. void removeListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToRemove)
  297. {
  298. removeListenerWithAddress (listenerToRemove, listenersWithAddress);
  299. }
  300. void removeListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToRemove)
  301. {
  302. removeListenerWithAddress (listenerToRemove, realtimeListenersWithAddress);
  303. }
  304. //==============================================================================
  305. struct CallbackMessage : public Message
  306. {
  307. CallbackMessage (OSCBundle::Element oscElement) : content (oscElement) {}
  308. // the payload of the message. Can be either an OSCMessage or an OSCBundle.
  309. OSCBundle::Element content;
  310. };
  311. //==============================================================================
  312. void handleBuffer (const char* data, size_t dataSize)
  313. {
  314. OSCInputStream inStream (data, dataSize);
  315. try
  316. {
  317. auto content = inStream.readElementWithKnownSize (dataSize);
  318. // realtime listeners should receive the OSC content first - and immediately
  319. // on this thread:
  320. callRealtimeListeners (content);
  321. if (content.isMessage())
  322. callRealtimeListenersWithAddress (content.getMessage());
  323. // now post the message that will trigger the handleMessage callback
  324. // dealing with the non-realtime listeners.
  325. if (listeners.size() > 0 || listenersWithAddress.size() > 0)
  326. postMessage (new CallbackMessage (content));
  327. }
  328. catch (const OSCFormatError&)
  329. {
  330. if (formatErrorHandler != nullptr)
  331. formatErrorHandler (data, (int) dataSize);
  332. }
  333. }
  334. //==============================================================================
  335. void registerFormatErrorHandler (OSCReceiver::FormatErrorHandler handler)
  336. {
  337. formatErrorHandler = handler;
  338. }
  339. private:
  340. //==============================================================================
  341. void run() override
  342. {
  343. int bufferSize = 65535;
  344. HeapBlock<char> oscBuffer (bufferSize);
  345. while (! threadShouldExit())
  346. {
  347. jassert (socket != nullptr);
  348. auto ready = socket->waitUntilReady (true, 100);
  349. if (ready < 0 || threadShouldExit())
  350. return;
  351. if (ready == 0)
  352. continue;
  353. auto bytesRead = (size_t) socket->read (oscBuffer.getData(), bufferSize, false);
  354. if (bytesRead >= 4)
  355. handleBuffer (oscBuffer.getData(), bytesRead);
  356. }
  357. }
  358. //==============================================================================
  359. template <typename ListenerType>
  360. void addListenerWithAddress (ListenerType* listenerToAdd,
  361. OSCAddress address,
  362. Array<std::pair<OSCAddress, ListenerType*>>& array)
  363. {
  364. for (auto& i : array)
  365. if (address == i.first && listenerToAdd == i.second)
  366. return;
  367. array.add (std::make_pair (address, listenerToAdd));
  368. }
  369. //==============================================================================
  370. template <typename ListenerType>
  371. void removeListenerWithAddress (ListenerType* listenerToRemove,
  372. Array<std::pair<OSCAddress, ListenerType*>>& array)
  373. {
  374. for (int i = 0; i < array.size(); ++i)
  375. {
  376. if (listenerToRemove == array.getReference (i).second)
  377. {
  378. // aarrgh... can't simply call array.remove (i) because this
  379. // requires a default c'tor to be present for OSCAddress...
  380. // luckily, we don't care about methods preserving element order:
  381. array.swap (i, array.size() - 1);
  382. array.removeLast();
  383. break;
  384. }
  385. }
  386. }
  387. //==============================================================================
  388. void handleMessage (const Message& msg) override
  389. {
  390. if (auto* callbackMessage = dynamic_cast<const CallbackMessage*> (&msg))
  391. {
  392. auto& content = callbackMessage->content;
  393. callListeners (content);
  394. if (content.isMessage())
  395. callListenersWithAddress (content.getMessage());
  396. }
  397. }
  398. //==============================================================================
  399. void callListeners (const OSCBundle::Element& content)
  400. {
  401. using OSCListener = OSCReceiver::Listener<OSCReceiver::MessageLoopCallback>;
  402. if (content.isMessage())
  403. {
  404. auto&& message = content.getMessage();
  405. listeners.call ([&] (OSCListener& l) { l.oscMessageReceived (message); });
  406. }
  407. else if (content.isBundle())
  408. {
  409. auto&& bundle = content.getBundle();
  410. listeners.call ([&] (OSCListener& l) { l.oscBundleReceived (bundle); });
  411. }
  412. }
  413. void callRealtimeListeners (const OSCBundle::Element& content)
  414. {
  415. using OSCListener = OSCReceiver::Listener<OSCReceiver::RealtimeCallback>;
  416. if (content.isMessage())
  417. {
  418. auto&& message = content.getMessage();
  419. realtimeListeners.call ([&] (OSCListener& l) { l.oscMessageReceived (message); });
  420. }
  421. else if (content.isBundle())
  422. {
  423. auto&& bundle = content.getBundle();
  424. realtimeListeners.call ([&] (OSCListener& l) { l.oscBundleReceived (bundle); });
  425. }
  426. }
  427. //==============================================================================
  428. void callListenersWithAddress (const OSCMessage& message)
  429. {
  430. for (auto& entry : listenersWithAddress)
  431. if (auto* listener = entry.second)
  432. if (message.getAddressPattern().matches (entry.first))
  433. listener->oscMessageReceived (message);
  434. }
  435. void callRealtimeListenersWithAddress (const OSCMessage& message)
  436. {
  437. for (auto& entry : realtimeListenersWithAddress)
  438. if (auto* listener = entry.second)
  439. if (message.getAddressPattern().matches (entry.first))
  440. listener->oscMessageReceived (message);
  441. }
  442. //==============================================================================
  443. ListenerList<OSCReceiver::Listener<OSCReceiver::MessageLoopCallback>> listeners;
  444. ListenerList<OSCReceiver::Listener<OSCReceiver::RealtimeCallback>> realtimeListeners;
  445. Array<std::pair<OSCAddress, OSCReceiver::ListenerWithOSCAddress<OSCReceiver::MessageLoopCallback>*>> listenersWithAddress;
  446. Array<std::pair<OSCAddress, OSCReceiver::ListenerWithOSCAddress<OSCReceiver::RealtimeCallback>*>> realtimeListenersWithAddress;
  447. OptionalScopedPointer<DatagramSocket> socket;
  448. OSCReceiver::FormatErrorHandler formatErrorHandler { nullptr };
  449. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  450. };
  451. //==============================================================================
  452. OSCReceiver::OSCReceiver (const String& threadName) : pimpl (new Pimpl (threadName))
  453. {
  454. }
  455. OSCReceiver::OSCReceiver() : OSCReceiver ("JUCE OSC server")
  456. {
  457. }
  458. OSCReceiver::~OSCReceiver()
  459. {
  460. pimpl.reset();
  461. }
  462. bool OSCReceiver::connect (int portNumber)
  463. {
  464. return pimpl->connectToPort (portNumber);
  465. }
  466. bool OSCReceiver::connectToSocket (DatagramSocket& socket)
  467. {
  468. return pimpl->connectToSocket (socket);
  469. }
  470. bool OSCReceiver::disconnect()
  471. {
  472. return pimpl->disconnect();
  473. }
  474. void OSCReceiver::addListener (OSCReceiver::Listener<MessageLoopCallback>* listenerToAdd)
  475. {
  476. pimpl->addListener (listenerToAdd);
  477. }
  478. void OSCReceiver::addListener (Listener<RealtimeCallback>* listenerToAdd)
  479. {
  480. pimpl->addListener (listenerToAdd);
  481. }
  482. void OSCReceiver::addListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToAdd, OSCAddress addressToMatch)
  483. {
  484. pimpl->addListener (listenerToAdd, addressToMatch);
  485. }
  486. void OSCReceiver::addListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToAdd, OSCAddress addressToMatch)
  487. {
  488. pimpl->addListener (listenerToAdd, addressToMatch);
  489. }
  490. void OSCReceiver::removeListener (Listener<MessageLoopCallback>* listenerToRemove)
  491. {
  492. pimpl->removeListener (listenerToRemove);
  493. }
  494. void OSCReceiver::removeListener (Listener<RealtimeCallback>* listenerToRemove)
  495. {
  496. pimpl->removeListener (listenerToRemove);
  497. }
  498. void OSCReceiver::removeListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToRemove)
  499. {
  500. pimpl->removeListener (listenerToRemove);
  501. }
  502. void OSCReceiver::removeListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToRemove)
  503. {
  504. pimpl->removeListener (listenerToRemove);
  505. }
  506. void OSCReceiver::registerFormatErrorHandler (FormatErrorHandler handler)
  507. {
  508. pimpl->registerFormatErrorHandler (handler);
  509. }
  510. //==============================================================================
  511. //==============================================================================
  512. #if JUCE_UNIT_TESTS
  513. class OSCInputStreamTests : public UnitTest
  514. {
  515. public:
  516. OSCInputStreamTests()
  517. : UnitTest ("OSCInputStream class", UnitTestCategories::osc)
  518. {}
  519. void runTest()
  520. {
  521. beginTest ("reading OSC addresses");
  522. {
  523. const char buffer[16] = {
  524. '/', 't', 'e', 's', 't', '/', 'f', 'a',
  525. 'd', 'e', 'r', '7', '\0', '\0', '\0', '\0' };
  526. // reading a valid osc address:
  527. {
  528. OSCInputStream inStream (buffer, sizeof (buffer));
  529. OSCAddress address = inStream.readAddress();
  530. expect (inStream.getPosition() == sizeof (buffer));
  531. expectEquals (address.toString(), String ("/test/fader7"));
  532. }
  533. // check various possible failures:
  534. {
  535. // zero padding is present, but size is not modulo 4:
  536. OSCInputStream inStream (buffer, 15);
  537. expectThrowsType (inStream.readAddress(), OSCFormatError)
  538. }
  539. {
  540. // zero padding is missing:
  541. OSCInputStream inStream (buffer, 12);
  542. expectThrowsType (inStream.readAddress(), OSCFormatError)
  543. }
  544. {
  545. // pattern does not start with a forward slash:
  546. OSCInputStream inStream (buffer + 4, 12);
  547. expectThrowsType (inStream.readAddress(), OSCFormatError)
  548. }
  549. }
  550. beginTest ("reading OSC address patterns");
  551. {
  552. const char buffer[20] = {
  553. '/', '*', '/', '*', 'p', 'u', 't', '/',
  554. 'f', 'a', 'd', 'e', 'r', '[', '0', '-',
  555. '9', ']', '\0', '\0' };
  556. // reading a valid osc address pattern:
  557. {
  558. OSCInputStream inStream (buffer, sizeof (buffer));
  559. expectDoesNotThrow (inStream.readAddressPattern());
  560. }
  561. {
  562. OSCInputStream inStream (buffer, sizeof (buffer));
  563. OSCAddressPattern ap = inStream.readAddressPattern();
  564. expect (inStream.getPosition() == sizeof (buffer));
  565. expectEquals (ap.toString(), String ("/*/*put/fader[0-9]"));
  566. expect (ap.containsWildcards());
  567. }
  568. // check various possible failures:
  569. {
  570. // zero padding is present, but size is not modulo 4:
  571. OSCInputStream inStream (buffer, 19);
  572. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  573. }
  574. {
  575. // zero padding is missing:
  576. OSCInputStream inStream (buffer, 16);
  577. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  578. }
  579. {
  580. // pattern does not start with a forward slash:
  581. OSCInputStream inStream (buffer + 4, 16);
  582. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  583. }
  584. }
  585. beginTest ("reading OSC time tags");
  586. {
  587. char buffer[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
  588. OSCInputStream inStream (buffer, sizeof (buffer));
  589. OSCTimeTag tag = inStream.readTimeTag();
  590. expect (tag.isImmediately());
  591. }
  592. {
  593. char buffer[8] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  594. OSCInputStream inStream (buffer, sizeof (buffer));
  595. OSCTimeTag tag = inStream.readTimeTag();
  596. expect (! tag.isImmediately());
  597. }
  598. beginTest ("reading OSC arguments");
  599. {
  600. // test data:
  601. int testInt = -2015;
  602. const uint8 testIntRepresentation[] = { 0xFF, 0xFF, 0xF8, 0x21 }; // big endian two's complement
  603. float testFloat = 345.6125f;
  604. const uint8 testFloatRepresentation[] = { 0x43, 0xAC, 0xCE, 0x66 }; // big endian IEEE 754
  605. String testString = "Hello, World!";
  606. const char testStringRepresentation[] = {
  607. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  608. 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' }; // padded to size % 4 == 0
  609. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  610. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  611. const uint8 testBlobRepresentation[] = {
  612. 0x00, 0x00, 0x00, 0x05,
  613. 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00 }; // size prefixed + padded to size % 4 == 0
  614. // read:
  615. {
  616. {
  617. // int32:
  618. OSCInputStream inStream (testIntRepresentation, sizeof (testIntRepresentation));
  619. OSCArgument arg = inStream.readArgument (OSCTypes::int32);
  620. expect (inStream.getPosition() == 4);
  621. expect (arg.isInt32());
  622. expectEquals (arg.getInt32(), testInt);
  623. }
  624. {
  625. // float32:
  626. OSCInputStream inStream (testFloatRepresentation, sizeof (testFloatRepresentation));
  627. OSCArgument arg = inStream.readArgument (OSCTypes::float32);
  628. expect (inStream.getPosition() == 4);
  629. expect (arg.isFloat32());
  630. expectEquals (arg.getFloat32(), testFloat);
  631. }
  632. {
  633. // string:
  634. OSCInputStream inStream (testStringRepresentation, sizeof (testStringRepresentation));
  635. OSCArgument arg = inStream.readArgument (OSCTypes::string);
  636. expect (inStream.getPosition() == sizeof (testStringRepresentation));
  637. expect (arg.isString());
  638. expectEquals (arg.getString(), testString);
  639. }
  640. {
  641. // blob:
  642. OSCInputStream inStream (testBlobRepresentation, sizeof (testBlobRepresentation));
  643. OSCArgument arg = inStream.readArgument (OSCTypes::blob);
  644. expect (inStream.getPosition() == sizeof (testBlobRepresentation));
  645. expect (arg.isBlob());
  646. expect (arg.getBlob() == testBlob);
  647. }
  648. }
  649. // read invalid representations:
  650. {
  651. // not enough bytes
  652. {
  653. const uint8 rawData[] = { 0xF8, 0x21 };
  654. OSCInputStream inStream (rawData, sizeof (rawData));
  655. expectThrowsType (inStream.readArgument (OSCTypes::int32), OSCFormatError);
  656. expectThrowsType (inStream.readArgument (OSCTypes::float32), OSCFormatError);
  657. }
  658. // test string not being padded to multiple of 4 bytes:
  659. {
  660. const char rawData[] = {
  661. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  662. 'o', 'r', 'l', 'd', '!', '\0' }; // padding missing
  663. OSCInputStream inStream (rawData, sizeof (rawData));
  664. expectThrowsType (inStream.readArgument (OSCTypes::string), OSCFormatError);
  665. }
  666. {
  667. const char rawData[] = {
  668. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  669. 'o', 'r', 'l', 'd', '!', '\0', 'x', 'x' }; // padding with non-zero chars
  670. OSCInputStream inStream (rawData, sizeof (rawData));
  671. expectThrowsType (inStream.readArgument (OSCTypes::string), OSCFormatError);
  672. }
  673. // test blob not being padded to multiple of 4 bytes:
  674. {
  675. const uint8 rawData[] = { 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; // padding missing
  676. OSCInputStream inStream (rawData, sizeof (rawData));
  677. expectThrowsType (inStream.readArgument (OSCTypes::blob), OSCFormatError);
  678. }
  679. // test blob having wrong size
  680. {
  681. const uint8 rawData[] = { 0x00, 0x00, 0x00, 0x12, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  682. OSCInputStream inStream (rawData, sizeof (rawData));
  683. expectThrowsType (inStream.readArgument (OSCTypes::blob), OSCFormatError);
  684. }
  685. }
  686. }
  687. beginTest ("reading OSC messages (type tag string)");
  688. {
  689. {
  690. // valid empty message
  691. const char data[] = {
  692. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  693. ',', '\0', '\0', '\0' };
  694. OSCInputStream inStream (data, sizeof (data));
  695. auto msg = inStream.readMessage();
  696. expect (msg.getAddressPattern().toString() == "/test");
  697. expect (msg.size() == 0);
  698. }
  699. {
  700. // invalid message: no type tag string
  701. const char data[] = {
  702. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  703. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  704. 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' };
  705. OSCInputStream inStream (data, sizeof (data));
  706. expectThrowsType (inStream.readMessage(), OSCFormatError);
  707. }
  708. {
  709. // invalid message: no type tag string and also empty
  710. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0' };
  711. OSCInputStream inStream (data, sizeof (data));
  712. expectThrowsType (inStream.readMessage(), OSCFormatError);
  713. }
  714. // invalid message: wrong padding
  715. {
  716. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', '\0', '\0', '\0' };
  717. OSCInputStream inStream (data, sizeof (data) - 1);
  718. expectThrowsType (inStream.readMessage(), OSCFormatError);
  719. }
  720. // invalid message: says it contains an arg, but doesn't
  721. {
  722. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', 'i', '\0', '\0' };
  723. OSCInputStream inStream (data, sizeof (data));
  724. expectThrowsType (inStream.readMessage(), OSCFormatError);
  725. }
  726. // invalid message: binary size does not match size deducted from type tag string
  727. {
  728. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', 'i', 'f', '\0' };
  729. OSCInputStream inStream (data, sizeof (data));
  730. expectThrowsType (inStream.readMessage(), OSCFormatError);
  731. }
  732. }
  733. beginTest ("reading OSC messages (contents)");
  734. {
  735. // valid non-empty message.
  736. {
  737. int32 testInt = -2015;
  738. float testFloat = 345.6125f;
  739. String testString = "Hello, World!";
  740. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  741. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  742. uint8 data[] = {
  743. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  744. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  745. 0xFF, 0xFF, 0xF8, 0x21,
  746. 0x43, 0xAC, 0xCE, 0x66,
  747. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  748. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  749. };
  750. OSCInputStream inStream (data, sizeof (data));
  751. auto msg = inStream.readMessage();
  752. expectEquals (msg.getAddressPattern().toString(), String ("/test"));
  753. expectEquals (msg.size(), 4);
  754. expectEquals (msg[0].getType(), OSCTypes::int32);
  755. expectEquals (msg[1].getType(), OSCTypes::float32);
  756. expectEquals (msg[2].getType(), OSCTypes::string);
  757. expectEquals (msg[3].getType(), OSCTypes::blob);
  758. expectEquals (msg[0].getInt32(), testInt);
  759. expectEquals (msg[1].getFloat32(), testFloat);
  760. expectEquals (msg[2].getString(), testString);
  761. expect (msg[3].getBlob() == testBlob);
  762. }
  763. }
  764. beginTest ("reading OSC messages (handling of corrupted messages)");
  765. {
  766. // invalid messages
  767. {
  768. OSCInputStream inStream (nullptr, 0);
  769. expectThrowsType (inStream.readMessage(), OSCFormatError);
  770. }
  771. {
  772. const uint8 data[] = { 0x00 };
  773. OSCInputStream inStream (data, 0);
  774. expectThrowsType (inStream.readMessage(), OSCFormatError);
  775. }
  776. {
  777. uint8 data[] = {
  778. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  779. ',', 'i', 'f', 's', 'b', // type tag string not padded
  780. 0xFF, 0xFF, 0xF8, 0x21,
  781. 0x43, 0xAC, 0xCE, 0x66,
  782. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  783. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  784. };
  785. OSCInputStream inStream (data, sizeof (data));
  786. expectThrowsType (inStream.readMessage(), OSCFormatError);
  787. }
  788. {
  789. uint8 data[] = {
  790. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  791. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  792. 0xFF, 0xFF, 0xF8, 0x21,
  793. 0x43, 0xAC, 0xCE, 0x66,
  794. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' // rest of message cut off
  795. };
  796. OSCInputStream inStream (data, sizeof (data));
  797. expectThrowsType (inStream.readMessage(), OSCFormatError);
  798. }
  799. }
  800. beginTest ("reading OSC messages (handling messages without type tag strings)");
  801. {
  802. {
  803. uint8 data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0' };
  804. OSCInputStream inStream (data, sizeof (data));
  805. expectThrowsType (inStream.readMessage(), OSCFormatError);
  806. }
  807. {
  808. uint8 data[] = {
  809. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  810. 0xFF, 0xFF, 0xF8, 0x21,
  811. 0x43, 0xAC, 0xCE, 0x66,
  812. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  813. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  814. };
  815. OSCInputStream inStream (data, sizeof (data));
  816. expectThrowsType (inStream.readMessage(), OSCFormatError);
  817. }
  818. }
  819. beginTest ("reading OSC bundles");
  820. {
  821. // valid bundle (empty)
  822. {
  823. uint8 data[] = {
  824. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  825. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
  826. };
  827. OSCInputStream inStream (data, sizeof (data));
  828. OSCBundle bundle = inStream.readBundle();
  829. expect (bundle.getTimeTag().isImmediately());
  830. expect (bundle.size() == 0);
  831. }
  832. // valid bundle (containing both messages and other bundles)
  833. {
  834. int32 testInt = -2015;
  835. float testFloat = 345.6125f;
  836. String testString = "Hello, World!";
  837. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  838. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  839. uint8 data[] = {
  840. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  841. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  842. 0x00, 0x00, 0x00, 0x34,
  843. '/', 't', 'e', 's', 't', '/', '1', '\0',
  844. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  845. 0xFF, 0xFF, 0xF8, 0x21,
  846. 0x43, 0xAC, 0xCE, 0x66,
  847. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  848. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00,
  849. 0x00, 0x00, 0x00, 0x0C,
  850. '/', 't', 'e', 's', 't', '/', '2', '\0',
  851. ',', '\0', '\0', '\0',
  852. 0x00, 0x00, 0x00, 0x10,
  853. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  854. 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
  855. };
  856. OSCInputStream inStream (data, sizeof (data));
  857. OSCBundle bundle = inStream.readBundle();
  858. expect (bundle.getTimeTag().isImmediately());
  859. expect (bundle.size() == 3);
  860. OSCBundle::Element* elements = bundle.begin();
  861. expect (elements[0].isMessage());
  862. expect (elements[0].getMessage().getAddressPattern().toString() == "/test/1");
  863. expect (elements[0].getMessage().size() == 4);
  864. expect (elements[0].getMessage()[0].isInt32());
  865. expect (elements[0].getMessage()[1].isFloat32());
  866. expect (elements[0].getMessage()[2].isString());
  867. expect (elements[0].getMessage()[3].isBlob());
  868. expectEquals (elements[0].getMessage()[0].getInt32(), testInt);
  869. expectEquals (elements[0].getMessage()[1].getFloat32(), testFloat);
  870. expectEquals (elements[0].getMessage()[2].getString(), testString);
  871. expect (elements[0].getMessage()[3].getBlob() == testBlob);
  872. expect (elements[1].isMessage());
  873. expect (elements[1].getMessage().getAddressPattern().toString() == "/test/2");
  874. expect (elements[1].getMessage().size() == 0);
  875. expect (elements[2].isBundle());
  876. expect (! elements[2].getBundle().getTimeTag().isImmediately());
  877. }
  878. // invalid bundles.
  879. {
  880. uint8 data[] = {
  881. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  882. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  883. 0x00, 0x00, 0x00, 0x34, // wrong bundle element size (too large)
  884. '/', 't', 'e', 's', 't', '/', '1', '\0',
  885. ',', 's', '\0', '\0',
  886. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0'
  887. };
  888. OSCInputStream inStream (data, sizeof (data));
  889. expectThrowsType (inStream.readBundle(), OSCFormatError);
  890. }
  891. {
  892. uint8 data[] = {
  893. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  894. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  895. 0x00, 0x00, 0x00, 0x08, // wrong bundle element size (too small)
  896. '/', 't', 'e', 's', 't', '/', '1', '\0',
  897. ',', 's', '\0', '\0',
  898. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0'
  899. };
  900. OSCInputStream inStream (data, sizeof (data));
  901. expectThrowsType (inStream.readBundle(), OSCFormatError);
  902. }
  903. {
  904. uint8 data[] = {
  905. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  906. 0x00, 0x00, 0x00, 0x00 // incomplete time tag
  907. };
  908. OSCInputStream inStream (data, sizeof (data));
  909. expectThrowsType (inStream.readBundle(), OSCFormatError);
  910. }
  911. {
  912. uint8 data[] = {
  913. '#', 'b', 'u', 'n', 'x', 'l', 'e', '\0', // wrong initial string
  914. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  915. };
  916. OSCInputStream inStream (data, sizeof (data));
  917. expectThrowsType (inStream.readBundle(), OSCFormatError);
  918. }
  919. {
  920. uint8 data[] = {
  921. '#', 'b', 'u', 'n', 'd', 'l', 'e', // padding missing from string
  922. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  923. };
  924. OSCInputStream inStream (data, sizeof (data));
  925. expectThrowsType (inStream.readBundle(), OSCFormatError);
  926. }
  927. }
  928. }
  929. };
  930. static OSCInputStreamTests OSCInputStreamUnitTests;
  931. #endif
  932. } // namespace juce