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.

1193 lines
44KB

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